Merge pull request #50 from SnowLuma/dev

chore: promote dev → main (941e60d)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-05-18 07:04:16 +00:00
commit fe567caeec
26 files changed
+1670 -667

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/core",
"version": "1.8.4",
"version": "1.8.5",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -66,6 +66,9 @@ export async function getStrangerStatus(bridge: Bridge, uin: number): Promise<St
request: {
schema: OidbStrangerStatusReqSchema,
value: { uin, key: [{ key: 27372 }] },
// Same UIN-form flag fetchUserProfile sets — without it newer
// QQ NT rejects with `[oidb] one of uid/openid is invaild`.
isUid: true,
},
response: { schema: OidbStrangerStatusRespSchema },
});
+25 -5
View File
@@ -103,6 +103,19 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
// ---------------------------------------------------------------------------
export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
// The config flags ask QQ which per-group fields to include in the
// response. Asking for everything looks innocent on small accounts
// but on ~200+ groups it makes the QQ NT process write a payload
// large enough to blow the named-pipe write buffer — we then read
// EPIPE and the whole session dies. See issue #42.
//
// The user-verified safe combination: keep `config1.*` mostly on
// (the response decoder pulls groupOwner / memberMax / memberCount /
// groupName / description / question / announcement from this
// group), but turn off the costly groups of bools that never map
// back to a decoded field:
// - config1.field5002, field5003 (expansive 5xxx-range descriptors)
// - all of config2 (auxiliary per-group blob the decoder ignores)
const allTrue = true;
const body = {
config: {
@@ -114,11 +127,11 @@ export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: allTrue,
field32: allTrue, field5001: allTrue, field5002: false, field5003: false,
},
config2: {
field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue,
field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue,
field1: false, field2: false, field3: false, field4: false,
field5: false, field6: false, field7: false, field8: false,
},
config3: { field5: allTrue, field6: allTrue },
},
@@ -208,16 +221,23 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<UserProfileInfo> {
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
// Only `uin` and `keys` — see OidbUserInfoRequestSchema for why
// sending field 2 makes the server reject the request.
const body = {
uin,
field2: 0,
keys: keys.map(k => ({ key: k })),
};
// Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the
// name is historical, the wire semantic is "this is the UIN-form
// variant of the call"). Without it newer QQ NT versions take the
// UID-form validation path, find neither uid nor openid in the body
// and bounce the request with `[oidb] one of uid/openid is invaild`.
// Matches Lagrange.Core's FetchStrangerByUin (Reserved = 1).
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: { schema: OidbUserInfoRequestSchema, value: body },
request: { schema: OidbUserInfoRequestSchema, value: body, isUid: true },
response: { schema: OidbUserInfoResponseSchema },
});
+10 -4
View File
@@ -20,10 +20,16 @@ export interface OidbCall<TResp = void> {
schema: ProtoSchema;
value: any;
/**
* Sets the OIDB envelope `reserved` field to 1 when true. A handful
* of commands (group/friend list, rkey download) operate on
* UID-keyed data and require this flag — the wire format is
* otherwise identical.
* Sets the OIDB envelope `reserved` field to 1 when true.
*
* The name is historical and misleading: empirically (see Lagrange
* FetchStrangerByUin vs FetchStrangerByUid, fetchGroupList, our own
* highway uploads) the `reserved = 1` flag indicates the UIN-form
* variant of an OIDB call — it tells newer QQ NT to translate the
* UIN in the body to an internal UID rather than running the
* UID-form validator that expects a uid/openid string in the body.
*
* Omit (default false) for genuinely UID-keyed calls.
*/
isUid?: boolean;
};
+18 -1
View File
@@ -230,6 +230,22 @@ export interface FriendAddEvent extends QQEvent {
userUin: number;
}
export interface GroupMsgEmojiLikeEvent extends QQEvent {
kind: 'group_msg_emoji_like';
groupId: number;
operatorUin: number;
operatorUid: string;
/** Sequence of the message that was reacted to (server-assigned msg_seq). */
msgSeq: number;
/** Emoji ID. QQ system faces are short numeric strings; market faces
* are alphanumeric. We keep the wire string verbatim. */
emojiId: string;
/** Multiplicity of the reaction event. Usually 1. */
count: number;
/** True when the reaction is being added; false when removed. */
isAdd: boolean;
}
export type QQEventVariant =
| FriendMessage
| GroupMessage
@@ -246,4 +262,5 @@ export type QQEventVariant =
| GroupPokeEvent
| GroupEssenceEvent
| GroupFileUploadEvent
| FriendAddEvent;
| FriendAddEvent
| GroupMsgEmojiLikeEvent;
@@ -1,12 +1,14 @@
// Handles Event0x2DC wrapper (732). Internal switch on subType dispatches
// to GroupMute (12) / GroupRecall (17) / GroupGreyTip (20) / GroupEssence (21).
// to GroupMute (12) / GroupMsgEmojiLike (16) / GroupRecall (17) /
// GroupGreyTip (20) / GroupEssence (21).
import { protoDecode } from '../../../protobuf/decode';
import {
GroupMuteSchema, NotifyMessageBodySchema,
GroupMuteSchema, NotifyMessageBodySchema, GroupReactNotifySchema,
} from '../../proto/notify';
import type {
GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent,
GroupMsgEmojiLikeEvent,
QQEventVariant,
} from '../../events';
import type { MsgPushDecoder } from '../registry';
@@ -23,6 +25,7 @@ const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x2DCSubType) {
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx);
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
@@ -108,3 +111,51 @@ function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
};
return [ev];
}
// Magic prefix QQ prepends to the GroupReactNotify payload inside
// body.msgContent for Event0x2DC subType=16. Same value NapCat strips
// (see api/group.ts: `msgContent?.slice(7)`).
const GROUP_REACT_PREFIX_BYTES = 7;
// Discriminator on GroupReactNotify.field13 — same subType is reused
// for other notify variants, only 35 means "emoji react". Anything
// else falls through to MsgPush.Unknown for protocol-drift visibility.
const GROUP_REACT_DISCRIMINATOR = 35;
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
const notify = protoDecode(payload, GroupReactNotifySchema);
if (!notify) return [];
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
notify.field13 ?? 0, GROUP_REACT_DISCRIMINATOR);
return [];
}
const content = notify.groupReactionData?.data?.data?.groupReactionDataContent;
const target = notify.groupReactionData?.data?.data?.groupReactionTarget;
if (!content) return [];
const groupId = Number(notify.groupUin ?? 0n);
const operatorUid = content.operatorUid ?? '';
const emojiId = content.code ?? '';
const count = content.count ?? 1;
// type is QQ's add/remove discriminator: 1 = react added, 2 = react
// removed. Older payloads occasionally omit it; default to "add"
// since most clients can only generate add events.
const isAdd = (content.type ?? 1) === 1;
const msgSeq = Number(target?.seq ?? 0n);
const ev: GroupMsgEmojiLikeEvent = {
kind: 'group_msg_emoji_like',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, ctx.fromUin),
operatorUid,
msgSeq,
emojiId,
count,
isAdd,
};
return [ev];
}
@@ -21,6 +21,7 @@ export enum PkgType {
export enum Event0x2DCSubType {
GroupMuteNotice = 12,
GroupMsgEmojiLikeNotice = 16,
GroupRecallNotice = 17,
GroupGreyTipNotice = 20,
GroupEssenceNotice = 21,
+38
View File
@@ -205,3 +205,41 @@ export const NotifyMessageBodySchema = {
msgSequence: { field: 37, type: 'uint32' as const },
field39: { field: 39, type: 'uint32' as const },
} satisfies ProtoSchema;
// ─── Event0x2DC subType=16: GroupMsgEmojiLike ──────────────────────────────
//
// QQ pushes a Group message emoji reaction (someone tapped an emoji on a
// message in a group). The payload nesting matches NapCat's transformer
// (packet/transformer/proto/message/message.ts → GroupReactNotify); the
// outermost message is preceded by a 7-byte prefix that must be stripped
// before decoding (see the call site).
export const GroupReactionDataInnerDataTargetSchema = {
seq: { field: 1, type: 'uint64' as const },
} satisfies ProtoSchema;
export const GroupReactionDataContentSchema = {
code: { field: 1, type: 'string' as const },
count: { field: 3, type: 'uint32' as const },
operatorUid: { field: 4, type: 'string' as const },
type: { field: 5, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GroupReactionDataInnerDataSchema = {
groupReactionTarget: { field: 2, type: 'message' as const, schema: GroupReactionDataInnerDataTargetSchema },
groupReactionDataContent: { field: 3, type: 'message' as const, schema: GroupReactionDataContentSchema },
} satisfies ProtoSchema;
export const GroupReactionDataInnerSchema = {
data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerDataSchema },
} satisfies ProtoSchema;
export const GroupReactionDataSchema = {
data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerSchema },
} satisfies ProtoSchema;
export const GroupReactNotifySchema = {
groupUin: { field: 4, type: 'uint64' as const },
field13: { field: 13, type: 'uint32' as const },
groupReactionData: { field: 44, type: 'message' as const, schema: GroupReactionDataSchema },
} satisfies ProtoSchema;
@@ -190,10 +190,14 @@ export const OidbUserInfoKeySchema = {
key: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
// Field 2 USED to be `field2: uint32 = 0`, but newer QQ NT versions
// reinterpret field 2 as `uid: string` / `openid: string` and reject
// the request with "one of uid/openid is invaild" when a varint 0
// shows up there. NapCat's schema (Oidb.0XFE1_2.ts) only emits `uin`
// and `key[]`, so we match that exactly.
export const OidbUserInfoRequestSchema = {
uin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
uin: { field: 1, type: 'uint32' as const },
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
} satisfies ProtoSchema;
export const OidbTwoNumberSchema = {
@@ -23,6 +23,7 @@ import {
convertGroupFileUpload,
convertGroupMemberJoin,
convertGroupMemberLeave,
convertGroupMsgEmojiLike,
convertGroupMute,
convertGroupPoke,
convertGroupRecall,
@@ -98,6 +99,7 @@ export async function convertEvent(
case 'group_essence': return convertGroupEssence(ctx, event);
case 'group_file_upload': return convertGroupFileUpload(ctx, event);
case 'friend_add': return convertFriendAdd(ctx, event);
case 'group_msg_emoji_like': return convertGroupMsgEmojiLike(ctx, event);
// Requests.
case 'friend_request': return convertFriendRequest(ctx, event);
@@ -21,6 +21,7 @@ type GroupPoke = Extract<QQEventVariant, { kind: 'group_poke' }>;
type GroupEssence = Extract<QQEventVariant, { kind: 'group_essence' }>;
type GroupFileUpload = Extract<QQEventVariant, { kind: 'group_file_upload' }>;
type FriendAdd = Extract<QQEventVariant, { kind: 'friend_add' }>;
type GroupMsgEmojiLike = Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>;
export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject {
return {
@@ -187,3 +188,32 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO
user_id: event.userUin,
};
}
/**
* Group message emoji reaction notice. Matches the gocqhttp / NapCat
* extension shape (`notice_type: 'group_msg_emoji_like'`) since OneBot
* v11 standard has no slot for reactions and that's what every
* downstream framework keys off.
*/
export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject {
// Reconstruct the OneBot message_id we originally minted for the
// reacted-to message. hashMessageIdInt32 is deterministic so the ID
// matches whatever the client received at receive-time, even when
// the message has fallen out of our store.
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_msg_emoji_like',
sub_type: event.isAdd ? 'add' : 'remove',
group_id: event.groupId,
user_id: event.operatorUin,
operator_id: event.operatorUin,
message_id: messageId,
message_seq: event.msgSeq,
likes: [{ emoji_id: event.emojiId, count: event.count }],
};
}
@@ -73,6 +73,7 @@ const NOTICE_KINDS = [
'group_essence',
'group_file_upload',
'friend_add',
'group_msg_emoji_like',
] as const satisfies readonly QQEventVariant['kind'][];
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
+2
View File
@@ -198,6 +198,8 @@ export function formatEvent(identity: IdentityService, event: QQEventVariant): s
return `群邀请 ${formatUser(identity, undefined, event.fromUin)} -> ${formatGroup(identity, event.groupId)}`;
case 'group_essence':
return `精华 ${formatGroup(identity, event.groupId)} | ${event.set ? '+' : '-'}精华`;
case 'group_msg_emoji_like':
return `表情回应 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.operatorUin, event.operatorUid)} ${event.isAdd ? '+' : '-'}[${event.emojiId}] msgSeq=${event.msgSeq}`;
default:
return null;
}
@@ -0,0 +1,213 @@
// Tests for the Event0x2DC subType=16 (GroupMsgEmojiLike) end-to-end:
// - decoder strips the 7-byte prefix and decodes GroupReactNotify
// - field13==35 yields a GroupMsgEmojiLikeEvent
// - field13!=35 surfaces under MsgPush.Unknown and emits nothing
// - converter shape matches the gocqhttp / NapCat extension layout
// - formatEvent prints something readable in the [Event] log
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { protoEncode } from '../src/protobuf/decode';
import { GroupReactNotifySchema } from '../src/bridge/proto/notify';
import { decodeEvent0x2DC } from '../src/bridge/msg-push/decoders/event-0x2dc';
import type { MsgPushContext } from '../src/bridge/msg-push/context';
import { IdentityService } from '../src/bridge/identity-service';
import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '../src/bridge/events';
import { convertGroupMsgEmojiLike } from '../src/onebot/event-converter/to-notice';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../src/onebot/message-id';
import { formatEvent } from '../src/utils/event-format';
import { subscribeLogs, type LogEntry } from '../src/utils/logger';
const SELF_UIN = '10001';
const GROUP_ID = 123456789;
function makeIdentity(): IdentityService {
return IdentityService.memory(SELF_UIN);
}
/** Build the raw bytes QQ would push into ctx.content for subType=16:
* a 7-byte magic prefix followed by an encoded GroupReactNotify. */
function buildReactContent(notify: Record<string, unknown>): Uint8Array {
const prefix = new Uint8Array([0, 0, 0, 0, 0, 0, 0]);
const body = protoEncode(notify as never, GroupReactNotifySchema);
const out = new Uint8Array(prefix.length + body.length);
out.set(prefix, 0);
out.set(body, prefix.length);
return out;
}
function makeCtx(content: Uint8Array, identity = makeIdentity()): MsgPushContext {
return {
head: { msgType: 732, subType: 16, sequence: 0, timestamp: 1735000000, msgId: 0 },
fromUin: 0,
fromUid: '',
selfUin: Number(SELF_UIN),
content,
body: undefined,
responseHead: undefined,
identity,
};
}
describe('decodeEvent0x2DC subType=16 — GroupMsgEmojiLike', () => {
it('decodes a field13=35 react add into a GroupMsgEmojiLikeEvent', () => {
const content = buildReactContent({
groupUin: BigInt(GROUP_ID),
field13: 35,
groupReactionData: {
data: {
data: {
groupReactionTarget: { seq: 4242n },
groupReactionDataContent: {
code: '76',
count: 1,
operatorUid: 'u_operator_xxx',
type: 1, // add
},
},
},
},
});
const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[];
expect(event).toBeDefined();
expect(event.kind).toBe('group_msg_emoji_like');
expect(event.groupId).toBe(GROUP_ID);
expect(event.operatorUid).toBe('u_operator_xxx');
expect(event.emojiId).toBe('76');
expect(event.msgSeq).toBe(4242);
expect(event.count).toBe(1);
expect(event.isAdd).toBe(true);
});
it('decodes type=2 as react remove (isAdd=false)', () => {
const content = buildReactContent({
groupUin: BigInt(GROUP_ID),
field13: 35,
groupReactionData: {
data: {
data: {
groupReactionTarget: { seq: 1n },
groupReactionDataContent: {
code: '⭐',
count: 1,
operatorUid: 'u_x',
type: 2,
},
},
},
},
});
const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[];
expect(event.isAdd).toBe(false);
expect(event.emojiId).toBe('⭐');
});
it('drops the packet and logs to MsgPush.Unknown when field13 is not 35', () => {
const captured: LogEntry[] = [];
const unsub = subscribeLogs((e) => captured.push(e));
const content = buildReactContent({
groupUin: BigInt(GROUP_ID),
field13: 99, // not 35
groupReactionData: {
data: { data: { groupReactionDataContent: { code: 'x', operatorUid: 'u_y' } } },
},
});
const result = decodeEvent0x2DC(makeCtx(content));
unsub();
expect(result).toHaveLength(0);
const unknown = captured.find((e) =>
e.scope === 'MsgPush.Unknown' && /field13=99/.test(e.message));
expect(unknown).toBeDefined();
});
it('returns empty when content is shorter than the prefix length', () => {
const tooShort = new Uint8Array([1, 2, 3]); // < 7 bytes
expect(decodeEvent0x2DC(makeCtx(tooShort))).toEqual([]);
});
});
describe('convertGroupMsgEmojiLike — OneBot notice shape', () => {
const baseEvent: GroupMsgEmojiLikeEvent = {
kind: 'group_msg_emoji_like',
time: 1735000000,
selfUin: 10001,
groupId: 123456789,
operatorUin: 99999,
operatorUid: 'u_x',
msgSeq: 4242,
emojiId: '76',
count: 1,
isAdd: true,
};
// Real production wiring puts a hashMessageIdInt32-based resolver
// on the ctx; mirror that so message_id is the same value the
// bot would have minted for the original message.
const ctx = {
selfId: 10001,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: (_isGroup: boolean, sessionId: number, sequence: number, eventName: string) =>
hashMessageIdInt32(sequence, sessionId, eventName),
mediaSegmentSink: null,
} as never;
it('produces a group_msg_emoji_like notice with sub_type=add and resolved message_id', () => {
const out = convertGroupMsgEmojiLike(ctx, baseEvent);
expect(out.post_type).toBe('notice');
expect(out.notice_type).toBe('group_msg_emoji_like');
expect(out.sub_type).toBe('add');
expect(out.group_id).toBe(123456789);
expect(out.user_id).toBe(99999);
expect(out.operator_id).toBe(99999);
expect(out.message_seq).toBe(4242);
expect(out.message_id).toBe(hashMessageIdInt32(4242, 123456789, GROUP_MESSAGE_EVENT));
expect(out.likes).toEqual([{ emoji_id: '76', count: 1 }]);
});
it('flips sub_type to remove when isAdd is false', () => {
const out = convertGroupMsgEmojiLike(ctx, { ...baseEvent, isAdd: false });
expect(out.sub_type).toBe('remove');
});
});
describe('formatEvent — group_msg_emoji_like', () => {
let savedLevel: string | undefined;
beforeEach(() => { savedLevel = process.env.SNOWLUMA_LOG_LEVEL; });
afterEach(() => {
if (savedLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
else process.env.SNOWLUMA_LOG_LEVEL = savedLevel;
});
it('renders a one-line summary with group, operator and emoji id', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([{
groupId: GROUP_ID, groupName: 'TestGroup', remark: '',
memberCount: 1, memberMax: 500, members: new Map(),
}]);
identity.rememberGroupMembers(GROUP_ID, [{
uin: 99999, uid: 'u_x', nickname: 'Alice', card: '',
role: 'member', level: 0, title: '',
joinTime: 0, lastSentTime: 0, shutUpTime: 0,
}]);
const event: QQEventVariant = {
kind: 'group_msg_emoji_like',
time: 0, selfUin: Number(SELF_UIN),
groupId: GROUP_ID,
operatorUin: 99999, operatorUid: 'u_x',
msgSeq: 100, emojiId: '76', count: 1, isAdd: true,
};
const line = formatEvent(identity, event);
expect(line).toBeDefined();
expect(line).toContain('TestGroup');
expect(line).toContain('Alice');
expect(line).toContain('[76]');
expect(line).toContain('msgSeq=100');
});
});