fix(protocol): decode group member operators correctly

Handle member joins and ordinary removals using their direct operator identity while preserving the special nested form used when the bot is removed.

Reject malformed values with bounded diagnostic context and add regression coverage for #228 and related member-decrease events.
This commit is contained in:
DrSmoothl committed 2026-07-14 20:08:29 +08:00
1 parent a3467a8d89
commit f9d251d1fa
3 files changed
+153 -12

No files matched your search

+91 -5
View File
@@ -66,10 +66,12 @@ function makeIdentity(members: GroupMemberInfo[] = []): IdentityService {
return identity;
}
function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin = GROUP_ID): PacketInfo {
const operatorBytes = operatorUid
? protobuf_encode<OperatorInfo>({ operatorField: { uid: operatorUid } })
: new Uint8Array(0);
function makeGroupIncreasePacket(
memberUid: string,
operatorUid = '',
fromUin = GROUP_ID,
operatorBytes: Uint8Array = Buffer.from(operatorUid, 'utf8'),
): PacketInfo {
const content = protobuf_encode<GroupChange>({
groupUin: GROUP_ID,
memberUid,
@@ -95,6 +97,38 @@ function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin =
};
}
function makeGroupDecreasePacket(
memberUid: string,
decreaseType: number,
operatorBytes: Uint8Array,
fromUin = GROUP_ID,
): PacketInfo {
const content = protobuf_encode<GroupChange>({
groupUin: GROUP_ID,
memberUid,
decreaseType,
operatorBytes,
});
const body = protobuf_encode<PushMsg>({
message: {
responseHead: { fromUin },
contentHead: { msgType: 34, timestamp: 1710000000 },
body: { msgContent: content },
},
status: 0,
});
return {
pid: 1,
uin: SELF_UIN,
serviceCmd: MSG_PUSH_CMD,
seqId: 1,
retCode: 0,
fromClient: false,
body,
};
}
describe('parseMsgPush group member increase', () => {
it('does not fall back to the group id when a joining uid is unresolved', () => {
const [event] = parseMsgPush(makeGroupIncreasePacket('u_new_member'), makeIdentity()) as GroupMemberJoin[];
@@ -106,7 +140,7 @@ describe('parseMsgPush group member increase', () => {
expect(event.userUid).toBe('u_new_member');
});
it('resolves joining uid and operator uid from the member cache when available', () => {
it('decodes the raw operator uid used by member-increase pushes (#228)', () => {
const member = makeGroupMember(22222, 'u_member');
const operator = makeGroupMember(33333, 'u_operator');
const [event] = parseMsgPush(
@@ -119,6 +153,58 @@ describe('parseMsgPush group member increase', () => {
expect(event.userUid).toBe(member.uid);
expect(event.operatorUid).toBe(operator.uid);
});
it('reports malformed raw operator bytes with bounded context', () => {
const captured: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'MsgPush') captured.push(entry.message);
});
try {
const events = parseMsgPush(
makeGroupIncreasePacket('u_new_member', '', GROUP_ID, new Uint8Array([0xff])),
makeIdentity(),
);
expect(events).toEqual([]);
expect(captured.some((message) =>
message.includes('group member increase operator UID')
&& message.includes('bytes=1')
&& message.includes('preview=ff'))).toBe(true);
} finally {
unsubscribe();
}
});
});
describe('parseMsgPush group member decrease', () => {
it('decodes a raw operator uid for ordinary member removals', () => {
const member = makeGroupMember(22222, 'u_member');
const operator = makeGroupMember(33333, 'u_operator');
const [event] = parseMsgPush(
makeGroupDecreasePacket(member.uid, 131, Buffer.from(operator.uid, 'utf8')),
makeIdentity([member, operator]),
) as Extract<QQEventVariant, { kind: 'group_member_leave' }>[];
expect(event.userUin).toBe(member.uin);
expect(event.operatorUin).toBe(operator.uin);
expect(event.operatorUid).toBe(operator.uid);
expect(event.leaveType).toBe('kick');
});
it('decodes nested operator info when the bot itself is kicked', () => {
const operator = makeGroupMember(33333, 'u_operator');
const operatorBytes = protobuf_encode<OperatorInfo>({
operatorField: { uid: operator.uid },
});
const [event] = parseMsgPush(
makeGroupDecreasePacket('u_self', 3, operatorBytes),
makeIdentity([operator]),
) as Extract<QQEventVariant, { kind: 'group_member_leave' }>[];
expect(event.operatorUin).toBe(operator.uin);
expect(event.operatorUid).toBe(operator.uid);
expect(event.leaveType).toBe('kick');
});
});
describe('parseMsgPush Event0x210 subType=38 (acknowledged-but-silent)', () => {
@@ -1,7 +1,7 @@
import { protobuf_decode } from '@snowluma/proton';
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify';
import { decodeOperatorUid, resolveUidToUin } from '../helpers';
import { decodeNestedOperatorUid, decodeRawOperatorUid, resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
@@ -9,7 +9,10 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
if (!change) return [];
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
const operatorUid = decodeRawOperatorUid(
change.operatorBytes ?? new Uint8Array(0),
'group member increase',
);
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
@@ -49,7 +52,12 @@ export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
const dt = change.decreaseType ?? 0;
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0));
const operatorBytes = change.operatorBytes ?? new Uint8Array(0);
// QQ sends the operator as a raw UTF-8 UID for normal member changes.
// Only the bot-self-kicked variant (decreaseType=3) wraps it in OperatorInfo.
const operatorUid = dt === 3
? decodeNestedOperatorUid(operatorBytes, 'group member decrease type=3')
: decodeRawOperatorUid(operatorBytes, `group member decrease type=${dt}`);
const ev: GroupMemberLeave = {
kind: 'group_member_leave',
time: ctx.head.timestamp,
+51 -4
View File
@@ -1,4 +1,5 @@
import { protobuf_decode } from '@snowluma/proton';
import { hexPreview } from '@snowluma/common/hex';
import { inflateSync } from 'zlib';
import type { IdentityService } from '../identity-service';
import type { OperatorInfo } from '@snowluma/proto-defs/notify';
@@ -85,11 +86,57 @@ export function resolveUidToUin(identity: IdentityService, groupId: number, uid:
return fallback;
}
export function decodeOperatorUid(bytes: Uint8Array): string {
const OPERATOR_BYTES_PREVIEW_LENGTH = 32;
function describeOperatorBytes(bytes: Uint8Array): string {
return `bytes=${bytes.length} preview=${hexPreview(bytes, OPERATOR_BYTES_PREVIEW_LENGTH)}`;
}
function hasControlCharacter(value: string): boolean {
for (const char of value) {
const codePoint = char.codePointAt(0);
if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f)) return true;
}
return false;
}
function assertOperatorUid(uid: string, context: string, bytes: Uint8Array): string {
if (hasControlCharacter(uid)) {
throw new Error(`${context} operator UID contains control characters (${describeOperatorBytes(bytes)})`);
}
return uid;
}
export function decodeRawOperatorUid(bytes: Uint8Array, context: string): string {
if (!bytes || bytes.length === 0) return '';
const info = protobuf_decode<OperatorInfo>(bytes);
if (info?.operatorField?.uid) return info.operatorField.uid;
return Buffer.from(bytes).toString('utf8');
let uid: string;
try {
uid = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
} catch (error) {
throw new Error(
`${context} operator UID is not valid UTF-8 (${describeOperatorBytes(bytes)})`,
{ cause: error },
);
}
return assertOperatorUid(uid, context, bytes);
}
export function decodeNestedOperatorUid(bytes: Uint8Array, context: string): string {
if (!bytes || bytes.length === 0) return '';
let info: OperatorInfo | null;
try {
info = protobuf_decode<OperatorInfo>(bytes);
} catch (error) {
throw new Error(
`${context} operator info decode failed (${describeOperatorBytes(bytes)})`,
{ cause: error },
);
}
const uid = info?.operatorField?.uid;
if (!uid) {
throw new Error(`${context} operator info is missing UID (${describeOperatorBytes(bytes)})`);
}
return assertOperatorUid(uid, context, bytes);
}
export function buildTemplateMap(params: Array<{ name?: string; value?: string }>): Map<string, string> {