diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index ff9fa610..aeca9979 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -3,7 +3,7 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sen import type { PacketInfo } from '@snowluma/common/protocol-types'; import { BridgeEventBus } from '@snowluma/protocol/event-bus'; import { IdentityService } from '@snowluma/protocol/identity-service'; -import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push'; +import { MSG_PUSH_CMD, parseMsgPush, SysMsgDedup } from '@snowluma/protocol/msg-push'; import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline'; import { buildApiHub, type ApiHub } from './apis'; import { @@ -26,6 +26,8 @@ export class Bridge implements BridgeInterface { private uploadedFileMeta_ = new Map(); private clientSeq_ = 100000000 + (Date.now() % 1000000000); private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0; + // Per-account dedup for QQ NT's already-deduped system pushes (#137). + private readonly sysMsgDedup_ = new SysMsgDedup(); constructor(identity: IdentityService) { this.identity = identity; @@ -62,7 +64,7 @@ export class Bridge implements BridgeInterface { } }, }); - this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush); + this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) => parseMsgPush(pkt, identity, this.sysMsgDedup_)); } dispose(): void { diff --git a/packages/protocol/src/msg-push/index.ts b/packages/protocol/src/msg-push/index.ts index db94638d..2c7804f8 100644 --- a/packages/protocol/src/msg-push/index.ts +++ b/packages/protocol/src/msg-push/index.ts @@ -21,6 +21,9 @@ import { decodeGroupMessage } from './decoders/group-message'; import { decodeTempMessage } from './decoders/temp-message'; import { PkgType } from './enums'; import { MsgPushRegistry } from './registry'; +import { SysMsgDedup } from './sysmsg-dedup'; + +export { SysMsgDedup } from './sysmsg-dedup'; export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history'; export { SSO_GET_C2C_MSG_CMD, fetchC2cMessageRange } from './fetch-c2c-history'; @@ -80,11 +83,15 @@ function describeUndecodedBody(body: PushMsgBody | undefined): string { return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`; } -export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEventVariant[] { +export function parseMsgPush( + pkt: PacketInfo, + identity: IdentityService, + dedup?: SysMsgDedup, +): QQEventVariant[] { const ctx = buildContext(pkt, identity); if (!ctx) return []; const events = registry.decode(ctx); - return events.filter((ev) => { + const out = events.filter((ev) => { if (!MESSAGE_KINDS.has(ev.kind)) return true; // C2C control/system signal (#102): QQ NT routes these via OnRecvSysMsg and // never shows them as a bubble. Drop by (msgType, c2cCmd) regardless of body @@ -111,4 +118,21 @@ export function parseMsgPush(pkt: PacketInfo, identity: IdentityService): QQEven } return false; }); + + // #137: mirror QQ NT `sys_msg_mgr.cc::ProcessRecvSysMsg` global-key dedup. + // The server pushes some system notices twice (e.g. inviting an official + // robot → two `group_member_increase`); the kernel drops the duplicate by + // (peer, seq, random) before any listener sees it, but we read the raw + // OlPush, so we replicate the drop. Scoped to system pushes only — chat + // messages have their own NT dedup path and the forward re-parse re-runs + // this without a tracker. A push that decodes to a message kind, or to + // nothing, is never deduped here. + if (dedup && out.length > 0 && out.every((ev) => !MESSAGE_KINDS.has(ev.kind))) { + if (dedup.seenDuplicate(ctx.head, ctx.fromUin)) { + log.debug('dropped duplicate system push (kinds=%s seq=%d from=%d msgType=%d msgId=%d)', + out.map((ev) => ev.kind).join(','), ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.msgId); + return []; + } + } + return out; } diff --git a/packages/protocol/src/msg-push/sysmsg-dedup.ts b/packages/protocol/src/msg-push/sysmsg-dedup.ts new file mode 100644 index 00000000..857a3fa0 --- /dev/null +++ b/packages/protocol/src/msg-push/sysmsg-dedup.ts @@ -0,0 +1,59 @@ +import type { MsgPushHead } from './context'; + +/** + * Mirrors QQ NT's system-message dedup so SnowLuma stops double-reporting the + * duplicate sys pushes the server emits for some events (#137: inviting an + * official robot pushes the `group_member_increase` notice twice → two + * `notice.group_increase`; a normal member is pushed once). + * + * RE of `wrapper.linux.node` — `sys_msg_mgr.cc::ProcessRecvSysMsg` + * (`sub_37BADE0`): every received system message is keyed and looked up in a + * per-account set; an already-seen key is logged ("on recv sys msg, ignore dup + * msg … global_key={}", sys_msg_mgr.cc:467) and the whole message is dropped + * before the UI / JS listeners ever see it. The key (`sub_37BC4E0`) is + * + * global_key = `{peerUid}_{chatType}_{msg_seq}_{random}` + * + * whose per-message discriminators are `msg_seq` (attr 40003 = contentHead + * field 5) and `random` (attr 40002 = contentHead field 4) — exactly + * {@link MsgPushHead.sequence} and {@link MsgPushHead.msgId} here + * (`msg_header_codec_helper.cc` sub_37C8AD0). Kernel-based bots (NapCat / + * LLOneBot) receive events *after* this dedup; SnowLuma reads the raw OlPush + * *before* it, so we replicate it here. + * + * We dedup at the push level (drop the whole duplicate, like NT) using the + * fields already on the head plus `fromUin` for peer scoping (a stand-in for + * peerUid — `msg_seq` can be per-conversation, so the peer keeps two groups' + * pushes from colliding; `random`/`msgId` makes the collision astronomically + * unlikely anyway). A push with no server identity (`sequence` or `msgId` 0) is + * never deduped — without a real per-message id we cannot distinguish a true + * duplicate from two distinct events, and dropping then would be a regression. + */ +export class SysMsgDedup { + private readonly seen = new Set(); + // Fixed-capacity ring of keys for O(1) bounded eviction (oldest-out). System + // pushes are low-frequency, so a duplicate always lands within a few entries + // of its original — eviction only matters far beyond the dup window. + private readonly ring: (string | undefined)[]; + private cursor = 0; + + constructor(private readonly capacity = 1024) { + this.ring = new Array(capacity); + } + + /** + * Returns true if a system push with this identity was already seen (caller + * should drop it); otherwise records it and returns false. + */ + seenDuplicate(head: Pick, fromUin: number): boolean { + if (head.sequence === 0 || head.msgId === 0) return false; + const key = `${head.msgType}:${head.subType}:${fromUin}:${head.sequence}:${head.msgId}`; + if (this.seen.has(key)) return true; + const evicted = this.ring[this.cursor]; + if (evicted !== undefined) this.seen.delete(evicted); + this.ring[this.cursor] = key; + this.seen.add(key); + this.cursor = (this.cursor + 1) % this.capacity; + return false; + } +} diff --git a/packages/protocol/tests/msg-push/sysmsg-dedup.test.ts b/packages/protocol/tests/msg-push/sysmsg-dedup.test.ts new file mode 100644 index 00000000..31b6b760 --- /dev/null +++ b/packages/protocol/tests/msg-push/sysmsg-dedup.test.ts @@ -0,0 +1,118 @@ +// Regression for #137: inviting an official robot (e.g. 2854207029) into a +// group makes QQ push the `group_member_increase` notice TWICE, so SnowLuma +// reported two `notice.group_increase` while a normal member produced one. +// QQ NT dedups system messages in `sys_msg_mgr.cc::ProcessRecvSysMsg` by a +// global key whose per-message discriminators are msg_seq (contentHead field 5 +// = head.sequence) and random (contentHead field 4 = head.msgId); kernel-based +// bots see events only after that dedup. SnowLuma reads the raw OlPush, so +// parseMsgPush must replicate the drop for system pushes — but only when given +// a dedup tracker (the live path), and never for chat messages. + +import { describe, expect, it } from 'vitest'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import { protobuf_encode } from '@snowluma/proton'; +import type { PushMsg, PushMsgBody } from '@snowluma/proto-defs/message'; +import type { GroupChange } from '@snowluma/proto-defs/notify'; +import type { IdentityService } from '../../src/identity-service'; +import { parseMsgPush, SysMsgDedup } from '../../src/msg-push'; + +const identity = { findUinByUid: () => null, findFriend: () => undefined } as unknown as IdentityService; + +function pushPacket(message: PushMsgBody): PacketInfo { + return { + pid: 0, + uin: '2000000001', + serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush', + seqId: 0, + retCode: 0, + fromClient: false, + body: protobuf_encode({ message }), + }; +} + +// A type-33 group member-increase push (the #137 shape). `memberUid` is a +// numeric string so resolveUidToUin returns it without touching identity. +function memberIncreasePush(opts: { groupId: number; memberUin: number; sequence: number; msgId: number }): PacketInfo { + return pushPacket({ + responseHead: { fromUin: opts.groupId, fromUid: '' }, + contentHead: { msgType: 33, subType: 0, sequence: opts.sequence, timestamp: 1781540572, msgId: opts.msgId }, + body: { msgContent: protobuf_encode({ groupUin: opts.groupId, memberUid: String(opts.memberUin) }) }, + }); +} + +describe('SysMsgDedup', () => { + it('flags the second push with the same (msgType, subType, fromUin, seq, msgId)', () => { + const d = new SysMsgDedup(); + const head = { msgType: 33, subType: 0, sequence: 500, msgId: 12345 }; + expect(d.seenDuplicate(head, 700)).toBe(false); + expect(d.seenDuplicate(head, 700)).toBe(true); + }); + + it('treats a different seq, msgId, type, or peer as a distinct push', () => { + const d = new SysMsgDedup(); + const base = { msgType: 33, subType: 0, sequence: 500, msgId: 12345 }; + expect(d.seenDuplicate(base, 700)).toBe(false); + expect(d.seenDuplicate({ ...base, sequence: 501 }, 700)).toBe(false); + expect(d.seenDuplicate({ ...base, msgId: 99999 }, 700)).toBe(false); + expect(d.seenDuplicate({ ...base, msgType: 34 }, 700)).toBe(false); + expect(d.seenDuplicate(base, 701)).toBe(false); + }); + + it('never dedups a push with no server identity (seq or msgId 0)', () => { + const d = new SysMsgDedup(); + expect(d.seenDuplicate({ msgType: 33, subType: 0, sequence: 0, msgId: 0 }, 700)).toBe(false); + expect(d.seenDuplicate({ msgType: 33, subType: 0, sequence: 0, msgId: 0 }, 700)).toBe(false); + expect(d.seenDuplicate({ msgType: 33, subType: 0, sequence: 5, msgId: 0 }, 700)).toBe(false); + expect(d.seenDuplicate({ msgType: 33, subType: 0, sequence: 0, msgId: 5 }, 700)).toBe(false); + }); + + it('evicts the oldest key once capacity is exceeded (bounded memory)', () => { + const d = new SysMsgDedup(2); + const k = (sequence: number) => ({ msgType: 33, subType: 0, sequence, msgId: 1 }); + expect(d.seenDuplicate(k(1), 1)).toBe(false); // [1] + expect(d.seenDuplicate(k(2), 1)).toBe(false); // [1,2] + expect(d.seenDuplicate(k(3), 1)).toBe(false); // [2,3] — evicts 1 + expect(d.seenDuplicate(k(1), 1)).toBe(false); // 1 was evicted → seen as new again + expect(d.seenDuplicate(k(3), 1)).toBe(true); // 3 still tracked + }); +}); + +describe('parseMsgPush — system-push dedup (#137)', () => { + it('drops the second identical official-robot member-increase push', () => { + const dedup = new SysMsgDedup(); + const push = () => memberIncreasePush({ groupId: 700, memberUin: 2854207029, sequence: 800, msgId: 555 }); + + const first = parseMsgPush(push(), identity, dedup); + expect(first).toHaveLength(1); + expect(first[0]).toMatchObject({ kind: 'group_member_join', groupId: 700, userUin: 2854207029 }); + + const second = parseMsgPush(push(), identity, dedup); + expect(second).toEqual([]); + }); + + it('keeps both pushes when no dedup tracker is supplied (forward re-parse path)', () => { + const push = () => memberIncreasePush({ groupId: 700, memberUin: 2854207029, sequence: 800, msgId: 555 }); + expect(parseMsgPush(push(), identity)).toHaveLength(1); + expect(parseMsgPush(push(), identity)).toHaveLength(1); + }); + + it('keeps distinct member-increase events (different members → different seq/msgId)', () => { + const dedup = new SysMsgDedup(); + const a = parseMsgPush(memberIncreasePush({ groupId: 700, memberUin: 111, sequence: 800, msgId: 555 }), identity, dedup); + const b = parseMsgPush(memberIncreasePush({ groupId: 700, memberUin: 222, sequence: 801, msgId: 556 }), identity, dedup); + expect(a).toHaveLength(1); + expect(b).toHaveLength(1); + expect(b[0]).toMatchObject({ userUin: 222 }); + }); + + it('does not dedup chat messages, even with an identical (seq, msgId)', () => { + const dedup = new SysMsgDedup(); + const chat = (): PacketInfo => pushPacket({ + responseHead: { fromUin: 10001, fromUid: 'u_x' }, + contentHead: { msgType: 166, subType: 0, sequence: 900, timestamp: 1781540572, msgId: 7 }, + body: { richText: { elems: [{ text: { str: 'hi' } }] } }, + }); + expect(parseMsgPush(chat(), identity, dedup)).toHaveLength(1); + expect(parseMsgPush(chat(), identity, dedup)).toHaveLength(1); + }); +});