refactor: replace polling with event-driven updates

Trigger account detection and group requests from observed changes. Remove native stage log forwarding and its lifecycle state, and simplify the README.
This commit is contained in:
手瓜一十雪 committed 2026-10-19 09:56:20 +08:00
1 parent 1b74747251
commit e5cfec01bd
33 files changed
+1314 -1958

No files matched your search

+2
View File
@@ -155,6 +155,8 @@ function makePipeline(identity: IdentityService): IncomingPacketPipeline {
events,
fetchGroupList: async () => {},
fetchGroupMemberList: async () => {},
resolveGroupJoinRequest: async () => null,
rememberGroupInviteCardSequence: () => true,
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
return pipeline;
+1 -1
View File
@@ -419,7 +419,7 @@ export interface GroupInviteEvent extends QQEvent {
* logged-in account. */
invitedUin?: number;
invitedUid?: string;
subType: string;
subType: 'add' | 'invite';
message: string;
flag: string;
}
@@ -3,36 +3,53 @@ import type { FriendMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
/**
* A private "qun.invite" ark card (someone DMs the bot a group-invite card)
* carries the only sequence the server accepts when the bot later approves the
* invite via 0x10c8 — the `msgseq` embedded in its `mqqapi://group/invite_join`
* jumpUrl, applied with eventType=2 / filtered=false. The MSF invite push
* (PkgType 87) never carries it. Parse it out so `set_group_add_request` can
* use it. See issue #125.
*/
/** Read the approval tuple from a QQ group-invitation card. */
function parseGroupInviteCard(jsonText: string): { groupUin: number; sequence: number } | null {
if (!jsonText.includes('group/invite_join')) {
const card: unknown = JSON.parse(jsonText);
if (
!card ||
typeof card !== 'object' ||
!('app' in card) ||
(card.app !== 'com.tencent.qun.invite' && card.app !== 'com.tencent.tuwen.lua')
) {
return null;
}
const m = jsonText.match(/mqqapi:\/\/group\/invite_join[^"\\\s]*/);
if (!m) {
if (
!('meta' in card) ||
!card.meta ||
typeof card.meta !== 'object' ||
!('news' in card.meta) ||
!card.meta.news ||
typeof card.meta.news !== 'object' ||
!('jumpUrl' in card.meta.news) ||
typeof card.meta.news.jumpUrl !== 'string'
) {
return null;
}
const query = m[0].split('?')[1] ?? '';
const params = new URLSearchParams(query);
const groupUin = Number(params.get('groupcode') ?? 0);
const sequence = Number(params.get('msgseq') ?? 0);
const url = URL.parse(card.meta.news.jumpUrl);
if (!Number.isSafeInteger(groupUin) || !Number.isSafeInteger(sequence)) {
if (
!url ||
url.protocol !== 'mqqapi:' ||
url.hostname !== 'group' ||
url.pathname !== '/invite_join'
) {
return null;
}
if (groupUin <= 0 || sequence <= 0) {
return null;
const groupUin = Number(url.searchParams.get('groupcode'));
const sequence = Number(url.searchParams.get('msgseq'));
if (
!Number.isSafeInteger(groupUin) ||
groupUin <= 0 ||
!Number.isSafeInteger(sequence) ||
sequence <= 0
) {
throw new Error('group invitation card has an invalid approval tuple');
}
return { groupUin, sequence };
@@ -21,7 +21,7 @@ export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
fromUid: join.targetUid ?? '',
subType: 'add',
message: '',
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
flag: '',
};
return [ev];
};
@@ -29,7 +29,7 @@ export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
const invitation = protobuf_decode<GroupInvitation>(ctx.content);
if (!invitation?.info?.inner) {
if (invitation?.cmd !== 87 || !invitation.info?.inner) {
return [];
}
@@ -45,7 +45,7 @@ export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
invitedUid: inner.targetUid ?? '',
subType: 'invite',
message: '',
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
flag: '',
};
return [ev];
};
@@ -67,7 +67,7 @@ export const decodeGroupInvite: MsgPushDecoder = (ctx) => {
invitedUin: ctx.selfUin,
subType: 'invite',
message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
flag: '',
};
return [ev];
};
+101 -215
View File
@@ -45,29 +45,15 @@ export interface PacketPipelineDeps {
/** One group's member-list fetch (adapter TTL applies). Roster
* side-effect only; the pipeline does not pass `force`. */
fetchGroupMemberList(groupId: number): Promise<void>;
/**
* Resolve the verify message ("postscript") + server sequence number
* for a pending group-join / group-invite. The OIDB push only
* carries the requester's UID + group uin — the actual verify text
* the user typed ("你们好" etc.) lives on the pending-request queue
* fetched via OIDB 0x10C0. NapCat surfaces this as
* `notify.postscript` from `nodeIKernelGroupService.getGroupNotifies`;
* we mirror that with an `fetchGroupRequests` lookup matched on
* `(groupId, uid, subType)`. Returns null when no matching pending
* request exists (e.g. it was already handled by another client).
*/
/** Resolve a pending request's comment and approval tuple after a push. */
resolveGroupJoinRequest(
groupId: number,
uid: string,
subType: 'add' | 'invite',
invitedUid?: string,
): Promise<GroupRequestInfo | null>;
/** 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;
/** Remember a live card; false means its approval sequence was already seen. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): boolean;
}
export class IncomingPacketPipeline {
@@ -178,7 +164,7 @@ export class IncomingPacketPipeline {
);
});
enrichmentTasks.push(task);
} else if (this.needsGroupInviteEnrich(event)) {
} else if (event.kind === 'group_invite') {
this.traceEnrichmentStarted(pkt, event, 'group_invite');
const task = this.dispatchGroupInvite(pkt, event)
.then((count) => {
@@ -363,12 +349,50 @@ export class IncomingPacketPipeline {
this.finishDispatch(event);
this.traceDispatch(pkt, event.kind, mode);
if (!this.emitGroupCardChange(event, cardBefore)) {
return 1;
let dispatched = 1;
if (this.emitGroupCardChange(event, cardBefore)) {
this.traceDispatch(pkt, 'group_card_change', 'derived');
dispatched++;
}
this.traceDispatch(pkt, 'group_card_change', 'derived');
return 2;
if (this.emitGroupInviteCard(event)) {
this.traceDispatch(pkt, 'group_invite', 'derived');
dispatched++;
}
return dispatched;
}
private emitGroupInviteCard(event: QQEventVariant): boolean {
if (event.kind !== 'friend_message' || event.senderUin === event.selfUin) {
return false;
}
const groupId = event.inviteCardGroupUin;
const sequence = event.inviteCardSequence;
if (
!groupId ||
!sequence ||
!this.deps.rememberGroupInviteCardSequence(groupId, sequence)
) {
return false;
}
this.finishDispatch({
kind: 'group_invite',
time: event.time,
selfUin: event.selfUin,
groupId,
fromUin: event.senderUin,
fromUid: event.senderUid,
invitedUin: event.selfUin,
subType: 'invite',
message: '',
flag: formatGroupRequestFlag({ groupId, sequence, eventType: 2, filtered: false }),
});
return true;
}
private emit(event: QQEventVariant): void {
@@ -435,29 +459,6 @@ export class IncomingPacketPipeline {
);
}
/** Every group_invite that carries a requester UID gets async
* enrichment before dispatch. Two INDEPENDENT things are filled in:
*
* 1. The verify COMMENT — the text the requester typed ("你们好" etc.).
* It is NEVER in the push; it lives on the OIDB pending-request
* queue, so we ALWAYS fetch it (mirrors Lagrange's unconditional
* `FetchGroupRequests`; NapCat reads the equivalent
* `notify.postscript`). See issue #98.
* 2. The requester's UIN + nickname — only when not already resolved
* (the push carries a bare UID). Mirrors Lagrange's
* `dev/Lagrange.Core/.../MessagingLogic.cs:215-224`.
*
* These USED to be coupled — the comment fetch piggy-backed on the
* uin-resolve condition, so a requester whose uin was already cached
* silently lost their comment (bug #98). They're now decoupled inside
* `dispatchGroupInvite`; this guard just routes every uid-bearing
* group_invite onto the async path. */
private needsGroupInviteEnrich(
event: QQEventVariant,
): event is Extract<QQEventVariant, { kind: 'group_invite' }> {
return event.kind === 'group_invite' && !!event.fromUid;
}
private async dispatchAfterIdentityRefresh(
pkt: PacketInfo,
event: Extract<QQEventVariant, { kind: 'group_member_join' }>,
@@ -491,158 +492,61 @@ export class IncomingPacketPipeline {
pkt: PacketInfo,
event: Extract<QQEventVariant, { kind: 'group_invite' }>,
): Promise<number> {
const uid = event.fromUid;
if (uid) {
// Record the requester's identity up-front (synchronously), mirroring the
// friend_request path — uid-bearing group_invites take this async branch
// and would otherwise never store the inviter's uid↔uin when the uin is
// already known (needsProfile=false).
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid,
uin: event.fromUin > 0 ? event.fromUin : 0,
source: 'group_request',
});
const subType = event.subType === 'invite' ? 'invite' : 'add';
// ALWAYS fetch the verify comment (it's never in the push). UID→UIN
// waits only when the requester is still unresolved. Comment and
// identity are independent; `Promise.allSettled` so a flake on one
// path cannot kill the other.
const needsProfile = event.fromUin <= 0;
const [profileR, requestR] = await Promise.allSettled([
needsProfile
? this.deps.identity.resolveUin(uid, event.groupId)
: Promise.resolve(null),
this.deps.resolveGroupJoinRequest(event.groupId, uid, subType),
]);
if (needsProfile) {
if (
profileR.status === 'fulfilled' &&
profileR.value !== null &&
profileR.value > 0
) {
event.fromUin = profileR.value;
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid,
uin: event.fromUin,
source: 'group_request',
});
} else if (profileR.status === 'rejected') {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=enrichment_degraded eventKind=%j enrichment="stranger_profile" error=%j',
pkt.serviceCmd,
pkt.seqId,
event.kind,
profileR.reason instanceof Error
? profileR.reason.message
: String(profileR.reason),
]);
this.log.warn(
'failed to resolve stranger profile: uid=%s err=%s',
uid,
profileR.reason instanceof Error
? profileR.reason.message
: String(profileR.reason),
);
}
}
if (requestR.status === 'fulfilled' && requestR.value) {
// The verify text the requester typed; NapCat surfaces it as
// `notify.postscript`. Without this the OneBot `comment` field is
// empty — bug #98.
event.message = requestR.value.comment;
const request = requestR.value;
if (subType === 'invite' && request.targetUid) {
if (!event.invitedUid) {
event.invitedUid = request.targetUid;
}
if ((event.invitedUin ?? 0) <= 0 && request.targetUin > 0) {
event.invitedUin = request.targetUin;
}
}
const hasApprovalTuple =
Number.isSafeInteger(request.sequence) &&
request.sequence > 0 &&
Number.isSafeInteger(request.groupId) &&
request.groupId > 0 &&
Number.isSafeInteger(request.eventType) &&
request.eventType > 0;
if (hasApprovalTuple) {
if (subType === 'invite' && request.eventType === 2) {
// A bot self-invite must use the private Ark card's msgseq (#125),
// not the sequence returned by 0x10C0. Keep the legacy flag when
// correlation times out so the action can retry the cache later.
const cardSequence =
(await this.deps.resolveGroupInviteCardSequence?.(event.groupId)) ??
null;
if (cardSequence) {
event.flag = formatGroupRequestFlag({
groupId: event.groupId,
sequence: cardSequence,
eventType: 2,
filtered: false,
});
} else {
this.log.warn(
'invite-card msgseq unavailable before dispatch: groupId=%d uid=%s',
event.groupId,
uid,
);
}
} else {
event.flag = formatGroupRequestFlag(request);
}
}
} else if (requestR.status === 'rejected') {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=enrichment_degraded eventKind=%j enrichment="group_join_request" error=%j',
pkt.serviceCmd,
pkt.seqId,
event.kind,
requestR.reason instanceof Error
? requestR.reason.message
: String(requestR.reason),
]);
this.log.warn(
'failed to resolve group join request: groupId=%d uid=%s err=%s',
event.groupId,
uid,
requestR.reason instanceof Error
? requestR.reason.message
: String(requestR.reason),
);
}
// Self-invite notices omit the approval msgseq; the private card owns this event.
if (
event.subType === 'invite' &&
this.isSelfMemberIdentity(event.invitedUin ?? 0, event.invitedUid)
) {
return 0;
}
if ((event.invitedUin ?? 0) <= 0 && event.invitedUid) {
try {
const invited = await this.deps.identity.resolveUin(
event.invitedUid,
event.groupId,
);
const uid = event.fromUid;
if (invited !== null && invited > 0) {
event.invitedUin = invited;
}
} catch (error) {
this.log.warn(
'failed to resolve invited account: groupId=%d uid=%s err=%s',
event.groupId,
event.invitedUid,
error instanceof Error ? error.message : String(error),
);
}
if (!uid) {
throw new Error('group request omitted requester UID');
}
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid,
uin: event.fromUin,
source: 'group_request',
});
const request = await this.deps.resolveGroupJoinRequest(
event.groupId,
uid,
event.subType,
event.invitedUid,
);
if (!request) {
this.log.warn('pending group request not found: group=%d uid=%s', event.groupId, uid);
return 0;
}
if (request.eventType === 2) {
return 0;
}
event.message = request.comment;
event.flag = formatGroupRequestFlag(request);
const requesterUin = event.subType === 'invite' ? request.invitorUin : request.targetUin;
event.fromUin =
event.fromUin ||
requesterUin ||
(await this.deps.identity.resolveUin(uid, event.groupId)) ||
0;
if (event.fromUin === 0) {
this.log.warn('group request sender unavailable: group=%d uid=%s', event.groupId, uid);
}
if (event.subType === 'invite') {
event.invitedUid = request.targetUid;
event.invitedUin =
request.targetUin ||
(await this.deps.identity.resolveUin(request.targetUid, event.groupId)) ||
0;
}
try {
@@ -778,13 +682,6 @@ export class IncomingPacketPipeline {
source: 'friend_message',
});
if (event.inviteCardGroupUin && event.inviteCardSequence) {
this.deps.rememberGroupInviteCardSequence?.(
event.inviteCardGroupUin,
event.inviteCardSequence,
);
}
break;
case 'group_message': {
@@ -875,29 +772,18 @@ export class IncomingPacketPipeline {
}
case 'group_invite': {
// Defensive: never cache a uid→uin mapping where uin equals
// the group's own uin — that's the pollution signature the
// legacy decoder fallback produced. Pass 0 so `rememberUidUin`
// skips the map write (it short-circuits on uin <= 0) but the
// user row still gets upserted with the uid + group context.
const uinForCache =
event.fromUin > 0 && event.fromUin !== event.groupId ? event.fromUin : 0;
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.fromUid,
uin: uinForCache,
uin: event.fromUin,
source: 'group_request',
});
if (event.invitedUid) {
const invitedUin =
event.invitedUin && event.invitedUin !== event.groupId
? event.invitedUin
: 0;
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.invitedUid,
uin: invitedUin,
uin: event.invitedUin ?? 0,
source: 'group_request',
});
}
@@ -38,7 +38,9 @@ function okResult(data: Uint8Array): SendPacketResult {
function inviteCardMessage(sequence: number): PushMsgBody {
const json = JSON.stringify({
app: 'com.tencent.qun.invite',
jumpUrl: `mqqapi://group/invite_join?groupcode=12345&msgseq=${sequence}`,
meta: {
news: { jumpUrl: `mqqapi://group/invite_join?groupcode=12345&msgseq=${sequence}` },
},
});
const compressed = deflateSync(Buffer.from(json));
const data = new Uint8Array(compressed.length + 1);
@@ -38,6 +38,21 @@ function ctx(
}
describe('group invitation push carries the invitee (#394)', () => {
it('ignores unrelated notification commands', () => {
const content = protobuf_encode<GroupInvitation>({
cmd: 86,
info: {
inner: {
groupUin: GROUP_ID,
targetUid: 'u_invitee',
invitorUid: 'u_inviter',
},
},
});
expect(decodeGroupInvitation(ctx(content))).toEqual([]);
});
it('keeps the inviter as from* and the invitee as invited*', () => {
const identity = IdentityService.memory(String(SELF_UIN));
identity.rememberRequestIdentity({ uid: 'u_inviter', uin: 456, source: 'group_request' });
@@ -154,6 +154,7 @@ function makePipeline(
fetchGroupList,
fetchGroupMemberList,
resolveGroupJoinRequest: vi.fn(async () => null),
rememberGroupInviteCardSequence: vi.fn(() => true),
});
return { identity, pipeline, captured, fetchGroupList, fetchGroupMemberList };
}
@@ -1,19 +1,14 @@
// Pre-dispatch stranger resolve regression — when a group join
// request comes in, the push only carries the requester's UID. The
// pipeline must do an async UID-form FetchUserProfile lookup BEFORE
// emitting the event so the OneBot layer's `user_id` field is
// populated and the consumer bot's `get_stranger_info` lookup works.
//
// Cross-checked against Lagrange's flow:
// dev/Lagrange.Core/.../MessagingLogic.cs:215-224
// (FetchUserInfoEvent by uid → resolved uin → posted event)
import { describe, expect, it, vi } from 'vitest';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { QQEventVariant } from '@snowluma/protocol/events';
import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info';
import type { GroupInviteEvent, QQEventVariant } from '@snowluma/protocol/events';
import type {
GroupMemberInfo,
GroupRequestInfo,
QQGroupInfo,
UserProfileInfo,
} from '@snowluma/protocol/qq-info';
import type { PacketInfo } from '@snowluma/common/protocol-types';
function makeProfile(uin: number, uid = '', nickname = ''): UserProfileInfo {
@@ -38,7 +33,6 @@ function makePipeline(
opts: {
fetchProfileByUid?: vi.Mock;
resolveGroupJoinRequest?: vi.Mock;
resolveGroupInviteCardSequence?: vi.Mock;
} = {},
) {
const identity = IdentityService.memory('10001');
@@ -48,16 +42,14 @@ function makePipeline(
fetchProfile: async () => makeProfile(0),
fetchProfileByUid,
});
const resolveGroupJoinRequest = opts.resolveGroupJoinRequest ?? vi.fn(async () => null);
const resolveGroupInviteCardSequence =
opts.resolveGroupInviteCardSequence ?? vi.fn(async () => null);
const resolveGroupJoinRequest = opts.resolveGroupJoinRequest ?? vi.fn(async () => request());
const pipeline = new IncomingPacketPipeline({
identity,
events,
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest,
resolveGroupInviteCardSequence,
rememberGroupInviteCardSequence: vi.fn(() => true),
});
const captured: QQEventVariant[] = [];
@@ -72,456 +64,184 @@ function makePipeline(
captured,
fetchProfileByUid,
resolveGroupJoinRequest,
resolveGroupInviteCardSequence,
};
}
describe('IncomingPacketPipeline / stranger resolve on group_invite', () => {
it('calls fetchProfileByUid when group_invite has fromUin=0 + fromUid', async () => {
const fetchProfileByUid = vi.fn(async (_uid: string) =>
makeProfile(950929451, 'u_stranger_abc', '小明'),
);
function request(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInfo {
return {
groupId: 12345,
groupName: 'group',
targetUid: 'u_requester',
targetUin: 0,
targetName: '',
invitorUid: '',
invitorUin: 0,
invitorName: '',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 42,
state: 1,
notifyType: 7,
eventType: 1,
comment: 'please',
filtered: false,
...overrides,
};
}
function requestEvent(overrides: Partial<GroupInviteEvent> = {}): GroupInviteEvent {
return {
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 12345,
fromUin: 0,
fromUid: 'u_requester',
subType: 'add',
message: '',
flag: 'add:12345:u_requester',
...overrides,
};
}
async function receive(pipeline: IncomingPacketPipeline, event: GroupInviteEvent): Promise<void> {
pipeline.registerCmd('test.cmd', () => [event]);
await pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
}
describe('IncomingPacketPipeline / group requests', () => {
it('resolves an unknown requester before dispatch', async () => {
const fetchProfileByUid = vi.fn(async () => makeProfile(222, 'u_requester', 'Alice'));
const { pipeline, captured } = makePipeline({ fetchProfileByUid });
// Plant a parser that emits the user's exact bug-report shape:
// groupId set, fromUid is a string UID, fromUin=0 (decoder fix).
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1700000000,
selfUin: 10001,
groupId: 123456789,
fromUin: 0,
fromUid: 'u_stranger_abc',
subType: 'add',
message: '',
flag: 'add:123456789:u_stranger_abc',
} as QQEventVariant,
await receive(pipeline, requestEvent());
expect(fetchProfileByUid).toHaveBeenCalledWith('u_requester');
expect(captured).toEqual([
expect.objectContaining({
fromUin: 222,
message: 'please',
flag: 'slreq:1:42:12345:1:0',
}),
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
// Let the async hook flush.
await new Promise((r) => setTimeout(r, 10));
expect(fetchProfileByUid).toHaveBeenCalledWith('u_stranger_abc');
expect(captured).toHaveLength(1);
const event = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(event.fromUin).toBe(950929451); // ← patched in by the async resolve
expect(event.fromUid).toBe('u_stranger_abc');
expect(event.groupId).toBe(123456789);
});
it('still emits the event when fetchProfileByUid returns no uin (fail open)', async () => {
const fetchProfileByUid = vi.fn(async () => makeProfile(0));
const { pipeline, captured } = makePipeline({ fetchProfileByUid });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 12345,
it('keeps an actionable request when its sender cannot be identified', async () => {
const { pipeline, captured } = makePipeline();
await receive(pipeline, requestEvent());
expect(captured).toEqual([
expect.objectContaining({
fromUin: 0,
fromUid: 'u_no_such_user',
subType: 'add',
message: '',
flag: 'add:12345:u_no_such_user',
} as QQEventVariant,
flag: 'slreq:1:42:12345:1:0',
}),
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(fetchProfileByUid).toHaveBeenCalledOnce();
expect(captured).toHaveLength(1);
const event = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
// fromUin stays 0 — but the event still goes out so the bot can
// see the join request and at least respond using the uid in the
// flag.
expect(event.fromUin).toBe(0);
expect(event.fromUid).toBe('u_no_such_user');
});
it('still emits the event when fetchProfileByUid throws', async () => {
const fetchProfileByUid = vi.fn(async () => {
throw new Error('network down');
});
const { pipeline, captured } = makePipeline({ fetchProfileByUid });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 12345,
fromUin: 0,
fromUid: 'u_x',
subType: 'add',
message: '',
flag: 'add:12345:u_x',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({ fromUin: 0, fromUid: 'u_x' });
});
it('still fetches + applies the comment when fromUin is already cached (issue #98)', async () => {
// THE bug: the comment fetch used to piggy-back on the uin-resolve
// gate, so a requester whose uin was already in cache (group member
// roster, prior @-mention, re-application…) silently lost their
// verify text — the OneBot `comment` came out empty. The comment
// and the uin resolve are now decoupled: the comment is fetched
// unconditionally; only the (wasteful) profile lookup is skipped on
// a cache hit.
const fetchProfileByUid = vi.fn(async () => makeProfile(0));
const resolveGroupJoinRequest = vi.fn(async () => ({ comment: '求通过', sequence: 42 }));
const { pipeline, captured } = makePipeline({ fetchProfileByUid, resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 12345,
fromUin: 99999,
fromUid: 'u_known',
subType: 'add',
message: '',
flag: 'add:12345:u_known',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
// Profile lookup is skipped — the uin is already known, no wasted call…
expect(fetchProfileByUid).not.toHaveBeenCalled();
// …but the comment IS still fetched from the pending-request queue
// and applied to the emitted event.
expect(resolveGroupJoinRequest).toHaveBeenCalledWith(12345, 'u_known', 'add');
expect(captured).toHaveLength(1);
const ev = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(ev.fromUin).toBe(99999);
expect(ev.message).toBe('求通过');
});
it('populates event.message from the pending-request queue (NapCat parity)', async () => {
// User-reported bug: SnowLuma's group_invite event surfaces a
// bare uid + uin but the requester's verify text ("你们好") never
// lands in the OneBot `comment` field. NapCat shows the text via
// `notify.postscript` from `getGroupNotifies`; we mirror that by
// doing an `OIDB 0x10C0 fetchGroupRequests` lookup in the async
// pre-dispatch hook and patching `event.message` from the matching
// row's `comment`.
const fetchProfileByUid = vi.fn(async () =>
makeProfile(1957003260, 'u_UVLHYYqba27WPUzTrdZlCA', 'KitaIkuyo'),
);
const resolveGroupJoinRequest = vi.fn(async () => ({
comment: '你们好',
sequence: 1779543612823906,
}));
const { pipeline, captured } = makePipeline({
fetchProfileByUid,
resolveGroupJoinRequest,
});
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 950929451,
fromUin: 0,
fromUid: 'u_UVLHYYqba27WPUzTrdZlCA',
subType: 'add',
message: '',
flag: 'add:950929451:u_UVLHYYqba27WPUzTrdZlCA',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
it('fetches the comment even when the requester identity is already known', async () => {
const { pipeline, captured, resolveGroupJoinRequest, fetchProfileByUid } = makePipeline();
await receive(pipeline, requestEvent({ fromUin: 222 }));
expect(resolveGroupJoinRequest).toHaveBeenCalledWith(
950929451,
'u_UVLHYYqba27WPUzTrdZlCA',
12345,
'u_requester',
'add',
undefined,
);
expect(captured).toHaveLength(1);
const ev = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(ev.message).toBe('你们好');
expect(ev.fromUin).toBe(1957003260);
expect(fetchProfileByUid).not.toHaveBeenCalled();
expect(captured).toEqual([expect.objectContaining({ fromUin: 222, message: 'please' })]);
});
it('replaces the legacy identity flag with a canonical approval tuple', async () => {
const resolveGroupJoinRequest = vi.fn(async () => ({
groupId: 950929451,
groupName: 'group',
targetUid: 'u_target',
targetUin: 1957003260,
targetName: 'target',
invitorUid: 'u_inviter',
invitorUin: 0,
invitorName: '',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 1779543612823906,
state: 1,
eventType: 1,
comment: '你们好',
filtered: true,
}));
const { pipeline, captured } = makePipeline({ resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 950929451,
fromUin: 1957003260,
fromUid: 'u_target',
subType: 'add',
message: '',
flag: 'add:950929451:u_target',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({
message: '你们好',
flag: 'slreq:1:1779543612823906:950929451:1:1',
});
});
it('uses the private invite-card msgseq for a self-invite approval tuple', async () => {
const resolveGroupJoinRequest = vi.fn(async () => ({
groupId: 999,
groupName: 'group',
targetUid: 'self',
targetUin: 10001,
targetName: 'self',
invitorUid: 'u_inviter',
invitorUin: 456,
invitorName: 'inviter',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 111,
state: 1,
eventType: 2,
comment: '',
filtered: false,
}));
const resolveGroupInviteCardSequence = vi.fn(async () => 778899);
const { pipeline, captured } = makePipeline({
resolveGroupJoinRequest,
resolveGroupInviteCardSequence,
});
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 999,
fromUin: 456,
fromUid: 'u_inviter',
subType: 'invite',
message: '',
flag: 'invite:999:u_inviter',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(resolveGroupInviteCardSequence).toHaveBeenCalledWith(999);
expect(captured[0]).toMatchObject({
flag: 'slreq:1:778899:999:2:0',
invitedUin: 10001,
invitedUid: 'self',
});
});
it('fills the invitee from the pending-request row (#394)', async () => {
const resolveGroupJoinRequest = vi.fn(async () => ({
groupId: 1,
groupName: 'group',
targetUid: 'u_invitee',
targetUin: 789,
targetName: 'invitee',
invitorUid: 'u_inviter',
invitorUin: 456,
invitorName: 'inviter',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 42,
state: 1,
eventType: 2,
comment: '',
filtered: false,
}));
const { pipeline, captured } = makePipeline({ resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 1,
fromUin: 456,
fromUid: 'u_inviter',
subType: 'invite',
message: '',
flag: 'invite:1:u_inviter',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(captured[0]).toMatchObject({
fromUin: 456,
invitedUin: 789,
invitedUid: 'u_invitee',
});
});
it('runs the profile + request lookups in parallel (independent failures)', async () => {
// Profile lookup succeeds, request lookup fails — event should
// still carry the resolved uin but no comment. The dispatch
// doesn't block on the slower / failing path.
const fetchProfileByUid = vi.fn(async () => makeProfile(12345, 'u_x', 'OK'));
const resolveGroupJoinRequest = vi.fn(async () => {
throw new Error('queue lookup failed');
});
const { pipeline, captured } = makePipeline({
fetchProfileByUid,
resolveGroupJoinRequest,
});
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 1,
fromUin: 0,
fromUid: 'u_x',
subType: 'add',
message: '',
flag: 'add:1:u_x',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
const ev = captured[0] as Extract<QQEventVariant, { kind: 'group_invite' }>;
expect(ev.fromUin).toBe(12345); // profile succeeded
expect(ev.message).toBe(''); // request lookup threw, message left empty
});
it('invite subtype matches the request on invitorUid (not targetUid)', async () => {
// For `subType: 'invite'` (group member invited the bot or another
// user), the pending-request row's REQUESTER field is
// `invitorUid` not `targetUid`. The dep contract makes this
// explicit so the bridge facade can route the lookup correctly.
const resolveGroupJoinRequest = vi.fn(async () => ({
comment: 'come join',
sequence: 999,
}));
const { pipeline } = makePipeline({ resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 1,
fromUin: 0,
fromUid: 'u_inviter',
subType: 'invite',
message: '',
flag: 'invite:1:u_inviter',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
expect(resolveGroupJoinRequest).toHaveBeenCalledWith(1, 'u_inviter', 'invite');
});
it('does not treat fromUin === groupId as an unresolved identity', async () => {
const fetchProfileByUid = vi.fn(async () =>
makeProfile(1957003260, 'u_kitaikuyo', 'KitaIkuyo'),
it('uses the sender and approval tuple from the matched filtered request', async () => {
const resolveGroupJoinRequest = vi.fn(async () =>
request({ targetUin: 222, filtered: true }),
);
const { pipeline, captured } = makePipeline({ fetchProfileByUid });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 950929451,
fromUin: 950929451,
fromUid: 'u_kitaikuyo',
subType: 'add',
message: '',
flag: 'add:950929451:u_kitaikuyo',
} as QQEventVariant,
]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
const { pipeline, captured, fetchProfileByUid } = makePipeline({ resolveGroupJoinRequest });
await receive(pipeline, requestEvent());
expect(fetchProfileByUid).not.toHaveBeenCalled();
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({
fromUin: 950929451,
fromUid: 'u_kitaikuyo',
groupId: 950929451,
});
expect(captured).toEqual([
expect.objectContaining({ fromUin: 222, flag: 'slreq:1:42:12345:1:1' }),
]);
});
it('skips both lookups when fromUid is empty (no uid to look up by)', async () => {
const fetchProfileByUid = vi.fn(async () => makeProfile(0));
const resolveGroupJoinRequest = vi.fn(async () => null);
const { pipeline, captured } = makePipeline({ fetchProfileByUid, resolveGroupJoinRequest });
pipeline.registerCmd('test.cmd', () => [
{
kind: 'group_invite',
time: 1,
selfUin: 10001,
groupId: 12345,
fromUin: 0,
fromUid: '',
subType: 'add',
message: '',
flag: 'add:12345:',
} as QQEventVariant,
it('matches an invitation approval by inviter and invitee', async () => {
const resolveGroupJoinRequest = vi.fn(async () =>
request({
invitorUid: 'u_inviter',
invitorUin: 456,
targetUid: 'u_invitee',
targetUin: 789,
eventType: 22,
notifyType: 5,
}),
);
const { pipeline, captured } = makePipeline({ resolveGroupJoinRequest });
await receive(
pipeline,
requestEvent({ subType: 'invite', fromUid: 'u_inviter', invitedUid: 'u_invitee' }),
);
expect(resolveGroupJoinRequest).toHaveBeenCalledWith(
12345,
'u_inviter',
'invite',
'u_invitee',
);
expect(captured).toEqual([
expect.objectContaining({
fromUin: 456,
invitedUin: 789,
invitedUid: 'u_invitee',
flag: 'slreq:1:42:12345:22:0',
}),
]);
});
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise((r) => setTimeout(r, 10));
// No uid → nothing to query by → neither lookup runs, event still emits.
expect(fetchProfileByUid).not.toHaveBeenCalled();
it('leaves self invitations to the card without querying or waiting', async () => {
const { pipeline, captured, resolveGroupJoinRequest, fetchProfileByUid } = makePipeline();
await receive(pipeline, requestEvent({ subType: 'invite', invitedUin: 10001 }));
expect(captured).toEqual([]);
expect(resolveGroupJoinRequest).not.toHaveBeenCalled();
expect(fetchProfileByUid).not.toHaveBeenCalled();
});
it('does not substitute a list sequence for the self-invite card sequence', async () => {
const resolveGroupJoinRequest = vi.fn(async () =>
request({ eventType: 2, targetUin: 10001 }),
);
const { pipeline, captured } = makePipeline({ resolveGroupJoinRequest });
await receive(pipeline, requestEvent({ subType: 'invite' }));
expect(captured).toEqual([]);
});
it.each(['missing', 'failed'])(
'does not emit an incomplete request after a %s lookup',
async (outcome) => {
const resolveGroupJoinRequest =
outcome === 'missing'
? vi.fn(async () => null)
: vi.fn(async () => {
throw new Error('lookup failed');
});
const { pipeline, captured, fetchProfileByUid } = makePipeline({
resolveGroupJoinRequest,
});
await receive(pipeline, requestEvent());
expect(captured).toEqual([]);
expect(resolveGroupJoinRequest).toHaveBeenCalledOnce();
expect(fetchProfileByUid).not.toHaveBeenCalled();
},
);
it('does not treat a requester UIN equal to the group number as unresolved', async () => {
const { pipeline, captured, identity, fetchProfileByUid } = makePipeline();
await receive(pipeline, requestEvent({ fromUin: 12345 }));
expect(fetchProfileByUid).not.toHaveBeenCalled();
expect(captured[0]).toMatchObject({ fromUin: 12345 });
expect(identity.findUinByUid('u_requester')).toBe(12345);
});
it('rejects a request without its requester UID', async () => {
const { pipeline, captured, resolveGroupJoinRequest } = makePipeline();
await receive(pipeline, requestEvent({ fromUid: '' }));
expect(captured).toEqual([]);
expect(resolveGroupJoinRequest).not.toHaveBeenCalled();
expect(captured).toHaveLength(1);
});
});
@@ -559,6 +279,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),
});
return { identity, pipeline };
}
@@ -672,6 +393,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),
});
const captured: QQEventVariant[] = [];
events.onAny((e) => captured.push(e as QQEventVariant));
@@ -734,43 +456,3 @@ 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(),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
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();
});
});
@@ -121,7 +121,26 @@ function makePipeline(
events,
fetchGroupList: opts.fetchGroupList ?? vi.fn(async () => {}),
fetchGroupMemberList: opts.fetchGroupMemberList ?? vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
resolveGroupJoinRequest: vi.fn(async () => ({
groupId: 123,
groupName: '',
targetUid: 'u_stranger',
targetUin: 0,
targetName: '',
invitorUid: '',
invitorUin: 0,
invitorName: '',
operatorUid: '',
operatorUin: 0,
operatorName: '',
sequence: 42,
state: 1,
notifyType: 7,
eventType: 1,
comment: '',
filtered: false,
})),
rememberGroupInviteCardSequence: vi.fn(() => true),
});
const dispatched: Array<{ event: QQEventVariant; req: number | undefined }> = [];
events.onAny((event) => {