refactor(protocol): keep Decoder a pure parse of MsgPush events

Decoder used to write Identity: decodeGroupAdmin patched member roles
and decodeFriendMessage stashed invite-card msgseq. That split
observation with IncomingPacketPipeline.rememberEventIdentity and put
pending-application state on Identity.

Decoder now only returns events. Invite-card groupUin/msgseq ride on
FriendMessage; the live pipeline writes them to ContactsApi through
an optional port. Role self-heal for #93 stays in
rememberEventIdentity. History and forward decode do not write.
Identity no longer stores invite-card sequences.

Live #93 and #125 behavior is unchanged.
This commit is contained in:
DrSmoothl committed 2026-08-16 18:22:41 +08:00
1 parent fea1996e46
commit 226b48fd7a
12 files changed
+148 -79

No files matched your search

+5
View File
@@ -278,6 +278,11 @@ export interface FriendMessage extends QQEvent {
sequenceAuthoritative?: boolean;
msgId: number;
elements: MessageElement[];
/** Parsed `qun.invite` card, if this private message is one. Live
* IncomingPacketPipeline copies these onto the pending-application
* store. Not OneBot wire. */
inviteCardGroupUin?: number;
inviteCardSequence?: number;
}
export interface GroupMessage extends QQEvent {
-24
View File
@@ -133,10 +133,6 @@ export class IdentityService {
private readonly userProfiles_ = new Map<number, UserProfileInfo>();
private friends_: FriendInfo[] = [];
private readonly groups_ = new Map<number, QQGroupInfo>();
// groupUin → approval msgseq from a private "qun.invite" card's jumpUrl.
// The 0x10c8 approval for a bot self-invite needs THIS sequence (with
// eventType=2); the MSF invite push never carries it. See issue #125.
private readonly groupInviteCardSeqs_ = new Map<number, number>();
// ─── Bidirectional UID↔UIN index (O(1), populated by every observation) ───
private readonly uinByUid = new Map<string, number>();
@@ -615,26 +611,6 @@ export class IdentityService {
this.runWrite('user profile', () => this.transaction(() => this.upsertUser(persisted)));
}
/** Remember the approval msgseq carried by a private "qun.invite" card's
* jumpUrl, keyed by group. `set_group_add_request` reads it back to approve
* a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
this.assertOpen('group invite sequence');
if (groupUin > 0 && sequence > 0) this.groupInviteCardSeqs_.set(groupUin, sequence);
}
getGroupInviteCardSequence(groupUin: number): number | undefined {
return this.groupInviteCardSeqs_.get(groupUin);
}
/** Reverse lookup used for NapCat-compatible numeric request flags. */
findGroupInviteCardGroupBySequence(sequence: number): number | undefined {
for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) {
if (rememberedSequence === sequence) return groupUin;
}
return undefined;
}
rememberGroupRequests(requests: GroupRequestInfo[]): void {
this.beginObservation('group requests');
const observed = requests.map((request) => ({ ...request }));
@@ -28,16 +28,11 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
const sentBySelf = ctx.fromUin > 0 && ctx.fromUin === ctx.selfUin;
const peerUin = sentBySelf ? (ctx.responseHead?.toUin ?? 0) : ctx.fromUin;
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
// Stash the approval msgseq from a live private group-invite card so a later
// `set_group_add_request` can approve a bot self-invite (issue #125).
// Historical decode is intentionally read-only: replaying an older card here
// could overwrite the sequence observed from a newer live invite.
if (!ctx.isHistorical) {
for (const el of elements) {
if (el.type === 'json' && typeof el.text === 'string') {
const card = parseGroupInviteCard(el.text);
if (card) ctx.identity.rememberGroupInviteCardSequence(card.groupUin, card.sequence);
}
let inviteCard: { groupUin: number; sequence: number } | null = null;
for (const el of elements) {
if (el.type === 'json' && typeof el.text === 'string') {
inviteCard = parseGroupInviteCard(el.text);
if (inviteCard) break;
}
}
const ev: FriendMessage = {
@@ -54,6 +49,10 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements,
senderNick: '',
...(inviteCard ? {
inviteCardGroupUin: inviteCard.groupUin,
inviteCardSequence: inviteCard.sequence,
} : {}),
};
if (ctx.responseHead?.forward?.friendName) {
ev.senderNick = ctx.responseHead.forward.friendName;
@@ -21,21 +21,6 @@ export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
const set = !!enableUid;
const userUin = resolveUidToUin(ctx.identity, groupId, adminUid);
// Keep the in-memory member cache in step with the promotion/demotion.
// `get_group_member_info` serves straight from this cache on its
// default (no_cache=false) path — and we deliberately *don't*
// force-refresh there, because clients like OlivaDice/MaiBot query it
// once per inbound message and a per-message OIDB refetch trips
// Tencent risk-control (see the ContactsApi member-list cache). So if
// we don't patch the role here, a freshly-promoted admin keeps reading
// back as `member` until the member-list TTL lapses, and permission
// gates reject their commands (#93). Only touch a member we already
// know, and never downgrade the owner.
const cached = ctx.identity.findGroupMember(groupId, userUin);
if (cached && cached.role !== 'owner') {
ctx.identity.updateGroupMember(groupId, { ...cached, role: set ? 'admin' : 'member' });
}
const ev: GroupAdminEvent = {
kind: 'group_admin',
time: ctx.head.timestamp,
+22 -1
View File
@@ -63,6 +63,10 @@ export interface PacketPipelineDeps {
/** Resolve a private invite-card msgseq. Implementations may briefly wait
* for the paired C2C Ark card, as the PkgType 87 push omits this value. */
resolveGroupInviteCardSequence?(groupId: number): Promise<number | null>;
/** Live-only write of a parsed private invite-card msgseq onto the
* pending-application store. Optional: tests that do not care about
* cards may omit it; production Bridge always binds ContactsApi. */
rememberGroupInviteCardSequence?(groupUin: number, sequence: number): void;
}
export class IncomingPacketPipeline {
@@ -627,6 +631,12 @@ export class IncomingPacketPipeline {
uin: event.senderUin,
source: 'friend_message',
});
if (event.inviteCardGroupUin && event.inviteCardSequence) {
this.deps.rememberGroupInviteCardSequence?.(
event.inviteCardGroupUin,
event.inviteCardSequence,
);
}
break;
case 'group_message': {
// [#1] Self-heal a member's cached group card from message traffic. The
@@ -661,11 +671,22 @@ export class IncomingPacketPipeline {
uin: event.operatorUin,
});
break;
case 'group_admin':
case 'group_admin': {
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uin: event.userUin,
});
// #93: get_group_member_info serves the cache and must not refetch
// per message. Patch a known member's role here — never invent a
// phantom, never downgrade the owner.
const cached = this.deps.identity.findGroupMember(event.groupId, event.userUin);
if (cached && cached.role !== 'owner') {
this.deps.identity.updateGroupMember(event.groupId, {
...cached,
role: event.set ? 'admin' : 'member',
});
}
break;
}
case 'friend_request':
this.deps.identity.rememberRequestIdentity({
uid: event.fromUid,
@@ -171,38 +171,38 @@ describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
)).rejects.toThrow('friend uid mismatch');
});
it('does not replay live-only invite observations from older history', async () => {
const remembered: Array<[number, number]> = [];
const observingIdentity = {
findFriend: () => undefined,
rememberGroupInviteCardSequence: (groupUin: number, sequence: number) => {
remembered.push([groupUin, sequence]);
},
} as unknown as IdentityService;
it('parses invite-card facts on friend messages without writing Identity', async () => {
const live = buildContextFromMessage(
inviteCardMessage(222),
10001,
observingIdentity,
identity,
false,
);
expect(live).not.toBeNull();
decodeFriendMessage(live!);
expect(decodeFriendMessage(live!)).toMatchObject([{
kind: 'friend_message',
inviteCardGroupUin: 12345,
inviteCardSequence: 222,
}]);
const historyResponse = protobuf_encode<SsoGetC2cMsgResponse>({
friendUid: 'u_friend',
messages: [inviteCardMessage(111)],
});
await fetchC2cMessageRange(
const out = await fetchC2cMessageRange(
{ sendRawPacket: async () => okResult(historyResponse) },
observingIdentity,
identity,
10001,
'u_friend',
100,
120,
);
expect(remembered).toEqual([[12345, 222]]);
expect(out).toMatchObject([{
kind: 'friend_message',
inviteCardGroupUin: 12345,
inviteCardSequence: 111,
}]);
});
});
@@ -498,3 +498,41 @@ describe('IncomingPacketPipeline / group_card_change from message traffic', () =
expect(captured.some((e) => e.kind === 'group_card_change')).toBe(false);
});
});
describe('IncomingPacketPipeline / invite-card pending application', () => {
const friendMessage = (
card?: { inviteCardGroupUin: number; inviteCardSequence: number },
): QQEventVariant => ({
kind: 'friend_message',
time: 1,
selfUin: 10001,
senderUin: 222,
senderNick: 'Bob',
msgSeq: 1,
msgId: 1,
elements: [],
...card,
});
it('remembers parsed invite-card facts through the optional port', () => {
const rememberGroupInviteCardSequence = vi.fn();
const pipeline = new IncomingPacketPipeline({
identity: IdentityService.memory('10001'),
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
resolveGroupJoinRequest: vi.fn(async () => null),
rememberGroupInviteCardSequence,
});
pipeline.registerCmd('test.cmd', () => [
friendMessage({ inviteCardGroupUin: 12345, inviteCardSequence: 778899 }),
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
expect(rememberGroupInviteCardSequence).toHaveBeenCalledWith(12345, 778899);
});
it('does not remember when the port is omitted or the event has no card', () => {
const { pipeline } = makePipeline();
pipeline.registerCmd('test.cmd', () => [friendMessage()]);
expect(() => pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo)).not.toThrow();
});
});