fix(onebot): distinguish group invitation identities

Expose joining members, inviters and request operators separately.
Preserve existing notice fields and report unavailable invitation identities explicitly.

Refs #643
This commit is contained in:
DrSmoothl committed 2026-11-06 23:37:00 +08:00
1 parent 7425cfae20
commit 9edc255a02
20 files changed
+853 -63

No files matched your search

+3
View File
@@ -346,6 +346,9 @@ export interface GroupMemberJoin extends QQEvent {
operatorUin: number;
userUid?: string;
operatorUid?: string;
/** Independent invitation origin; never inferred from the operator. */
invitorUid?: string;
invitorUin?: number;
/**
* Admission mode derived from GroupChange field 4. This is deliberately
* separate from QQ's nested invitation-source enum, which has different
@@ -1,9 +1,17 @@
import { protobuf_decode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify';
import { decodeGroupChangeOperatorUid, decodeNestedOperatorUid, resolveUidToUin } from '../helpers';
import {
decodeGroupChangeOperatorUid,
decodeNestedOperatorUid,
decodeRawOperatorUid,
resolveUidToUin,
} from '../helpers';
import type { MsgPushDecoder } from '../registry';
const log = createLogger('MsgPush.GroupJoin');
function joinTypeFromOperationType(raw: number): NonNullable<GroupMemberJoin['joinType']> {
// QQ uses bit 0x80 as a flag on the PkgType=33 operation code. Clear only
// that bit: other high bits remain significant in the native handler. The
@@ -26,6 +34,22 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
change.operatorBytes ?? new Uint8Array(0),
'group member increase',
);
const operation = (change.decreaseType ?? 0) - ((change.decreaseType ?? 0) & 0x80);
const origin = ctx.responseHead?.grp?.messageKey?.joinExtra?.origin;
// QQ consumes this independent origin only for operation 2. Type 1
// identifies a QR-code sharer; neither that person nor the approving
// operator is evidence of an invitation.
const invitorUid =
operation === 2 && origin?.type !== 1 && origin?.uid?.length
? decodeRawOperatorUid(origin.uid, 'group member invitation origin')
: '';
log.trace(
'join identity: group=%d operation=%d originType=%s inviterProvided=%s',
groupId,
operation,
origin?.type === undefined ? 'absent' : String(origin.type),
Boolean(invitorUid),
);
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
@@ -35,6 +59,9 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid),
userUid,
operatorUid,
...(invitorUid
? { invitorUid, invitorUin: resolveUidToUin(ctx.identity, groupId, invitorUid) }
: {}),
joinType: joinTypeFromOperationType(change.decreaseType ?? 0),
};
return [ev];
+59 -9
View File
@@ -464,8 +464,8 @@ export class IncomingPacketPipeline {
return (
event.kind === 'group_member_join' &&
event.groupId > 0 &&
event.userUin <= 0 &&
Boolean(event.userUid)
((event.userUin <= 0 && Boolean(event.userUid)) ||
((event.invitorUin ?? 0) <= 0 && Boolean(event.invitorUid)))
);
}
@@ -601,17 +601,46 @@ export class IncomingPacketPipeline {
): Promise<void> {
this.resolveMemberIdentityFromCache(event);
if (event.userUin > 0 || !event.userUid) {
return;
}
const results = await Promise.allSettled(
(
[
['userUid', 'userUin'],
['invitorUid', 'invitorUin'],
] as const
).map(async ([uidKey, uinKey]) => {
const uid = event[uidKey];
const uin = await this.deps.identity.resolveUin(event.userUid, event.groupId);
if (!uid || (event[uinKey] ?? 0) > 0) {
return;
}
if (uin !== null) {
event.userUin = uin;
}
const uin = await this.deps.identity.resolveUin(uid, event.groupId);
if (uin !== null) {
event[uinKey] = uin;
} else {
this.log.warn(
'group join identity unavailable: group=%d role=%s',
event.groupId,
uidKey,
);
}
}),
);
this.resolveMemberIdentityFromCache(event);
const failures = results.filter((result) => result.status === 'rejected');
if (failures.length) {
throw new AggregateError(
failures.map((result) => result.reason),
`group join identity lookup failed: ${failures
.map(({ reason }) =>
reason instanceof Error ? reason.message : String(reason),
)
.join('; ')}`,
);
}
}
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
@@ -634,6 +663,18 @@ export class IncomingPacketPipeline {
event.operatorUin = uin;
}
}
if (
event.kind === 'group_member_join' &&
(event.invitorUin ?? 0) <= 0 &&
event.invitorUid
) {
const uin = this.deps.identity.findUinByUid(event.invitorUid, event.groupId);
if (uin !== null) {
event.invitorUin = uin;
}
}
}
private isSelfMemberIdentity(uin: number, uid?: string): boolean {
@@ -744,6 +785,15 @@ export class IncomingPacketPipeline {
}
case 'group_member_join':
if (event.invitorUid) {
this.deps.identity.rememberRequestIdentity({
groupId: event.groupId,
uid: event.invitorUid,
uin: event.invitorUin ?? 0,
source: 'group_request',
});
}
this.deps.identity.rememberGroupMemberIdentity(event.groupId, {
uid: event.userUid,
uin: event.userUin,
@@ -3,7 +3,8 @@ import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import { IdentityService } from '@snowluma/protocol/identity-service';
import type { GroupInviteEvent, QQEventVariant } from '@snowluma/protocol/events';
import type { GroupInviteEvent, GroupMemberJoin, QQEventVariant } from '@snowluma/protocol/events';
import { subscribeLogs } from '@snowluma/common/logger';
import type {
GroupMemberInfo,
GroupRequestInfo,
@@ -111,6 +112,99 @@ async function receive(pipeline: IncomingPacketPipeline, event: GroupInviteEvent
await pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo);
}
describe('IncomingPacketPipeline / independent join inviter', () => {
function join(): GroupMemberJoin {
return {
kind: 'group_member_join',
time: 1,
selfUin: 10001,
groupId: 12345,
userUid: 'u_member',
userUin: 10002,
operatorUid: 'u_admin',
operatorUin: 10003,
invitorUid: 'u_inviter',
invitorUin: 0,
joinType: 'approve',
};
}
it('resolves an inviter even when the joining member is already known', async () => {
const fetchProfileByUid = vi.fn(async () => makeProfile(10004, 'u_inviter'));
const { pipeline, captured, resolveGroupJoinRequest } = makePipeline({ fetchProfileByUid });
await pipeline.processEvents({ serviceCmd: 'test.cmd' } as PacketInfo, [join()]);
expect(captured).toEqual([
expect.objectContaining({ userUin: 10002, operatorUin: 10003, invitorUin: 10004 }),
]);
expect(fetchProfileByUid).toHaveBeenCalledExactlyOnceWith('u_inviter');
expect(resolveGroupJoinRequest).not.toHaveBeenCalled();
});
it('keeps the event observable when the inviter cannot be resolved', async () => {
const fetchProfileByUid = vi.fn(async () => {
throw new Error('profile unavailable');
});
const { pipeline, captured } = makePipeline({ fetchProfileByUid });
const warnings: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.level === 'warn') {
warnings.push(entry.message);
}
});
try {
await pipeline.processEvents({ serviceCmd: 'test.cmd' } as PacketInfo, [join()]);
} finally {
unsubscribe();
}
expect(captured).toEqual([expect.objectContaining({ invitorUin: 0, operatorUin: 10003 })]);
expect(
warnings.some((message) => message.includes('group join identity unavailable')),
).toBe(true);
});
it('waits for both identities before dispatching a join', async () => {
let finishInviter!: (profile: UserProfileInfo) => void;
const fetchProfileByUid = vi.fn((uid: string) =>
uid === 'u_member'
? Promise.resolve(makeProfile(10002, uid))
: new Promise<UserProfileInfo>((resolve) => {
finishInviter = resolve;
}),
);
const { pipeline, captured } = makePipeline({ fetchProfileByUid });
const pending = pipeline.processEvents({ serviceCmd: 'test.cmd' } as PacketInfo, [
{ ...join(), userUin: 0 },
]);
await vi.waitFor(() => expect(fetchProfileByUid).toHaveBeenCalledTimes(2));
expect(captured).toEqual([]);
finishInviter(makeProfile(10004, 'u_inviter'));
await pending;
expect(captured).toEqual([expect.objectContaining({ userUin: 10002, invitorUin: 10004 })]);
});
it('retains the original identity failure in the warning', async () => {
const { pipeline, identity, captured } = makePipeline();
vi.spyOn(identity, 'resolveUin').mockRejectedValueOnce(new Error('identity store closed'));
const warnings: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.level === 'warn') {
warnings.push(entry.message);
}
});
try {
await pipeline.processEvents({ serviceCmd: 'test.cmd' } as PacketInfo, [join()]);
} finally {
unsubscribe();
}
expect(captured).toHaveLength(1);
expect(warnings.some((message) => message.includes('identity store closed'))).toBe(true);
});
});
describe('IncomingPacketPipeline / group requests', () => {
it('resolves an unknown requester before dispatch', async () => {
const fetchProfileByUid = vi.fn(async () => makeProfile(222, 'u_requester', 'Alice'));