fix(onebot): match group invitations to the correct request
Report distinct invitations separately and approve only the request that belongs to the account and inviter. Reject ambiguous approvals and resolve the sender of invitations from outside the contact list. Refs #612
This commit is contained in:
16 files changed
+429
-142
No files matched your search
@@ -24,6 +24,7 @@ import type { GroupChange } from '@snowluma/proto-defs/notify';
|
||||
import { parseMsgPush, MSG_PUSH_CMD } from '../src/msg-push/index';
|
||||
import { IdentityService } from '../src/identity-service';
|
||||
import { BridgeEventBus } from '../src/event-bus';
|
||||
import { GroupInviteTracker } from '../src/group-invite-tracker';
|
||||
import { IncomingPacketPipeline } from '../src/packet-pipeline';
|
||||
|
||||
const SELF_UIN = '10001';
|
||||
@@ -156,7 +157,7 @@ function makePipeline(identity: IdentityService): IncomingPacketPipeline {
|
||||
fetchGroupList: async () => {},
|
||||
fetchGroupMemberList: async () => {},
|
||||
resolveGroupJoinRequest: async () => null,
|
||||
rememberGroupInviteCardSequence: () => true,
|
||||
groupInvites: new GroupInviteTracker(),
|
||||
});
|
||||
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
|
||||
return pipeline;
|
||||
|
||||
@@ -24,6 +24,10 @@
|
||||
"types": "./src/identity-service.ts",
|
||||
"default": "./src/identity-service.ts"
|
||||
},
|
||||
"./group-invite-tracker": {
|
||||
"types": "./src/group-invite-tracker.ts",
|
||||
"default": "./src/group-invite-tracker.ts"
|
||||
},
|
||||
"./packet-pipeline": {
|
||||
"types": "./src/packet-pipeline.ts",
|
||||
"default": "./src/packet-pipeline.ts"
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
const PAIR_WINDOW_MS = 3_000;
|
||||
const MAX_INVITES = 1_024;
|
||||
|
||||
interface Card {
|
||||
groupId: number;
|
||||
sequence: number;
|
||||
}
|
||||
|
||||
interface SelfInviteNotice {
|
||||
cardSequence?: number;
|
||||
ambiguous?: boolean;
|
||||
}
|
||||
|
||||
interface UnpairedInvite {
|
||||
key: string;
|
||||
notice?: SelfInviteNotice;
|
||||
source: 'card' | 'notice';
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
function remember<T>(entries: Map<string, T>, key: string, value: T): void {
|
||||
entries.delete(key);
|
||||
|
||||
if (entries.size >= MAX_INVITES) {
|
||||
const oldest = entries.keys().next();
|
||||
|
||||
if (!oldest.done) {
|
||||
entries.delete(oldest.value);
|
||||
}
|
||||
}
|
||||
|
||||
entries.set(key, value);
|
||||
}
|
||||
|
||||
/** Account-local state shared by incoming invitations and their approval actions. */
|
||||
export class GroupInviteTracker {
|
||||
private readonly cards = new Map<string, Card>();
|
||||
private readonly notices = new Map<string, SelfInviteNotice>();
|
||||
private unpaired: UnpairedInvite[] = [];
|
||||
|
||||
receiveNotice(groupId: number, uid: string): boolean {
|
||||
const key = `${groupId}:${uid}`;
|
||||
const notice: SelfInviteNotice = {};
|
||||
|
||||
if (this.pair(key, 'notice', notice)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Earlier notices with the same legacy flag cannot lend this one their card.
|
||||
remember(this.notices, key, notice);
|
||||
return true;
|
||||
}
|
||||
|
||||
receiveCard(groupId: number, sequence: number, uid?: string): boolean {
|
||||
const key = `${groupId}:${sequence}`;
|
||||
|
||||
if (this.cards.has(key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const paired = uid ? this.pair(`${groupId}:${uid}`, 'card') : undefined;
|
||||
|
||||
if (paired?.notice) {
|
||||
paired.notice.cardSequence = sequence;
|
||||
}
|
||||
|
||||
remember(this.cards, key, { groupId, sequence });
|
||||
return !paired;
|
||||
}
|
||||
|
||||
private pair(
|
||||
key: string,
|
||||
source: UnpairedInvite['source'],
|
||||
notice?: SelfInviteNotice,
|
||||
): UnpairedInvite | undefined {
|
||||
const now = Date.now();
|
||||
this.unpaired = this.unpaired.filter((entry) => entry.expiresAt > now);
|
||||
const match = this.unpaired.findIndex(
|
||||
(entry) => entry.key === key && entry.source !== source,
|
||||
);
|
||||
|
||||
if (match !== -1) {
|
||||
return this.unpaired.splice(match, 1)[0];
|
||||
}
|
||||
|
||||
if (this.unpaired.length >= MAX_INVITES) {
|
||||
this.unpaired.shift();
|
||||
}
|
||||
|
||||
if (
|
||||
notice &&
|
||||
this.unpaired.some((entry) => entry.key === key && entry.source === 'notice')
|
||||
) {
|
||||
notice.ambiguous = true;
|
||||
}
|
||||
|
||||
this.unpaired.push({ key, source, notice, expiresAt: now + PAIR_WINDOW_MS });
|
||||
return undefined;
|
||||
}
|
||||
|
||||
getSelfInviteNotice(groupId: number, uid: string): Readonly<SelfInviteNotice> | undefined {
|
||||
const notice = this.notices.get(`${groupId}:${uid}`);
|
||||
|
||||
if (notice?.ambiguous) {
|
||||
throw new Error('multiple pending self invitations share this flag');
|
||||
}
|
||||
|
||||
return notice;
|
||||
}
|
||||
|
||||
getCardSequence(groupId: number): number | undefined {
|
||||
let sequence: number | undefined;
|
||||
|
||||
for (const card of this.cards.values()) {
|
||||
if (card.groupId === groupId) {
|
||||
sequence = card.sequence;
|
||||
}
|
||||
}
|
||||
|
||||
return sequence;
|
||||
}
|
||||
|
||||
findCardGroup(sequence: number, groupId?: number): number | undefined {
|
||||
if (groupId !== undefined) {
|
||||
return this.cards.get(`${groupId}:${sequence}`)?.groupId;
|
||||
}
|
||||
|
||||
let match: number | undefined;
|
||||
|
||||
for (const card of this.cards.values()) {
|
||||
if (card.sequence === sequence) {
|
||||
if (match !== undefined) {
|
||||
throw new Error('multiple groups match this invitation card sequence');
|
||||
}
|
||||
|
||||
match = card.groupId;
|
||||
}
|
||||
}
|
||||
|
||||
return match;
|
||||
}
|
||||
}
|
||||
@@ -3,17 +3,10 @@ import { formatEvent } from './format';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { BridgeEventBus } from './event-bus';
|
||||
import type { QQEventVariant } from './events';
|
||||
import type { GroupInviteTracker } from './group-invite-tracker';
|
||||
import type { IdentityService } from './identity-service';
|
||||
import { formatGroupRequestFlag, type GroupRequestInfo } from './qq-info';
|
||||
|
||||
/**
|
||||
* How long a dispatched invitation stays remembered so the MSF notice and the
|
||||
* private `qun.invite` card of the SAME invitation do not both dispatch.
|
||||
* Both packets come from one server-side action, so the window only bounds how
|
||||
* long the marker lives -- matching itself is exact (group + inviter UID).
|
||||
*/
|
||||
const INVITE_PAIR_WINDOW_MS = 3_000;
|
||||
|
||||
const moduleLog = createLogger('Bridge');
|
||||
const moduleEventLog = createLogger('Event');
|
||||
const modulePacketLog = createLogger('Protocol.Packet');
|
||||
@@ -60,8 +53,7 @@ export interface PacketPipelineDeps {
|
||||
subType: 'add' | 'invite',
|
||||
invitedUid?: string,
|
||||
): Promise<GroupRequestInfo | null>;
|
||||
/** Remember a live card; false means its approval sequence was already seen. */
|
||||
rememberGroupInviteCardSequence(groupUin: number, sequence: number): boolean;
|
||||
groupInvites: GroupInviteTracker;
|
||||
}
|
||||
|
||||
export class IncomingPacketPipeline {
|
||||
@@ -70,15 +62,6 @@ export class IncomingPacketPipeline {
|
||||
private readonly log: Logger;
|
||||
private readonly eventLog: Logger;
|
||||
private readonly packetLog: Logger;
|
||||
/**
|
||||
* One invitation can arrive as an MSF notice AND as a private card. The card
|
||||
* is the richer source (it carries the approval msgseq), so either one may
|
||||
* dispatch -- but never both. Two independent markers keep that mutual: a
|
||||
* notice suppresses the card that follows it, a card suppresses the notice.
|
||||
* Cards never suppress each other (a new msgseq is a new invitation).
|
||||
*/
|
||||
private readonly noticeDispatched_ = new Map<string, number>();
|
||||
private readonly cardDispatched_ = new Map<string, number>();
|
||||
|
||||
constructor(private readonly deps: PacketPipelineDeps) {
|
||||
// Tag every line we emit with this Bridge's UIN so per-account file
|
||||
@@ -402,21 +385,11 @@ export class IncomingPacketPipeline {
|
||||
if (
|
||||
!groupId ||
|
||||
!sequence ||
|
||||
!this.deps.rememberGroupInviteCardSequence(groupId, sequence)
|
||||
!this.deps.groupInvites.receiveCard(groupId, sequence, event.senderUid)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The msgseq is cached above either way. Skip the duplicate event only when
|
||||
// the notice already delivered this same invitation -- a card with a new
|
||||
// sequence is a genuinely new invitation and must always dispatch.
|
||||
if (this.dispatchedRecently_(this.noticeDispatched_, groupId, event.senderUid ?? '')) {
|
||||
this.log.debug('invitation already dispatched from the notice: group=%d', groupId);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.rememberDispatched_(this.cardDispatched_, groupId, event.senderUid ?? '');
|
||||
|
||||
this.finishDispatch({
|
||||
kind: 'group_invite',
|
||||
time: event.time,
|
||||
@@ -432,27 +405,6 @@ export class IncomingPacketPipeline {
|
||||
return true;
|
||||
}
|
||||
|
||||
private dispatchedRecently_(
|
||||
marker: Map<string, number>,
|
||||
groupId: number,
|
||||
inviterUid: string,
|
||||
): boolean {
|
||||
const key = `${groupId}:${inviterUid}`;
|
||||
const at = marker.get(key);
|
||||
if (at === undefined) return false;
|
||||
if (Date.now() - at < INVITE_PAIR_WINDOW_MS) return true;
|
||||
marker.delete(key);
|
||||
return false;
|
||||
}
|
||||
|
||||
private rememberDispatched_(
|
||||
marker: Map<string, number>,
|
||||
groupId: number,
|
||||
inviterUid: string,
|
||||
): void {
|
||||
marker.set(`${groupId}:${inviterUid}`, Date.now());
|
||||
}
|
||||
|
||||
private emit(event: QQEventVariant): void {
|
||||
// Fire-and-forget: errors inside subscribers are surfaced via the bus's
|
||||
// own onError hook so one bad listener never blocks the others.
|
||||
@@ -550,22 +502,17 @@ export class IncomingPacketPipeline {
|
||||
pkt: PacketInfo,
|
||||
event: Extract<QQEventVariant, { kind: 'group_invite' }>,
|
||||
): Promise<number> {
|
||||
// A self-invite never appears in the UIN-based request inbox, so there is
|
||||
// nothing to enrich from and querying it only wastes a round trip. The
|
||||
// private card carries the approval msgseq, but it only arrives for some
|
||||
// inviters -- when it does not, the notice is the only chance to surface
|
||||
// the invitation at all. Dispatch it with the decoder-provided legacy flag,
|
||||
// and let the card win when both arrive (see `dispatchedInvites_`).
|
||||
// A self-invite notice carries an inviter UID but no approval sequence.
|
||||
if (
|
||||
event.subType === 'invite' &&
|
||||
this.isSelfMemberIdentity(event.invitedUin ?? 0, event.invitedUid)
|
||||
) {
|
||||
if (!event.flag) {
|
||||
this.log.warn('self invitation without a flag: group=%d', event.groupId);
|
||||
if (!(event.groupId > 0) || !event.fromUid?.trim() || !event.flag) {
|
||||
this.log.warn('self invitation missing group or inviter: group=%d', event.groupId);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (this.dispatchedRecently_(this.cardDispatched_, event.groupId, event.fromUid ?? '')) {
|
||||
if (!this.deps.groupInvites.receiveNotice(event.groupId, event.fromUid)) {
|
||||
this.log.debug(
|
||||
'self invitation already dispatched from the card: group=%d',
|
||||
event.groupId,
|
||||
@@ -573,7 +520,18 @@ export class IncomingPacketPipeline {
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.rememberDispatched_(this.noticeDispatched_, event.groupId, event.fromUid ?? '');
|
||||
if (!event.fromUin) {
|
||||
event.fromUin =
|
||||
(await this.deps.identity.resolveUin(event.fromUid, event.groupId)) ?? 0;
|
||||
|
||||
if (!event.fromUin) {
|
||||
this.log.warn(
|
||||
'self invitation sender unavailable: group=%d uid=%s',
|
||||
event.groupId,
|
||||
event.fromUid,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
return this.dispatchEvent(pkt, event, 'sync');
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import type { QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
|
||||
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
|
||||
import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -154,7 +155,7 @@ function makePipeline(
|
||||
fetchGroupList,
|
||||
fetchGroupMemberList,
|
||||
resolveGroupJoinRequest: vi.fn(async () => null),
|
||||
rememberGroupInviteCardSequence: vi.fn(() => true),
|
||||
groupInvites: new GroupInviteTracker(),
|
||||
});
|
||||
return { identity, pipeline, captured, fetchGroupList, fetchGroupMemberList };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
|
||||
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
@@ -49,7 +50,7 @@ function makePipeline(
|
||||
fetchGroupList: vi.fn(async () => {}),
|
||||
fetchGroupMemberList: vi.fn(async () => {}),
|
||||
resolveGroupJoinRequest,
|
||||
rememberGroupInviteCardSequence: vi.fn(() => true),
|
||||
groupInvites: new GroupInviteTracker(),
|
||||
});
|
||||
|
||||
const captured: QQEventVariant[] = [];
|
||||
@@ -193,23 +194,32 @@ describe('IncomingPacketPipeline / group requests', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('dispatches a self invitation without querying the inbox', async () => {
|
||||
// A self-invite never shows up in the UIN-based inbox, so the lookup is
|
||||
// skipped and the decoder-provided legacy flag is what keeps it actionable.
|
||||
const { pipeline, captured, resolveGroupJoinRequest, fetchProfileByUid } = makePipeline();
|
||||
await receive(
|
||||
pipeline,
|
||||
requestEvent({ subType: 'invite', invitedUin: 10001, flag: 'invite:12345:u_requester' }),
|
||||
);
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(captured[0]).toMatchObject({
|
||||
kind: 'group_invite',
|
||||
invitedUin: 10001,
|
||||
flag: 'invite:12345:u_requester',
|
||||
});
|
||||
expect(resolveGroupJoinRequest).not.toHaveBeenCalled();
|
||||
expect(fetchProfileByUid).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([76543, 0])(
|
||||
'resolves the self-invite sender without querying the inbox (profile UIN %d)',
|
||||
async (uin) => {
|
||||
const fetchProfileByUid = vi.fn(async () => makeProfile(uin));
|
||||
const { pipeline, captured, resolveGroupJoinRequest } = makePipeline({
|
||||
fetchProfileByUid,
|
||||
});
|
||||
await receive(
|
||||
pipeline,
|
||||
requestEvent({
|
||||
subType: 'invite',
|
||||
invitedUin: 10001,
|
||||
flag: 'invite:12345:u_requester',
|
||||
}),
|
||||
);
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(captured[0]).toMatchObject({
|
||||
kind: 'group_invite',
|
||||
fromUin: uin,
|
||||
invitedUin: 10001,
|
||||
flag: 'invite:12345:u_requester',
|
||||
});
|
||||
expect(resolveGroupJoinRequest).not.toHaveBeenCalled();
|
||||
expect(fetchProfileByUid).toHaveBeenCalledExactlyOnceWith('u_requester');
|
||||
},
|
||||
);
|
||||
|
||||
it('does not substitute a list sequence for the self-invite card sequence', async () => {
|
||||
const resolveGroupJoinRequest = vi.fn(async () =>
|
||||
@@ -289,7 +299,7 @@ describe('IncomingPacketPipeline / #1 group card self-heal', () => {
|
||||
fetchGroupList: vi.fn(async () => {}),
|
||||
fetchGroupMemberList: vi.fn(async () => {}),
|
||||
resolveGroupJoinRequest: vi.fn(async () => null),
|
||||
rememberGroupInviteCardSequence: vi.fn(() => true),
|
||||
groupInvites: new GroupInviteTracker(),
|
||||
});
|
||||
return { identity, pipeline };
|
||||
}
|
||||
@@ -403,7 +413,7 @@ describe('IncomingPacketPipeline / group_card_change from message traffic', () =
|
||||
fetchGroupList: vi.fn(async () => {}),
|
||||
fetchGroupMemberList: vi.fn(async () => {}),
|
||||
resolveGroupJoinRequest: vi.fn(async () => null),
|
||||
rememberGroupInviteCardSequence: vi.fn(() => true),
|
||||
groupInvites: new GroupInviteTracker(),
|
||||
});
|
||||
const captured: QQEventVariant[] = [];
|
||||
events.onAny((e) => captured.push(e as QQEventVariant));
|
||||
|
||||
@@ -13,6 +13,7 @@ import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import type { MsgPushContext } from '@snowluma/protocol/msg-push/context';
|
||||
import { PkgType } from '@snowluma/protocol/msg-push/enums';
|
||||
import { MsgPushRegistry } from '@snowluma/protocol/msg-push/registry';
|
||||
import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
|
||||
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
@@ -140,7 +141,7 @@ function makePipeline(
|
||||
comment: '',
|
||||
filtered: false,
|
||||
})),
|
||||
rememberGroupInviteCardSequence: vi.fn(() => true),
|
||||
groupInvites: new GroupInviteTracker(),
|
||||
});
|
||||
const dispatched: Array<{ event: QQEventVariant; req: number | undefined }> = [];
|
||||
events.onAny((event) => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import type { GroupInviteEvent, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
|
||||
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
@@ -103,7 +104,7 @@ function makePipeline(options: { request?: 'found' | 'missing' } = {}) {
|
||||
fetchGroupList: vi.fn(async () => {}),
|
||||
fetchGroupMemberList: vi.fn(async () => {}),
|
||||
resolveGroupJoinRequest,
|
||||
rememberGroupInviteCardSequence: vi.fn(() => true),
|
||||
groupInvites: new GroupInviteTracker(),
|
||||
});
|
||||
|
||||
return { pipeline, received, resolveGroupJoinRequest };
|
||||
|
||||
Reference in new issue
Block a user