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:
DrSmoothl committed 2026-10-31 18:28:05 +08:00
1 parent d8763c98db
commit 299fa85a74
16 files changed
+429 -142

No files matched your search

@@ -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;
}
}
+19 -61
View File
@@ -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');