diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index df96d272..4213c608 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -52,6 +52,7 @@ export class Bridge implements BridgeInterface { this.apis = buildApiHub(this); this.identity.setFetcher({ fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin), + fetchProfileByUid: (uid) => this.apis.contacts.fetchUserProfileByUid(uid), fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid), }); this.pipeline = new IncomingPacketPipeline({ @@ -59,15 +60,6 @@ export class Bridge implements BridgeInterface { events: this.events, refreshMemberCache: (groupId, refreshGroupList, forceMemberList) => this.refreshMemberCache(groupId, refreshGroupList, forceMemberList), - resolveStrangerProfile: async (uid) => { - try { - const p = await this.apis.contacts.fetchUserProfileByUid(uid); - if (p.uin <= 0) return null; - return { uin: p.uin, nickname: p.nickname }; - } catch { - return null; - } - }, resolveGroupJoinRequest: async (groupId, uid, subType) => { const [main, filtered] = await Promise.allSettled([ this.apis.contacts.fetchGroupRequestsByUid(false), diff --git a/packages/core/tests/bridge-member-identity.test.ts b/packages/core/tests/bridge-member-identity.test.ts index 0d209b5f..f86b6d68 100644 --- a/packages/core/tests/bridge-member-identity.test.ts +++ b/packages/core/tests/bridge-member-identity.test.ts @@ -35,28 +35,19 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo { }; } -class RefreshingBridge extends Bridge { - readonly memberFetches: Array<{ groupId: number; force: boolean }> = []; - - constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) { - super(identity); - // `fetchGroupMemberList` moved from Bridge onto `apis.contacts` - // under the #6 refactor — patch the method on the constructed - // ContactsApi instance to intercept calls + record them for - // assertions. (Direct property assignment works because the - // method is just an own property on the Api instance, not on - // its prototype.) - this.apis.contacts.fetchGroupMemberList = async ( - groupId: number, - options: { force?: boolean } = {}, - ): Promise => { - this.memberFetches.push({ groupId, force: Boolean(options.force) }); - for (const member of this.refreshedMembers) { - this.identity.updateGroupMember(groupId, member); - } - return this.refreshedMembers; - }; - } +function emptyProfile(uin: number, uid: string) { + return { + uin, + uid, + nickname: '', + remark: '', + qid: '', + sex: 'unknown', + age: 0, + sign: '', + avatar: '', + level: 0, + }; } function makePacket(): PacketInfo { @@ -87,11 +78,21 @@ async function waitForEvent(events: GroupMemberJoin[]): Promise } describe('Bridge group member identity refresh', () => { - it('forces a fresh member list before dispatching an unresolved join event', async () => { + it('resolves an unresolved join UIN via inbound profile before dispatch', async () => { const member = makeGroupMember(22222, 'u_new_member'); const identity = IdentityService.memory(SELF_UIN); identity.rememberGroups([makeGroup()]); - const bridge = new RefreshingBridge(identity, [member]); + const bridge = new Bridge(identity); + const profileFetches: string[] = []; + const memberFetches: Array<{ groupId: number; force: boolean }> = []; + bridge.apis.contacts.fetchUserProfileByUid = async (uid) => { + profileFetches.push(uid); + return emptyProfile(member.uin, uid); + }; + bridge.apis.contacts.fetchGroupMemberList = async (groupId, options = {}) => { + memberFetches.push({ groupId, force: Boolean(options.force) }); + return []; + }; const seen: GroupMemberJoin[] = []; bridge.registerCmd('test.member_join', () => [{ @@ -111,9 +112,9 @@ describe('Bridge group member identity refresh', () => { bridge.onPacket(makePacket()); const event = await waitForEvent(seen); - expect(bridge.memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]); + expect(profileFetches).toEqual([member.uid]); + expect(memberFetches.some((fetch) => fetch.force)).toBe(false); expect(event.userUin).toBe(member.uin); - expect(event.operatorUin).toBe(member.uin); }); it('remembers UID mappings from realtime request events', () => { diff --git a/packages/core/tests/identity-service.test.ts b/packages/core/tests/identity-service.test.ts index 985bd4dc..f7e24102 100644 --- a/packages/core/tests/identity-service.test.ts +++ b/packages/core/tests/identity-service.test.ts @@ -974,3 +974,146 @@ describe('IdentityService.resolveUid', () => { expect(fetchProfile).not.toHaveBeenCalled(); }); }); + +describe('IdentityService inbound UID→UIN', () => { + function makeProfile(uin: number, uid: string): UserProfileInfo { + return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0 }; + } + + it('findUinByUid treats a numeric uid as that uin without consulting maps', () => { + const identity = IdentityService.memory(SELF_UIN); + identity.rememberRequestIdentity({ uid: '22999', uin: 11111 }); + expect(identity.findUinByUid('22999')).toBe(22999); + expect(identity.findUinByUid('0')).toBeNull(); + expect(identity.findUinByUid('')).toBeNull(); + }); + + it('returns the cached uin without invoking fetchProfileByUid', async () => { + const identity = IdentityService.memory(SELF_UIN); + identity.rememberRequestIdentity({ uid: 'u_known', uin: 12345 }); + const fetchProfileByUid = vi.fn(async () => makeProfile(999, 'should-not-be-used')); + identity.setFetcher({ + fetchProfile: async () => makeProfile(0, ''), + fetchProfileByUid, + }); + + await expect(identity.resolveUin('u_known')).resolves.toBe(12345); + expect(fetchProfileByUid).not.toHaveBeenCalled(); + }); + + it('does not call fetchProfileByUid for a numeric uid', async () => { + const identity = IdentityService.memory(SELF_UIN); + const fetchProfileByUid = vi.fn(async () => makeProfile(1, '1')); + identity.setFetcher({ + fetchProfile: async () => makeProfile(0, ''), + fetchProfileByUid, + }); + + await expect(identity.resolveUin('22999')).resolves.toBe(22999); + expect(fetchProfileByUid).not.toHaveBeenCalled(); + }); + + it('falls back to fetchProfileByUid on miss and returns the profile uin', async () => { + const identity = IdentityService.memory(SELF_UIN); + const fetchProfileByUid = vi.fn(async (uid: string) => { + identity.rememberUserProfile(makeProfile(88888, uid)); + return makeProfile(88888, uid); + }); + identity.setFetcher({ + fetchProfile: async () => makeProfile(0, ''), + fetchProfileByUid, + }); + + await expect(identity.resolveUin('u_stranger')).resolves.toBe(88888); + expect(fetchProfileByUid).toHaveBeenCalledWith('u_stranger'); + }); + + it('returns the profile uin even when the fetcher forgets to remember', async () => { + const identity = IdentityService.memory(SELF_UIN); + identity.setFetcher({ + fetchProfile: async () => makeProfile(0, ''), + fetchProfileByUid: async () => makeProfile(77777, 'u_forgetful'), + }); + + await expect(identity.resolveUin('u_forgetful')).resolves.toBe(77777); + }); + + it('does not pull a group member list even when groupId is provided', async () => { + const identity = IdentityService.memory(SELF_UIN); + const fetchGroupMemberList = vi.fn(async () => []); + const fetchProfileByUid = vi.fn(async () => makeProfile(66666, 'u_invitee')); + identity.setFetcher({ + fetchProfile: async () => makeProfile(0, ''), + fetchProfileByUid, + fetchGroupMemberList, + }); + + await expect(identity.resolveUin('u_invitee', GROUP_ID)).resolves.toBe(66666); + expect(fetchGroupMemberList).not.toHaveBeenCalled(); + expect(fetchProfileByUid).toHaveBeenCalledWith('u_invitee'); + }); + + it('does not pull a group member list when the inbound fetcher is absent', async () => { + const identity = IdentityService.memory(SELF_UIN); + const fetchGroupMemberList = vi.fn(async () => []); + identity.setFetcher({ + fetchProfile: async () => makeProfile(0, ''), + fetchGroupMemberList, + }); + + await expect(identity.resolveUin('u_none', GROUP_ID)).resolves.toBeNull(); + expect(fetchGroupMemberList).not.toHaveBeenCalled(); + }); + + it('uses a mapping remembered before the inbound fetcher throws', async () => { + const identity = IdentityService.memory(SELF_UIN); + identity.setFetcher({ + fetchProfile: async () => makeProfile(0, ''), + fetchProfileByUid: async (uid: string) => { + identity.rememberUserProfile(makeProfile(55555, uid)); + throw new Error('transport reset after remember'); + }, + }); + + await expect(identity.resolveUin('u_remembered')).resolves.toBe(55555); + }); + + it('returns null on miss, fetcher error, empty profile, or missing inbound fetcher', async () => { + const identity = IdentityService.memory(SELF_UIN); + + await expect(identity.resolveUin('u_none')).resolves.toBeNull(); + + identity.setFetcher({ fetchProfile: async () => makeProfile(0, '') }); + await expect(identity.resolveUin('u_none')).resolves.toBeNull(); + + identity.setFetcher({ + fetchProfile: async () => makeProfile(0, ''), + fetchProfileByUid: async () => makeProfile(0, 'u_none'), + }); + await expect(identity.resolveUin('u_none')).resolves.toBeNull(); + + identity.setFetcher({ + fetchProfile: async () => makeProfile(0, ''), + fetchProfileByUid: async () => { + throw new Error('oidb down'); + }, + }); + await expect(identity.resolveUin('u_none')).resolves.toBeNull(); + }); + + it('does not enter Identity degraded when the inbound fetcher throws', async () => { + const dbPath = tempDbPath('inbound-fetch-throw'); + const identity = new IdentityService(SELF_UIN, dbPath); + identity.setFetcher({ + fetchProfile: async () => makeProfile(0, ''), + fetchProfileByUid: async () => { + throw new Error('oidb down'); + }, + }); + + await expect(identity.resolveUin('u_none')).resolves.toBeNull(); + expect(identity.persistenceStatus.state).toBe('healthy'); + expect(identity.persistenceStatus.pendingWrites).toBe(0); + identity.close(); + }); +}); diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index 0e77a219..49f27c18 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -495,7 +495,6 @@ describe('parseMsgPush Event0x210 subType=364 (friend remark synchronization)', identity, events: new BridgeEventBus(), refreshMemberCache: vi.fn(async () => false), - resolveStrangerProfile: vi.fn(async () => null), resolveGroupJoinRequest: vi.fn(async () => null), }); pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush); @@ -979,8 +978,7 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache const [event] = parseMsgPush(makeGroupAdminPacket('u_unknown', true), identity) as GroupAdminEvent[]; expect(event.kind).toBe('group_admin'); - // fromUin (the group id) is the resolve fallback — it must not be - // confused for a real, promotable member. + expect(event.userUin).toBe(0); expect(identity.findGroupMember(GROUP_ID, GROUP_ID)).toBeNull(); }); }); diff --git a/packages/protocol/src/identity-service.ts b/packages/protocol/src/identity-service.ts index 3158d6b7..8c4e308b 100644 --- a/packages/protocol/src/identity-service.ts +++ b/packages/protocol/src/identity-service.ts @@ -44,6 +44,8 @@ interface PendingIdentityWrite { */ export interface IdentityFetcher { fetchProfile(uin: number): Promise; + /** Inbound UID→UIN network hop. Must not be used to refresh a group roster. */ + fetchProfileByUid?(uid: string): Promise; fetchGroupMemberList?(groupId: number): Promise; } @@ -431,10 +433,36 @@ export class IdentityService { throw new Error(`failed to resolve UID for UIN ${normalized}`); } + /** + * Inbound UID→UIN. Sync cache/DB (including a numeric UID) first; on miss, + * `fetchProfileByUid`. Returns null when still unknown. Never throws for a + * miss, a fetcher error, or a missing fetcher — inbound events still emit. + * Does not pull a group member list; that remains a roster side-effect. + */ + async resolveUin(uid: string, groupId?: number): Promise { + const cached = this.findUinByUid(uid, groupId); + if (cached !== null) return cached; + + const normalized = normalizeUid(uid); + if (!normalized || !this.fetcher?.fetchProfileByUid) return null; + + try { + const profile = await this.fetcher.fetchProfileByUid(normalized); + const uin = normalizeUin(profile.uin); + if (uin !== null) return uin; + } catch { + // Fall through: a fetcher that remembered then threw still counts as a hit. + } + return this.findUinByUid(normalized, groupId); + } + findUinByUid(uid: string, groupId?: number): number | null { const normalized = normalizeUid(uid); if (!normalized) return null; + const numeric = numericUidAsUin(normalized); + if (numeric !== null) return numeric; + if (groupId !== undefined) { const member = this.findGroupMemberByUid(groupId, normalized); if (member) return member.uin; @@ -1303,6 +1331,12 @@ function normalizeUid(uid: unknown): string { return typeof uid === 'string' ? uid.trim() : ''; } +/** A UID that is itself a decimal UIN. Protocol fact, not a packet-header guess. */ +function numericUidAsUin(uid: string): number | null { + if (!/^\d+$/.test(uid)) return null; + return normalizeUin(uid); +} + function normalizeUin(uin: unknown): number | null { if (typeof uin === 'number' && Number.isFinite(uin)) { const n = Math.trunc(uin); diff --git a/packages/protocol/src/msg-push/decoders/event-0x210.ts b/packages/protocol/src/msg-push/decoders/event-0x210.ts index e5e30869..1fa14e29 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x210.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x210.ts @@ -22,8 +22,7 @@ import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans'; import type { MsgPushContext } from '../context'; import { Event0x210SubType } from '../enums'; import { - buildTemplateMap, findTemplateValue, - parseU64OrZero, + buildTemplateMap, c2cRoutingUin, findTemplateValue, resolveUidToUin, } from '../helpers'; import type { MsgPushDecoder } from '../registry'; @@ -177,7 +176,7 @@ function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] { kind: 'friend_request', time: ctx.head.timestamp, selfUin: ctx.selfUin, - fromUin: resolveUidToUin(ctx.identity, 0, sourceUid, ctx.fromUin), + fromUin: resolveUidToUin(ctx.identity, 0, sourceUid), fromUid: sourceUid, message: request.info.message ?? '', flag: sourceUid, @@ -199,7 +198,7 @@ function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] { kind: 'friend_recall', time: recall.info.time ?? ctx.head.timestamp, selfUin: ctx.selfUin, - userUin: resolveUidToUin(ctx.identity, 0, peerUid, ctx.fromUin), + userUin: resolveUidToUin(ctx.identity, 0, peerUid), msgSeq: recall.info.clientSequence ?? 0, clientSeq: recall.info.clientSequence ?? 0, recalledBySelf: isSelfRecall, @@ -211,7 +210,7 @@ function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] { const nf = protobuf_decode(ctx.content); if (!nf?.info) return []; const newFriendUid = nf.info.uid ?? ''; - const newFriendUin = resolveUidToUin(ctx.identity, 0, newFriendUid, ctx.fromUin); + const newFriendUin = c2cRoutingUin(ctx.identity, newFriendUid, ctx.fromUin); if (newFriendUin <= 0) return []; // can't surface a `user_id`-less friend_add to OneBot const ev: FriendAddEvent = { kind: 'friend_add', @@ -240,7 +239,7 @@ function decodeInputStatus(ctx: MsgPushContext): QQEventVariant[] { kind: 'friend_input_status', time: ctx.head.timestamp, selfUin: ctx.selfUin, - userUin: resolveUidToUin(ctx.identity, 0, fromUid, ctx.fromUin), + userUin: resolveUidToUin(ctx.identity, 0, fromUid), userUid: fromUid, eventType, statusText: inputStatusText(eventType), @@ -285,16 +284,15 @@ function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] { const templates = buildTemplateMap(grayTip.msgTemplParam ?? []); const actor = findTemplateValue(templates, 'uin_str1'); const target = findTemplateValue(templates, 'uin_str2'); - const senderUin = resolveUidToUin(ctx.identity, 0, actor, parseU64OrZero(actor)); - const routeFromUin = resolveUidToUin(ctx.identity, 0, ctx.fromUid, ctx.fromUin); + const senderUin = resolveUidToUin(ctx.identity, 0, actor); + const routeFromUin = c2cRoutingUin(ctx.identity, ctx.fromUid, ctx.fromUin); // The gray-tip template only identifies the two poke endpoints. The C2C // routing head owns the conversation peer: outbound notices use `to`, // while inbound notices use `from`, just like ordinary friend messages. const sentBySelf = routeFromUin > 0 && routeFromUin === ctx.selfUin; const peerUin = sentBySelf - ? resolveUidToUin( + ? c2cRoutingUin( ctx.identity, - 0, ctx.responseHead?.toUid ?? '', ctx.responseHead?.toUin ?? 0, ) @@ -311,7 +309,7 @@ function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] { selfUin: ctx.selfUin, peerUin, senderUin, - targetUin: resolveUidToUin(ctx.identity, 0, target, parseU64OrZero(target)), + targetUin: resolveUidToUin(ctx.identity, 0, target), action: findTemplateValue(templates, 'action_str', 'alt_str1'), suffix: findTemplateValue(templates, 'suffix_str'), actionImgUrl: findTemplateValue(templates, 'action_img_url'), diff --git a/packages/protocol/src/msg-push/decoders/event-0x2dc.ts b/packages/protocol/src/msg-push/decoders/event-0x2dc.ts index 95e1595c..87443903 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x2dc.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x2dc.ts @@ -21,7 +21,6 @@ import type { MsgPushContext } from '../context'; import { Event0x2DCSubType } from '../enums'; import { buildTemplateMap, findTemplateValue, - parseU64OrZero, resolveUidToUin, unwrapGroupNotifyPayload, } from '../helpers'; @@ -50,8 +49,8 @@ function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] { time: mute.data.timestamp ?? ctx.head.timestamp, selfUin: ctx.selfUin, groupId: mute.groupUin ?? 0, - operatorUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.operatorUid ?? '', ctx.fromUin), - userUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? '', 0), + operatorUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.operatorUid ?? ''), + userUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? ''), duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration, }; return [ev]; @@ -69,8 +68,8 @@ function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] { selfUin: ctx.selfUin, groupId: notify.groupUin ?? 0, operatorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, - notify.recall.operatorUid || notify.operatorUid || '', ctx.fromUin), - authorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, recalled.authorUid ?? '', ctx.fromUin), + notify.recall.operatorUid || notify.operatorUid || ''), + authorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, recalled.authorUid ?? ''), msgSeq: recalled.sequence ?? 0, }; return [ev]; @@ -89,8 +88,8 @@ function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] { time: ctx.head.timestamp, selfUin: ctx.selfUin, groupId: notify.groupUin ?? 0, - userUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, actor, parseU64OrZero(actor)), - targetUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, target, parseU64OrZero(target)), + userUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, actor), + targetUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, target), action: findTemplateValue(templates, 'action_str', 'alt_str1'), suffix: findTemplateValue(templates, 'suffix_str'), actionImgUrl: findTemplateValue(templates, 'action_img_url'), @@ -111,7 +110,7 @@ function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] { selfUin: ctx.selfUin, groupId: essence.groupUin ?? notify.groupUin ?? 0, senderUin: essence.memberUin ?? 0, - operatorUin: essence.operatorUin ?? ctx.fromUin, + operatorUin: essence.operatorUin ?? 0, msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0, random: essence.random ?? 0, set: setFlag === 1, @@ -200,7 +199,7 @@ function decodeGroupName(ctx: MsgPushContext): QQEventVariant[] { // Operator is a group member → resolves from the roster. Fall back to 0 // (not ctx.fromUin, which on a 0x2DC push is the group id) so an // unresolved operator never surfaces the group id as user_id. - operatorUin: resolveUidToUin(ctx.identity, groupId, notify?.operatorUid ?? '', 0), + operatorUin: resolveUidToUin(ctx.identity, groupId, notify?.operatorUid ?? ''), name, }; return [ev]; @@ -235,7 +234,7 @@ function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] { time: ctx.head.timestamp, selfUin: ctx.selfUin, groupId, - operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, ctx.fromUin), + operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid), operatorUid, msgSeq, emojiId, diff --git a/packages/protocol/src/msg-push/decoders/group-admin.ts b/packages/protocol/src/msg-push/decoders/group-admin.ts index 79e932c0..c2a1b0f4 100644 --- a/packages/protocol/src/msg-push/decoders/group-admin.ts +++ b/packages/protocol/src/msg-push/decoders/group-admin.ts @@ -19,7 +19,7 @@ export const decodeGroupAdmin: MsgPushDecoder = (ctx) => { if (!adminUid) return []; const groupId = admin.groupUin ?? 0; const set = !!enableUid; - const userUin = resolveUidToUin(ctx.identity, groupId, adminUid, ctx.fromUin); + 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 diff --git a/packages/protocol/src/msg-push/decoders/group-join-request.ts b/packages/protocol/src/msg-push/decoders/group-join-request.ts index 4ca79ed4..bd512ba4 100644 --- a/packages/protocol/src/msg-push/decoders/group-join-request.ts +++ b/packages/protocol/src/msg-push/decoders/group-join-request.ts @@ -15,15 +15,8 @@ export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => { time: ctx.head.timestamp, selfUin: ctx.selfUin, groupId: join.groupUin ?? 0, - // Strangers (not in our cache, not yet group members) won't resolve - // here — pass 0 instead of ctx.fromUin (which on a group-scoped push - // IS the group's own uin, so falling back to it produces a bogus - // `fromUin === groupId` collision). The packet-pipeline's pre- - // dispatch hook does an async UID-form FetchUserProfile lookup to - // fill in the uin + nickname before the event is emitted — same - // shape as Lagrange's flow at - // `dev/Lagrange.Core/.../MessagingLogic.cs:215-224`. - fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? '', 0), + // Strangers stay unresolved here. Pipeline fills UIN via Identity.resolveUin. + fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? ''), fromUid: join.targetUid ?? '', subType: 'add', message: '', @@ -41,7 +34,7 @@ export const decodeGroupInvitation: MsgPushDecoder = (ctx) => { time: ctx.head.timestamp, selfUin: ctx.selfUin, groupId: inner.groupUin ?? 0, - fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? '', 0), + fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? ''), fromUid: inner.invitorUid ?? '', subType: 'invite', message: '', @@ -58,7 +51,7 @@ export const decodeGroupInvite: MsgPushDecoder = (ctx) => { time: ctx.head.timestamp, selfUin: ctx.selfUin, groupId: invite.groupUin ?? 0, - fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? '', 0), + fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? ''), fromUid: invite.invitorUid ?? '', subType: 'invite', message: '', diff --git a/packages/protocol/src/msg-push/decoders/group-member-change.ts b/packages/protocol/src/msg-push/decoders/group-member-change.ts index 1b47e8f0..7b44a1c5 100644 --- a/packages/protocol/src/msg-push/decoders/group-member-change.ts +++ b/packages/protocol/src/msg-push/decoders/group-member-change.ts @@ -31,8 +31,8 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => { time: ctx.head.timestamp, selfUin: ctx.selfUin, groupId, - userUin: resolveUidToUin(ctx.identity, groupId, userUid, 0), - operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0), + userUin: resolveUidToUin(ctx.identity, groupId, userUid), + operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid), userUid, operatorUid, joinType: joinTypeFromOperationType(change.decreaseType ?? 0), @@ -66,7 +66,7 @@ export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => { const dt = change.decreaseType ?? 0; const groupId = change.groupUin ?? 0; const userUid = change.memberUid ?? ''; - const userUin = resolveUidToUin(ctx.identity, groupId, userUid, 0); + const userUin = resolveUidToUin(ctx.identity, groupId, userUid); let operatorUid: string; let operatorUin: number; @@ -83,7 +83,7 @@ export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => { operatorUid = dt === 3 ? decodeNestedOperatorUid(operatorBytes, 'group member decrease type=3') : decodeGroupChangeOperatorUid(operatorBytes, `group member decrease type=${dt}`); - operatorUin = resolveUidToUin(ctx.identity, groupId, operatorUid, 0); + operatorUin = resolveUidToUin(ctx.identity, groupId, operatorUid); } const ev: GroupMemberLeave = { kind: 'group_member_leave', @@ -119,7 +119,7 @@ export const decodeGroupSelfJoined: MsgPushDecoder = (ctx) => { groupId, userUin: ctx.selfUin, userUid: ctx.identity.selfUid ?? '', - operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, 0), + operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid), operatorUid, }; return [ev]; diff --git a/packages/protocol/src/msg-push/helpers.ts b/packages/protocol/src/msg-push/helpers.ts index 8fab4635..6d623dce 100644 --- a/packages/protocol/src/msg-push/helpers.ts +++ b/packages/protocol/src/msg-push/helpers.ts @@ -62,28 +62,27 @@ export function decompressData( return { ok: true, text: Buffer.from(data).toString('utf8'), outputBytes: data.length }; } -export function isNumericUin(value: string): boolean { - return value.length > 0 && /^\d+$/.test(value); -} - export function parseU64OrZero(value: string): number { if (!value) return 0; const n = parseInt(value, 10); return isNaN(n) ? 0 : n; } -// Cascades group-scoped lookup → in-memory map → SQLite. -// No network fallback on the parse hot path: missing identities fall back to -// `fallback` and downstream events drive a roster refresh asynchronously. -export function resolveUidToUin(identity: IdentityService, groupId: number, uid: string, fallback = 0): number { - if (!uid) return fallback; - if (isNumericUin(uid)) { - const n = parseInt(uid, 10); - if (!isNaN(n)) return n; - } - const uin = identity.findUinByUid(uid, groupId || undefined); - if (uin !== null) return uin; - return fallback; +/** Sync Identity lookup. Miss is unresolved (0). Decoder must not invent a UIN. */ +export function resolveUidToUin(identity: IdentityService, groupId: number, uid: string): number { + if (!uid) return 0; + return identity.findUinByUid(uid, groupId || undefined) ?? 0; +} + +/** + * C2C routing hop. Prefer Identity on the hop UID; otherwise use that hop's + * own wire UIN. This is not a fallback that assigns an unrelated header UIN + * to a different UID. + */ +export function c2cRoutingUin(identity: IdentityService, uid: string, wireUin: number): number { + const resolved = resolveUidToUin(identity, 0, uid); + if (resolved > 0) return resolved; + return wireUin > 0 ? wireUin : 0; } const OPERATOR_BYTES_PREVIEW_LENGTH = 32; diff --git a/packages/protocol/src/packet-pipeline.ts b/packages/protocol/src/packet-pipeline.ts index 70214417..921eef3c 100644 --- a/packages/protocol/src/packet-pipeline.ts +++ b/packages/protocol/src/packet-pipeline.ts @@ -46,16 +46,6 @@ export interface PacketPipelineDeps { * and `refreshGroupList` was false). */ refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise; - /** - * Resolve a stranger profile by UID — used to fill in the requester's - * uin + nickname on group-join-request and friend-request events - * where the push only carries a uid. Mirrors Lagrange's - * `FetchUserInfoEvent.Create(targetUid)` path - * (`dev/Lagrange.Core/.../MessagingLogic.cs:215-224`). Returns null - * on lookup failure so the dispatch path can proceed with the bare - * uid-only event. - */ - resolveStrangerProfile(uid: string): Promise<{ uin: number; nickname: string } | null>; /** * Resolve the verify message ("postscript") + server sequence number * for a pending group-join / group-invite. The OIDB push only @@ -459,34 +449,28 @@ export class IncomingPacketPipeline { // 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). uin equal to the group's own uin is - // the legacy decoder-pollution signature → pass 0 so the map write is - // skipped (rememberUidUin short-circuits on uin <= 0). + // already known (needsProfile=false). this.deps.identity.rememberRequestIdentity({ groupId: event.groupId, uid, - uin: event.fromUin > 0 && event.fromUin !== event.groupId ? event.fromUin : 0, + 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). Resolve - // the UID→UIN profile only when the requester isn't already known — - // `fromUin === groupId` is the legacy cache-pollution signature - // (decoder fell back to the group's own uin) and must force a - // re-resolve so the cache self-heals. The two are independent OIDB - // calls (0xFE1_2 profile + 0x10C0 request queue); `Promise.allSettled` - // so a flake on one path can't kill the other. - const needsProfile = event.fromUin <= 0 || (event.groupId > 0 && event.fromUin === event.groupId); + // 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.resolveStrangerProfile(uid) : Promise.resolve(null), + 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 && profileR.value.uin > 0) { - event.fromUin = profileR.value.uin; - // uin was unknown/polluted at entry; now resolved → self-heal the map. + if (profileR.status === 'fulfilled' && profileR.value !== null && profileR.value > 0) { + event.fromUin = profileR.value; this.deps.identity.rememberRequestIdentity({ groupId: event.groupId, uid, @@ -560,15 +544,13 @@ export class IncomingPacketPipeline { private async prepareGroupMemberJoinIdentity(event: Extract): Promise { this.resolveMemberIdentityFromCache(event); - if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false; + if (event.userUin > 0 || !event.userUid) return false; - const refreshed = await this.deps.refreshMemberCache( - event.groupId, - !this.deps.identity.findGroup(event.groupId) || this.isSelfMemberIdentity(event.userUin, event.userUid), - true, - ); + const uin = await this.deps.identity.resolveUin(event.userUid, event.groupId); + if (uin !== null) event.userUin = uin; this.resolveMemberIdentityFromCache(event); - return refreshed; + // Roster refresh stays a post-dispatch side-effect, not the UIN hop. + return false; } private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void { diff --git a/packages/protocol/tests/msg-push/friend-poke.test.ts b/packages/protocol/tests/msg-push/friend-poke.test.ts index e5d8ba4c..e1bcc689 100644 --- a/packages/protocol/tests/msg-push/friend-poke.test.ts +++ b/packages/protocol/tests/msg-push/friend-poke.test.ts @@ -4,16 +4,14 @@ import type { GeneralGrayTipInfo } from '@snowluma/proto-defs/notify'; import { protobuf_encode } from '@snowluma/proton'; import { describe, expect, it } from 'vitest'; -import type { IdentityService } from '../../src/identity-service'; +import { IdentityService } from '../../src/identity-service'; import { parseMsgPush } from '../../src/msg-push'; const SELF_UIN = 10001; const FRIEND_A = 20001; const FRIEND_B = 20002; -const identity = { - findUinByUid: () => null, -} as unknown as IdentityService; +const identity = IdentityService.memory(String(SELF_UIN)); function friendPokePacket( peerUin: number, diff --git a/packages/protocol/tests/msg-push/sysmsg-dedup.test.ts b/packages/protocol/tests/msg-push/sysmsg-dedup.test.ts index 2a90931b..d852bf78 100644 --- a/packages/protocol/tests/msg-push/sysmsg-dedup.test.ts +++ b/packages/protocol/tests/msg-push/sysmsg-dedup.test.ts @@ -20,7 +20,7 @@ import type { PacketInfo } from '@snowluma/common/protocol-types'; import { protobuf_encode } from '@snowluma/proton'; import type { PushMsg, PushMsgBody } from '@snowluma/proto-defs/message'; import type { GroupChange, OnlineDeviceNotify } from '@snowluma/proto-defs/notify'; -import type { IdentityService } from '../../src/identity-service'; +import { IdentityService } from '../../src/identity-service'; import { deriveSysMsgDedupIdentity, parseMsgPush, @@ -28,7 +28,7 @@ import { type SysMsgDedupIdentity, } from '../../src/msg-push'; -const identity = { findUinByUid: () => null, findFriend: () => undefined } as unknown as IdentityService; +const identity = IdentityService.memory('2000000001'); function pushPacket(message: PushMsgBody): PacketInfo { return { @@ -43,7 +43,7 @@ function pushPacket(message: PushMsgBody): PacketInfo { } // A type-33 group member-increase push (the #137 shape). `memberUid` is a -// numeric string so resolveUidToUin returns it without touching identity. +// numeric string so Identity.findUinByUid returns it without a map lookup. function memberIncreasePush(opts: { groupId: number; memberUin: number; sequence: number; msgId: number }): PacketInfo { return pushPacket({ responseHead: { fromUin: opts.groupId, fromUid: '' }, diff --git a/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts b/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts index 8353df47..bf982186 100644 --- a/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts +++ b/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts @@ -13,24 +13,31 @@ 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 } from '@snowluma/protocol/qq-info'; +import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info'; import type { PacketInfo } from '@snowluma/common/protocol-types'; +function makeProfile(uin: number, uid = '', nickname = ''): UserProfileInfo { + return { uin, uid, nickname, remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0 }; +} + function makePipeline(opts: { - resolveStrangerProfile?: vi.Mock; + fetchProfileByUid?: vi.Mock; resolveGroupJoinRequest?: vi.Mock; resolveGroupInviteCardSequence?: vi.Mock; } = {}) { const identity = IdentityService.memory('10001'); const events = new BridgeEventBus(); - const resolveStrangerProfile = opts.resolveStrangerProfile ?? vi.fn(async () => null); + const fetchProfileByUid = opts.fetchProfileByUid ?? vi.fn(async () => makeProfile(0)); + identity.setFetcher({ + fetchProfile: async () => makeProfile(0), + fetchProfileByUid, + }); const resolveGroupJoinRequest = opts.resolveGroupJoinRequest ?? vi.fn(async () => null); const resolveGroupInviteCardSequence = opts.resolveGroupInviteCardSequence ?? vi.fn(async () => null); const pipeline = new IncomingPacketPipeline({ identity, events, refreshMemberCache: vi.fn(async () => false), - resolveStrangerProfile, resolveGroupJoinRequest, resolveGroupInviteCardSequence, }); @@ -40,16 +47,14 @@ function makePipeline(opts: { return { identity, pipeline, events, captured, - resolveStrangerProfile, resolveGroupJoinRequest, resolveGroupInviteCardSequence, + fetchProfileByUid, resolveGroupJoinRequest, resolveGroupInviteCardSequence, }; } 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 }); + it('calls fetchProfileByUid when group_invite has fromUin=0 + fromUid', async () => { + const fetchProfileByUid = vi.fn(async (_uid: string) => makeProfile(950929451, 'u_stranger_abc', '小明')); + 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). @@ -70,7 +75,7 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { // Let the async hook flush. await new Promise(r => setTimeout(r, 10)); - expect(resolveStrangerProfile).toHaveBeenCalledWith('u_stranger_abc'); + expect(fetchProfileByUid).toHaveBeenCalledWith('u_stranger_abc'); expect(captured).toHaveLength(1); const event = captured[0] as Extract; expect(event.fromUin).toBe(950929451); // ← patched in by the async resolve @@ -78,9 +83,9 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { 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 }); + 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', @@ -92,7 +97,7 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); await new Promise(r => setTimeout(r, 10)); - expect(resolveStrangerProfile).toHaveBeenCalledOnce(); + expect(fetchProfileByUid).toHaveBeenCalledOnce(); expect(captured).toHaveLength(1); const event = captured[0] as Extract; // fromUin stays 0 — but the event still goes out so the bot can @@ -102,9 +107,9 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { 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 }); + 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', @@ -128,9 +133,9 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { // and the uin resolve are now decoupled: the comment is fetched // unconditionally; only the (wasteful) profile lookup is skipped on // a cache hit. - const resolveStrangerProfile = vi.fn(async () => null); + const fetchProfileByUid = vi.fn(async () => makeProfile(0)); const resolveGroupJoinRequest = vi.fn(async () => ({ comment: '求通过', sequence: 42 })); - const { pipeline, captured } = makePipeline({ resolveStrangerProfile, resolveGroupJoinRequest }); + const { pipeline, captured } = makePipeline({ fetchProfileByUid, resolveGroupJoinRequest }); pipeline.registerCmd('test.cmd', () => [{ kind: 'group_invite', @@ -143,7 +148,7 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { await new Promise(r => setTimeout(r, 10)); // Profile lookup is skipped — the uin is already known, no wasted call… - expect(resolveStrangerProfile).not.toHaveBeenCalled(); + 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'); @@ -161,14 +166,12 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { // doing an `OIDB 0x10C0 fetchGroupRequests` lookup in the async // pre-dispatch hook and patching `event.message` from the matching // row's `comment`. - const resolveStrangerProfile = vi.fn(async () => ({ - uin: 1957003260, nickname: 'KitaIkuyo', - })); + const fetchProfileByUid = vi.fn(async () => makeProfile(1957003260, 'u_UVLHYYqba27WPUzTrdZlCA', 'KitaIkuyo')); const resolveGroupJoinRequest = vi.fn(async () => ({ comment: '你们好', sequence: 1779543612823906, })); const { pipeline, captured } = makePipeline({ - resolveStrangerProfile, resolveGroupJoinRequest, + fetchProfileByUid, resolveGroupJoinRequest, }); pipeline.registerCmd('test.cmd', () => [{ @@ -262,14 +265,12 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { // 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 resolveStrangerProfile = vi.fn(async () => ({ - uin: 12345, nickname: 'OK', - })); + 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({ - resolveStrangerProfile, resolveGroupJoinRequest, + fetchProfileByUid, resolveGroupJoinRequest, }); pipeline.registerCmd('test.cmd', () => [{ @@ -310,25 +311,15 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { expect(resolveGroupJoinRequest).toHaveBeenCalledWith(1, 'u_inviter', 'invite'); }); - it('forces re-resolve when fromUin === groupId (legacy cache pollution)', async () => { - // Pre-fix builds stored ` → ` 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 }); + it('does not treat fromUin === groupId as an unresolved identity', async () => { + const fetchProfileByUid = vi.fn(async () => makeProfile(1957003260, 'u_kitaikuyo', 'KitaIkuyo')); + const { pipeline, captured } = makePipeline({ fetchProfileByUid }); pipeline.registerCmd('test.cmd', () => [{ kind: 'group_invite', time: 1, selfUin: 10001, groupId: 950929451, - fromUin: 950929451, // ← POLLUTED: equals groupId + fromUin: 950929451, fromUid: 'u_kitaikuyo', subType: 'add', message: '', flag: 'add:950929451:u_kitaikuyo', } as QQEventVariant]); @@ -336,19 +327,19 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); await new Promise(r => setTimeout(r, 10)); - expect(resolveStrangerProfile).toHaveBeenCalledWith('u_kitaikuyo'); + expect(fetchProfileByUid).not.toHaveBeenCalled(); expect(captured).toHaveLength(1); expect(captured[0]).toMatchObject({ - fromUin: 1957003260, // ← corrected by the async resolve + fromUin: 950929451, fromUid: 'u_kitaikuyo', groupId: 950929451, }); }); it('skips both lookups when fromUid is empty (no uid to look up by)', async () => { - const resolveStrangerProfile = vi.fn(async () => null); + const fetchProfileByUid = vi.fn(async () => makeProfile(0)); const resolveGroupJoinRequest = vi.fn(async () => null); - const { pipeline, captured } = makePipeline({ resolveStrangerProfile, resolveGroupJoinRequest }); + const { pipeline, captured } = makePipeline({ fetchProfileByUid, resolveGroupJoinRequest }); pipeline.registerCmd('test.cmd', () => [{ kind: 'group_invite', @@ -361,7 +352,7 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { await new Promise(r => setTimeout(r, 10)); // No uid → nothing to query by → neither lookup runs, event still emits. - expect(resolveStrangerProfile).not.toHaveBeenCalled(); + expect(fetchProfileByUid).not.toHaveBeenCalled(); expect(resolveGroupJoinRequest).not.toHaveBeenCalled(); expect(captured).toHaveLength(1); }); @@ -397,7 +388,6 @@ describe('IncomingPacketPipeline / #1 group card self-heal', () => { identity, events, refreshMemberCache: vi.fn(async () => false), - resolveStrangerProfile: vi.fn(async () => null), resolveGroupJoinRequest: vi.fn(async () => null), }); return { identity, pipeline }; @@ -463,7 +453,6 @@ describe('IncomingPacketPipeline / group_card_change from message traffic', () = const pipeline = new IncomingPacketPipeline({ identity, events, refreshMemberCache: vi.fn(async () => false), - resolveStrangerProfile: vi.fn(async () => null), resolveGroupJoinRequest: vi.fn(async () => null), }); const captured: QQEventVariant[] = []; diff --git a/packages/protocol/tests/packet-pipeline-trace.test.ts b/packages/protocol/tests/packet-pipeline-trace.test.ts index cc6dd52c..ef1e7939 100644 --- a/packages/protocol/tests/packet-pipeline-trace.test.ts +++ b/packages/protocol/tests/packet-pipeline-trace.test.ts @@ -75,15 +75,23 @@ function msgPushContext( function makePipeline(opts: { refreshMemberCache?: () => Promise; - resolveStrangerProfile?: () => Promise<{ uin: number; nickname: string } | null>; + fetchProfileByUid?: () => Promise<{ uin: number; uid: string; nickname: string; remark: string; qid: string; sex: string; age: number; sign: string; avatar: string; level: number }>; } = {}) { const identity = IdentityService.memory('10001'); + if (opts.fetchProfileByUid) { + identity.setFetcher({ + fetchProfile: async () => ({ + uin: 0, uid: '', nickname: '', remark: '', qid: '', sex: 'unknown', + age: 0, sign: '', avatar: '', level: 0, + }), + fetchProfileByUid: opts.fetchProfileByUid, + }); + } const events = new BridgeEventBus(); const pipeline = new IncomingPacketPipeline({ identity, events, refreshMemberCache: opts.refreshMemberCache ?? vi.fn(async () => false), - resolveStrangerProfile: opts.resolveStrangerProfile ?? vi.fn(async () => null), resolveGroupJoinRequest: vi.fn(async () => null), }); const dispatched: Array<{ event: QQEventVariant; req: number | undefined }> = []; @@ -200,7 +208,7 @@ describe('IncomingPacketPipeline TRACE lifecycle', () => { } }); - it('records degraded enrichment but still completes after dispatch', async () => { + it('completes join identity enrichment without treating roster refresh as the UIN hop', async () => { const entries: LogEntry[] = []; setLogLevel('trace'); const unsubscribe = subscribeLogs((entry) => entries.push(entry)); @@ -227,7 +235,6 @@ describe('IncomingPacketPipeline TRACE lifecycle', () => { expect(packetTrace(entries).map((entry) => entry.message)).toEqual([ 'packet_branch serviceCmd="Trace.Command" seqId=77 parser=1 branch=parser_events events=1', 'packet_branch serviceCmd="Trace.Command" seqId=77 branch=enrichment_started eventKind="group_member_join" enrichment="identity_refresh"', - 'packet_branch serviceCmd="Trace.Command" seqId=77 branch=enrichment_degraded eventKind="group_member_join" enrichment="identity_refresh" error="fixture refresh failed"', 'packet_branch serviceCmd="Trace.Command" seqId=77 branch=dispatch eventKind="group_member_join" mode=enriched', expect.stringMatching(/^packet_terminal serviceCmd="Trace\.Command" seqId=77 outcome=completed reason=dispatch_complete events=1 dispatched=1 parserErrors=0 elapsedMs=\d+$/), ]); @@ -305,7 +312,21 @@ describe('IncomingPacketPipeline TRACE lifecycle', () => { const unsubscribe = subscribeLogs((entry) => entries.push(entry)); try { const { pipeline, dispatched } = makePipeline({ - resolveStrangerProfile: () => profile, + fetchProfileByUid: async () => { + const resolved = await profile; + return { + uin: resolved.uin, + uid: 'u_stranger', + nickname: resolved.nickname, + remark: '', + qid: '', + sex: 'unknown', + age: 0, + sign: '', + avatar: '', + level: 0, + }; + }, }); pipeline.registerCmd('Trace.Command', () => [{ kind: 'group_invite',