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

+13 -2
View File
@@ -134,6 +134,9 @@ export class ContactsApi {
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
});
private robotUinRangesPromise_: Promise<RobotUinRangeSnapshot> | null = null;
/** groupUin → approval msgseq from a private qun.invite card. Written
* only by IncomingPacketPipeline (and tests). OneBot reads get/find. */
private readonly groupInviteCardSeqs_ = new Map<number, number>();
constructor(private readonly ctx: BridgeContext) { }
@@ -520,17 +523,25 @@ export class ContactsApi {
return requests;
}
/** Live observation write. IncomingPacketPipeline and tests only. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
if (groupUin > 0 && sequence > 0) this.groupInviteCardSeqs_.set(groupUin, sequence);
}
/** The approval msgseq captured from a private "qun.invite" card for this
* group, or undefined if none was seen. `set_group_add_request` uses it to
* approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
getGroupInviteCardSequence(groupId: number): number | undefined {
return this.ctx.identity.getGroupInviteCardSequence(groupId);
return this.groupInviteCardSeqs_.get(groupId);
}
/** Resolve the group for a private invite-card msgseq. Numeric OneBot flags
* use this path because the card sequence is absent from 0x10C0. */
findGroupInviteCardGroupBySequence(sequence: number): number | undefined {
return this.ctx.identity.findGroupInviteCardGroupBySequence(sequence);
for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) {
if (rememberedSequence === sequence) return groupUin;
}
return undefined;
}
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
+3
View File
@@ -94,6 +94,9 @@ export class Bridge implements BridgeInterface {
} while (Date.now() < deadline);
return null;
},
rememberGroupInviteCardSequence: (groupUin, sequence) => {
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence);
},
});
this.pipeline.registerCmd(
MSG_PUSH_CMD,
@@ -623,3 +623,18 @@ describe('apis/contacts / robot group-member classification', () => {
expect(rememberGroupMembers).toHaveBeenCalledOnce();
});
});
describe('apis/contacts / invite-card pending application', () => {
it('remembers, reads, and reverse-looks-up a card sequence', () => {
const api = new ContactsApi({ identity: { uin: '10001' } } as any);
expect(api.getGroupInviteCardSequence(12345)).toBeUndefined();
api.rememberGroupInviteCardSequence(12345, 778899);
api.rememberGroupInviteCardSequence(0, 1);
api.rememberGroupInviteCardSequence(1, 0);
expect(api.getGroupInviteCardSequence(12345)).toBe(778899);
expect(api.findGroupInviteCardGroupBySequence(778899)).toBe(12345);
expect(api.findGroupInviteCardGroupBySequence(1)).toBeUndefined();
});
});
@@ -786,7 +786,6 @@ describe('IdentityService', () => {
['forget group', () => identity.forgetGroup(GROUP_ID)],
['group members', () => identity.rememberGroupMembers(GROUP_ID, [])],
['user profile', () => identity.rememberUserProfile(profile)],
['group invite sequence', () => identity.rememberGroupInviteCardSequence(GROUP_ID, 123)],
['group requests', () => identity.rememberGroupRequests([request])],
['request identity', () => identity.rememberRequestIdentity({ uid: 'u_request', uin: 88888 })],
['group member identity', () => identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_new', uin: 99999 })],
+29 -12
View File
@@ -916,11 +916,8 @@ describe('parseMsgPush PkgType 85 (bot self-joined a group)', () => {
});
describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache fresh', () => {
// Regression for #93: a member promoted to admin kept reading back as
// `member` via get_group_member_info because the admin-change push only
// emitted the notice and never patched the cached role — and that API
// serves straight from the cache (no per-read refetch, on purpose, to
// dodge risk-control). The decoder now mirrors the role into the cache.
// Regression for #93: get_group_member_info serves the cache. Role
// patch is IncomingPacketPipeline observation, not Decoder.
function makeGroupAdminPacket(adminUid: string, set: boolean, fromUin = GROUP_ID): PacketInfo {
const extra = { adminUid };
const content = protobuf_encode<GroupAdmin>({
@@ -941,7 +938,18 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache
};
}
it('promotes a cached member to admin in the identity cache (and emits set=true)', () => {
async function processAdmin(identity: IdentityService, packet: PacketInfo): Promise<void> {
const pipeline = new IncomingPacketPipeline({
identity,
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
await pipeline.process(packet);
}
it('Decoder emits the event without writing Identity', () => {
const member = makeGroupMember(22222, 'u_member');
const identity = makeIdentity([member]);
@@ -950,32 +958,41 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache
expect(event.kind).toBe('group_admin');
expect(event.userUin).toBe(member.uin);
expect(event.set).toBe(true);
expect(identity.findGroupMember(GROUP_ID, member.uin)?.role).toBe('member');
});
it('promotes a cached member to admin at the packet-pipeline boundary', async () => {
const member = makeGroupMember(22222, 'u_member');
const identity = makeIdentity([member]);
await processAdmin(identity, makeGroupAdminPacket(member.uid, true));
expect(identity.findGroupMember(GROUP_ID, member.uin)?.role).toBe('admin');
});
it('demotes a cached admin back to member on an unset push', () => {
it('demotes a cached admin back to member on an unset push', async () => {
const admin = { ...makeGroupMember(22222, 'u_admin'), role: 'admin' };
const identity = makeIdentity([admin]);
const [event] = parseMsgPush(makeGroupAdminPacket(admin.uid, false), identity) as GroupAdminEvent[];
await processAdmin(identity, makeGroupAdminPacket(admin.uid, false));
expect(event.set).toBe(false);
expect(identity.findGroupMember(GROUP_ID, admin.uin)?.role).toBe('member');
});
it('never downgrades the owner', () => {
it('never downgrades the owner', async () => {
const owner = { ...makeGroupMember(22222, 'u_owner'), role: 'owner' };
const identity = makeIdentity([owner]);
parseMsgPush(makeGroupAdminPacket(owner.uid, false), identity);
await processAdmin(identity, makeGroupAdminPacket(owner.uid, false));
expect(identity.findGroupMember(GROUP_ID, owner.uin)?.role).toBe('owner');
});
it('is a no-op (no throw, no phantom member) when the target is not cached', () => {
it('is a no-op (no throw, no phantom member) when the target is not cached', async () => {
const identity = makeIdentity();
const [event] = parseMsgPush(makeGroupAdminPacket('u_unknown', true), identity) as GroupAdminEvent[];
await processAdmin(identity, makeGroupAdminPacket('u_unknown', true));
expect(event.kind).toBe('group_admin');
expect(event.userUin).toBe(0);
+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();
});
});