Files
SnowLuma/packages/bridge/tests/packet-pipeline-stranger-resolve.test.ts
T
DrSmoothl 8631453940 fix(events): self-heal group_invite cache pollution from pre-fix builds
User report: after [a4909ec], log STILL shows
  群邀请 950929451 -> [bot group(950929451)]
  get_stranger_info params=user_id=950929451 → 未知昵称

But NapCat and a sibling SnowLuma bot in the same group BOTH decoded
the same push as `QQ:1957003260 nickname:KitaIkuyo`. So the wire is
correct — our bot is just looking it up wrong.

Root cause: **legacy cache pollution**. The pre-fix decoder fallback
stored `<requester_uid> → <groupUin>` in the identity DB whenever
`resolveUidToUin` missed (because the fallback `ctx.fromUin` on a
group-scoped push IS the group's own uin). After upgrading to
[a4909ec], `decodeGroupJoinRequest` calls `resolveUidToUin` which
hits the polluted in-memory map (re-populated from SQLite at boot)
and returns the groupUin instead of 0. The new `needsStrangerResolve`
guard only fired on `fromUin <= 0` — so the polluted value flowed
straight through and re-emitted the bug.

Two-part heal:

  1. `needsStrangerResolve` now ALSO fires when `fromUin === groupId`
     — the pollution signature. A real requester's uin can never
     equal the group's own uin, so this is a safe override that
     forces the async UID-form FetchUserProfile lookup, which then
     `rememberUidUin`s the correct mapping on success (eviction is
     already wired in identity-service.ts:468-471).

  2. `rememberEventIdentity` for group_invite now passes `uin: 0`
     when `event.fromUin === event.groupId`, so future writes don't
     re-pollute the cache (`rememberUidUin` short-circuits on
     normalized uin ≤ 0).

Cache self-heals on first event after upgrade — no manual DB nuke
needed.

Regression test pins the legacy-pollution path: feeds an event
where `fromUin === groupId` (matching the user's log), verifies the
resolver fires and patches fromUin to the correct value.
2026-05-23 18:40:01 +08:00

188 lines
7.5 KiB
TypeScript

// 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/bridge/packet-pipeline';
import { BridgeEventBus } from '@snowluma/bridge/event-bus';
import { IdentityService } from '@snowluma/bridge/identity-service';
import type { QQEventVariant } from '@snowluma/bridge/events';
import type { PacketInfo } from '@snowluma/common/protocol-types';
function makePipeline(opts: {
resolveStrangerProfile?: vi.Mock;
} = {}) {
const identity = IdentityService.memory('10001');
const events = new BridgeEventBus();
const resolveStrangerProfile = opts.resolveStrangerProfile ?? vi.fn(async () => null);
const pipeline = new IncomingPacketPipeline({
identity,
events,
refreshMemberCache: vi.fn(async () => false),
resolveStrangerProfile,
});
const captured: QQEventVariant[] = [];
events.onAny((event) => { captured.push(event as QQEventVariant); });
return { pipeline, events, captured, resolveStrangerProfile };
}
describe('IncomingPacketPipeline / stranger resolve on group_invite', () => {
it('calls resolveStrangerProfile(uid) when group_invite has fromUin=0 + fromUid', async () => {
const resolveStrangerProfile = vi.fn(async (_uid: string) => ({
uin: 950929451, nickname: '小明',
}));
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
// 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]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
// Let the async hook flush.
await new Promise(r => setTimeout(r, 10));
expect(resolveStrangerProfile).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 resolveStrangerProfile returns null (fail open)', async () => {
const resolveStrangerProfile = vi.fn(async () => null);
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 12345, fromUin: 0, fromUid: 'u_no_such_user',
subType: 'add', message: '', flag: 'add:12345:u_no_such_user',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
expect(resolveStrangerProfile).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 resolveStrangerProfile throws', async () => {
const resolveStrangerProfile = vi.fn(async () => { throw new Error('network down'); });
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
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('skips the stranger resolve when fromUin is already populated (cache hit)', async () => {
// If the decoder's `resolveUidToUin` already found the uin in
// the local cache (e.g. group member roster), we shouldn't waste
// a wire call.
const resolveStrangerProfile = vi.fn(async () => null);
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 12345, fromUin: 99999, fromUid: 'u_known',
subType: 'invite', message: '', flag: 'invite:12345:u_known',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
expect(resolveStrangerProfile).not.toHaveBeenCalled();
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({ fromUin: 99999, fromUid: 'u_known' });
});
it('forces re-resolve when fromUin === groupId (legacy cache pollution)', async () => {
// Pre-fix builds stored `<requester_uid> → <groupUin>` because
// the decoder's fallback was `ctx.fromUin` (= group's own uin on
// a group-scoped push). After upgrade, the decoder's
// resolveUidToUin would re-read that polluted mapping and emit
// event.fromUin === groupId. The `fromUin <= 0` check alone
// wouldn't fire the async resolve, so the bug would persist.
// This guard catches that signature and forces a re-lookup, so
// the cache self-heals on the next event.
const resolveStrangerProfile = vi.fn(async () => ({
uin: 1957003260, nickname: 'KitaIkuyo',
}));
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 950929451,
fromUin: 950929451, // ← POLLUTED: equals groupId
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));
expect(resolveStrangerProfile).toHaveBeenCalledWith('u_kitaikuyo');
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({
fromUin: 1957003260, // ← corrected by the async resolve
fromUid: 'u_kitaikuyo',
groupId: 950929451,
});
});
it('skips the stranger resolve when fromUid is empty (no uid to look up by)', async () => {
const resolveStrangerProfile = vi.fn(async () => null);
const { pipeline, captured } = makePipeline({ resolveStrangerProfile });
pipeline.registerCmd('test.cmd', () => [{
kind: 'group_invite',
time: 1, selfUin: 10001,
groupId: 12345, fromUin: 0, fromUid: '',
subType: 'add', message: '', flag: 'add:12345:',
} as QQEventVariant]);
pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
await new Promise(r => setTimeout(r, 10));
expect(resolveStrangerProfile).not.toHaveBeenCalled();
expect(captured).toHaveLength(1);
});
});