diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts index f777df2a..b6ee5e0a 100644 --- a/packages/core/src/bridge/apis/contacts.ts +++ b/packages/core/src/bridge/apis/contacts.ts @@ -1,5 +1,5 @@ import { GroupInviteTracker } from '@snowluma/protocol/group-invite-tracker'; -import { isSelfGroupInvitation } from '@snowluma/protocol/qq-info'; +import { groupRequestSubType } from '@snowluma/protocol/qq-info'; import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys'; import { FetchFriendListPage, @@ -12,7 +12,8 @@ import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/conta import { FetchGroupRequests, FetchGroupRequestsByUid, - groupRequestOperationType, + groupRequestNotifyType, + type DecodedGroupRequest, } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests'; import { FetchRobotUinRanges, @@ -79,19 +80,43 @@ export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boole ); } -function normalizeGroupRequestSequence( - rawSequence: bigint | number | undefined, +function groupRequestMetadata( + raw: Pick< + DecodedGroupRequest, + 'sequence' | 'state' | 'eventType' | 'comment' | 'operateTransInfo' + >, groupId: number, -): number { - const sequence = Number(rawSequence ?? 0); + filtered: boolean, +) { + const sequence = Number(raw.sequence ?? 0); if (!Number.isSafeInteger(sequence) || sequence <= 0) { throw new Error( - `invalid group-request sequence: group=${groupId} sequence=${String(rawSequence ?? 0)}`, + `invalid group-request sequence: group=${groupId} sequence=${String(raw.sequence ?? 0)}`, ); } - return sequence; + const eventType = raw.eventType ?? 0; + const notifyType = groupRequestNotifyType(eventType); + + if (notifyType === undefined) { + log.warn( + 'unsupported group-request wire type: group=%d sequence=%d type=%d', + groupId, + sequence, + eventType, + ); + } + + return { + sequence, + state: raw.state ?? 0, + eventType, + notifyType, + comment: raw.comment ?? '', + filtered, + operateTransInfo: raw.operateTransInfo?.length ? raw.operateTransInfo : undefined, + }; } const MEMBER_LIST_TTL_MS = 60_000; @@ -556,18 +581,6 @@ export class ContactsApi { this.ctx.identity.findUidByUin(operatorUin, groupId) || this.ctx.identity.findUidByUin(operatorUin) || ''; - const notifyType = raw.eventType ?? 0; - const operationType = groupRequestOperationType(notifyType); - const sequence = normalizeGroupRequestSequence(raw.sequence, groupId); - - if (operationType === null) { - log.warn( - 'unsupported group-request notification type: group=%d sequence=%s type=%d', - groupId, - String(raw.sequence ?? 0n), - notifyType, - ); - } requests.push({ groupId, @@ -593,16 +606,7 @@ export class ContactsApi { this.ctx.identity.findUinByUid(operatorUid) || 0, operatorName: raw.operatorUser?.name ?? '', - sequence, - state: raw.state ?? 0, - notifyType, - eventType: operationType ?? 0, - comment: raw.comment ?? '', - filtered, - operateTransInfo: - raw.operateTransInfo && raw.operateTransInfo.length > 0 - ? raw.operateTransInfo - : undefined, + ...groupRequestMetadata(raw, groupId, filtered), }); } @@ -626,18 +630,6 @@ export class ContactsApi { const targetUid = raw.target?.uid ?? ''; const invitorUid = raw.invitor?.uid ?? ''; const operatorUid = raw.operatorUser?.uid ?? ''; - const notifyType = raw.eventType ?? 0; - const operationType = groupRequestOperationType(notifyType); - const sequence = normalizeGroupRequestSequence(raw.sequence, groupId); - - if (operationType === null) { - log.warn( - 'unsupported group-request notification type: group=%d sequence=%s type=%d', - groupId, - String(raw.sequence ?? 0n), - notifyType, - ); - } requests.push({ groupId, @@ -660,16 +652,7 @@ export class ContactsApi { this.ctx.identity.findUinByUid(operatorUid) ?? 0, operatorName: raw.operatorUser?.name ?? '', - sequence, - state: raw.state ?? 0, - notifyType, - eventType: operationType ?? 0, - comment: raw.comment ?? '', - filtered, - operateTransInfo: - raw.operateTransInfo && raw.operateTransInfo.length > 0 - ? raw.operateTransInfo - : undefined, + ...groupRequestMetadata(raw, groupId, filtered), }); } @@ -698,15 +681,17 @@ export class ContactsApi { return ( [...main.value, ...filtered.value].find((request) => { - if (request.groupId !== groupId || request.state !== 1) { + if ( + request.groupId !== groupId || + request.state !== 1 || + groupRequestSubType(request) !== subType + ) { return false; } return subType === 'add' - ? request.eventType === 1 && request.targetUid === uid - : (isSelfGroupInvitation(request) || request.eventType === 22) && - request.invitorUid === uid && - request.targetUid === invitedUid; + ? request.targetUid === uid + : request.invitorUid === uid && request.targetUid === invitedUid; }) ?? null ); } diff --git a/packages/core/tests/actions/contacts.test.ts b/packages/core/tests/actions/contacts.test.ts index 207de463..d9074323 100644 --- a/packages/core/tests/actions/contacts.test.ts +++ b/packages/core/tests/actions/contacts.test.ts @@ -397,7 +397,7 @@ describe('apis/contacts / group requests', () => { requests: [ { sequence: 1_785_525_232_784_291n, - eventType: 7, + eventType: 1, state: 1, group: { groupUin: 1_095_186_374, groupName: 'group' }, target: { uin: 1_234_567_890, name: 'requester' }, @@ -439,7 +439,7 @@ describe('apis/contacts / group requests', () => { requests: [ { sequence: 42n, - eventType: 7, + eventType: 1, state: 1, group: { groupUin: 999, groupName: 'group' }, target: { uid: 'target_uid', name: 'requester' }, @@ -462,6 +462,8 @@ describe('apis/contacts / group requests', () => { targetUin: 1_234_567_890, invitorUid: 'inviter_uid', operatorUid: 'operator_uid', + notifyType: 7, + eventType: 1, filtered: true, }), ]); diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index c744b989..1f2a2457 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -3,7 +3,7 @@ import { mapWithConcurrency } from '@snowluma/common/concurrency'; import { positiveIntEnv } from '@snowluma/common/env'; import { readFile } from 'node:fs/promises'; import { FriendDressError } from '@snowluma/protocol/web/friend-dress'; -import { formatGroupRequestFlag } from '@snowluma/protocol/qq-info'; +import { formatGroupRequestFlag, groupRequestSubType } from '@snowluma/protocol/qq-info'; import type { GroupEssenceContent, GroupEssenceMessage, @@ -5486,7 +5486,8 @@ export const actions = [ // 与标准群系统消息共用过滤收件箱,只保留方言动作的返回形状。 // 这几个动作只是为实际使用中的 OneBot 方言客户端重命名并投影相同数据。 async function fetchFilteredGroupRequests(ctx: ApiActionContext) { - return ctx.bridge.apis.contacts.fetchGroupRequests(true); + const requests = await ctx.bridge.apis.contacts.fetchGroupRequests(true); + return requests.filter((request) => groupRequestSubType(request) !== undefined); } function parseDownloadHeaders(headers: unknown): Record { diff --git a/packages/onebot/src/modules/contact-actions.ts b/packages/onebot/src/modules/contact-actions.ts index 870b9ec8..fa2d63fe 100644 --- a/packages/onebot/src/modules/contact-actions.ts +++ b/packages/onebot/src/modules/contact-actions.ts @@ -7,6 +7,7 @@ import { } from '@snowluma/protocol/dataline/device-contacts'; import { formatGroupRequestFlag, + groupRequestSubType, isSelfGroupInvitation, type GroupMemberInfo, type GroupRequestInfo, @@ -589,18 +590,6 @@ async function resolveRequesterUins( return resolved; } -/** Join requests, self invitations, and invitations awaiting administrator approval. */ -function isJoinOrInviteNotify(notifyType: number | undefined): boolean { - return ( - notifyType === undefined || - notifyType === 1 || - notifyType === 2 || - notifyType === 5 || - notifyType === 7 || - notifyType === 22 - ); -} - function groupRequestActor(request: GroupRequestInfo): { uid: string; uin: number; @@ -638,11 +627,7 @@ export async function getGroupSystemMessages( const unique = new Map(); for (const request of [...main, ...filtered]) { - if (!isJoinOrInviteNotify(request.notifyType)) { - continue; - } - - if (request.eventType <= 0) { + if (!groupRequestSubType(request)) { continue; } diff --git a/packages/onebot/src/modules/request-actions.ts b/packages/onebot/src/modules/request-actions.ts index efc4a8d2..eef78613 100644 --- a/packages/onebot/src/modules/request-actions.ts +++ b/packages/onebot/src/modules/request-actions.ts @@ -1,6 +1,7 @@ import { createLogger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import { + groupRequestSubType, isSelfGroupInvitation, type GroupRequestHandle, type GroupRequestInfo, @@ -141,10 +142,7 @@ async function resolveLiveGroupRequest( const lookup = await fetchRequestInboxes(bridge, 'uin'); const live = lookup.requests.find( - (request) => - request.groupId === handle.groupId && - request.sequence === handle.sequence && - request.eventType > 0, + (request) => request.groupId === handle.groupId && request.sequence === handle.sequence, ); if (!live) { @@ -168,6 +166,13 @@ async function applyGroupRequest( knownLive?: GroupRequestInfo, ): Promise { const live = knownLive ?? (await resolveLiveGroupRequest(bridge, handle)); + + if (!groupRequestSubType(live)) { + throw new Error( + `unsupported group request type: group=${live.groupId} sequence=${live.sequence} type=${live.eventType}`, + ); + } + log.debug( 'handling group request: group=%d sequence=%d eventType=%d filtered=%s approve=%s', live.groupId, @@ -263,7 +268,11 @@ export async function handleGroupAddRequest( const lookup = await fetchRequestInboxes(bridge, 'uid'); const candidates = lookup.requests.filter((request) => { - if (request.groupId !== parsed.groupId || request.state !== 1 || request.eventType <= 0) { + if ( + request.groupId !== parsed.groupId || + request.state !== 1 || + groupRequestSubType(request) !== parsed.requestType + ) { return false; } diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index e18dc157..66436be9 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -1300,7 +1300,7 @@ function fakeFilteredRequest(overrides: Partial = {}): GroupRe operatorName: 'op', sequence: 42, state: 1, - eventType: 7, + eventType: 1, comment: 'pls', filtered: true, ...overrides, @@ -1310,7 +1310,9 @@ function fakeFilteredRequest(overrides: Partial = {}): GroupRe describe('extended-actions / get_group_ignored_notifies', () => { it('maps filtered fetchGroupRequests(true) into the napcat shape', async () => { const fetchGroupRequests = vi.fn(async (filtered: boolean) => - filtered ? [fakeFilteredRequest()] : [], + filtered + ? [fakeFilteredRequest(), fakeFilteredRequest({ sequence: 43, eventType: 7 })] + : [], ); const bridge = fakeBridge({ fetchGroupRequests: fetchGroupRequests as any }); const h = makeHandler(fakeCtx(bridge)); @@ -1329,7 +1331,7 @@ describe('extended-actions / get_group_ignored_notifies', () => { actor: 8888, invitor_uin: 7777, invitor_nick: 'inviter', - flag: 'slreq:1:42:999:7:1', + flag: 'slreq:1:42:999:1:1', }, ]); }); diff --git a/packages/onebot/tests/group-invitation-requests.test.ts b/packages/onebot/tests/group-invitation-requests.test.ts index b1a3d4fd..2ac750b3 100644 --- a/packages/onebot/tests/group-invitation-requests.test.ts +++ b/packages/onebot/tests/group-invitation-requests.test.ts @@ -1,12 +1,18 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { Bridge } from '@snowluma/core/bridge'; import { IdentityService } from '@snowluma/protocol/identity-service'; +import type { GroupInviteEvent } from '@snowluma/protocol/events'; import { MSG_PUSH_CMD } from '@snowluma/protocol/msg-push'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { PushMsg } from '@snowluma/proto-defs/message'; -import type { GroupInvite } from '@snowluma/proto-defs/notify'; -import type { OidbBase, OidbSvcTrpcTcp0x10C0Response } from '@snowluma/proto-defs/oidb'; +import type { GroupInvitation, GroupInvite, GroupJoin } from '@snowluma/proto-defs/notify'; +import type { + OidbBase, + OidbSvcTrpcTcp0x10C0Response, + OidbSvcTrpcTcp0x10C0ResponseRequest, +} from '@snowluma/proto-defs/oidb'; import type { OidbGroupRequestAction } from '@snowluma/proto-defs/oidb-actions/base'; +import { convertEvent } from '../src/event-converter'; import { getGroupSystemMessages } from '../src/modules/contact-actions'; import { handleGroupAddRequest } from '../src/modules/request-actions'; @@ -16,7 +22,7 @@ afterEach(async () => { await Promise.all(bridges.splice(0).map((bridge) => bridge.dispose())); }); -function setup(filtered = false, overrides: { targetUid?: string; state?: number } = {}) { +function setup(filtered = false, overrides: OidbSvcTrpcTcp0x10C0ResponseRequest = {}) { const bridge = new Bridge(IdentityService.memory('10001')); bridges.push(bridge); bridge.identity.setSelfProfile({ @@ -36,15 +42,15 @@ function setup(filtered = false, overrides: { targetUid?: string; state?: number }); bridge.identity.rememberRequestIdentity({ groupId: 999, uid: 'u_self', uin: 10001 }); bridge.identity.rememberRequestIdentity({ groupId: 999, uid: 'u_inviter', uin: 456 }); - const operateTransInfo = Uint8Array.from([8, 42, 16, 231, 7, 24, 2]); const record = { sequence: 42n, eventType: 2, - state: overrides.state ?? 1, + state: 1, group: { groupUin: 999, groupName: 'group' }, - target: { uid: overrides.targetUid ?? 'u_self', name: 'bot' }, + target: { uid: 'u_self', name: 'bot' }, invitor: { uid: 'u_inviter', name: 'inviter' }, - operateTransInfo, + operateTransInfo: Uint8Array.from([8, 42, 16, 231, 7, 24, 2]), + ...overrides, }; const send = vi.spyOn(bridge, 'sendRawPacket').mockImplementation(async (cmd) => { let responseData = Buffer.alloc(0); @@ -61,9 +67,12 @@ function setup(filtered = false, overrides: { targetUid?: string; state?: number return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; }); - const flags: string[] = []; - bridge.events.on('group_invite', (event) => flags.push(event.flag)); - const notice = () => + const events: GroupInviteEvent[] = []; + bridge.events.on('group_invite', (event) => events.push(event)); + const notice = ( + msgType = 87, + msgContent = protobuf_encode({ groupUin: 999, invitorUid: 'u_inviter' }), + ) => bridge.onPacket({ pid: 1, uin: '10001', @@ -74,36 +83,108 @@ function setup(filtered = false, overrides: { targetUid?: string; state?: number body: Buffer.from( protobuf_encode({ message: { - contentHead: { msgType: 87, timestamp: 1 }, - body: { - msgContent: protobuf_encode({ - groupUin: 999, - invitorUid: 'u_inviter', - }), - }, + contentHead: { msgType, timestamp: 1 }, + body: { msgContent }, }, status: 0, }), ), }); - return { bridge, send, flags, notice, operateTransInfo }; + return { bridge, send, events, notice, operateTransInfo: record.operateTransInfo }; } +describe('group join requests', () => { + it.each([false, true])( + 'reports and handles a join from the inbox (filtered=%s)', + async (filtered) => { + const { bridge, send, events, notice, operateTransInfo } = setup(filtered, { + eventType: 1, + target: { uid: 'u_applicant', name: 'applicant' }, + invitor: undefined, + comment: 'please let me in', + operateTransInfo: Uint8Array.from([8, 42, 16, 231, 7, 24, 1]), + }); + bridge.identity.rememberRequestIdentity({ groupId: 999, uid: 'u_applicant', uin: 123 }); + await notice( + 84, + protobuf_encode({ groupUin: 999, targetUid: 'u_applicant' }), + ); + + expect(events).toHaveLength(1); + const flag = `slreq:1:42:999:1:${filtered ? 1 : 0}`; + const event = await convertEvent( + { + selfId: 10001, + imageUrlResolver: null, + mediaUrlResolver: null, + messageIdResolver: null, + mediaSegmentSink: null, + }, + events[0]!, + ); + expect(event).toMatchObject({ + post_type: 'request', + request_type: 'group', + sub_type: 'add', + group_id: 999, + user_id: 123, + comment: 'please let me in', + flag, + }); + expect(await getGroupSystemMessages(bridge, { onlyPending: true })).toEqual([ + expect.objectContaining({ requester_uin: 123, requester_nick: 'applicant', flag }), + ]); + + await handleGroupAddRequest(bridge, events[0]!.flag, true, ''); + const approvals = send.mock.calls.filter(([cmd]) => + cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'), + ); + expect(approvals).toHaveLength(1); + const [cmd, bytes] = approvals[0]!; + expect(cmd).toBe(`OidbSvcTrpcTcp.0x10c8_${filtered ? 2 : 1}`); + expect(protobuf_decode>(bytes).body).toMatchObject({ + accept: 1, + body: { sequence: 42n, groupUin: 999, eventType: 1, operateTransInfo }, + }); + }, + ); + + it.each([7, 10, 5])('does not report another wire type (%i) as a join', async (eventType) => { + const { bridge, events, notice } = setup(false, { eventType }); + await notice(84, protobuf_encode({ groupUin: 999, targetUid: 'u_self' })); + expect(events).toEqual([]); + expect(await getGroupSystemMessages(bridge)).toEqual([]); + }); + + it.each(['42', 'slreq:1:42:999:1:0'])( + 'refuses an unknown inbox type for flag %s', + async (flag) => { + const { bridge, send } = setup(false, { eventType: 5 }); + await expect(handleGroupAddRequest(bridge, flag, true, '')).rejects.toThrow( + 'unsupported group request type', + ); + expect(send.mock.calls.some(([cmd]) => cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'))).toBe( + false, + ); + }, + ); +}); + describe('non-friend group invitations', () => { it.each([ { approve: true, filtered: false }, { approve: false, filtered: true }, ])('handles an emitted flag through the real codecs: %j', async ({ approve, filtered }) => { - const { bridge, send, flags, notice, operateTransInfo } = setup(filtered); + const { bridge, send, events, notice, operateTransInfo } = setup(filtered); await notice(); - expect(flags).toEqual(['invite:999:u_inviter']); - await handleGroupAddRequest(bridge, flags[0]!, approve, ''); + expect(events).toEqual([expect.objectContaining({ flag: 'invite:999:u_inviter' })]); + await handleGroupAddRequest(bridge, events[0]!.flag, approve, ''); const approval = send.mock.calls.find(([cmd]) => cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'))!; expect(approval[0]).toBe(`OidbSvcTrpcTcp.0x10c8_${filtered ? 2 : 1}`); const wire = protobuf_decode>(approval[1]); expect(wire.body).toMatchObject({ accept: approve ? 1 : 2, - body: { sequence: 42n, groupUin: 999, eventType: 10, message: ' ', operateTransInfo }, + body: { sequence: 42n, groupUin: 999, eventType: 2, message: ' ', operateTransInfo }, }); expect( await bridge.apis.contacts.resolveGroupJoinRequest( @@ -112,7 +193,7 @@ describe('non-friend group invitations', () => { 'invite', 'u_self', ), - ).toMatchObject({ notifyType: 2, eventType: 10 }); + ).toMatchObject({ notifyType: 1, eventType: 2 }); }); it('lists the inviter and returns a flag that can approve the same invitation', async () => { @@ -124,21 +205,38 @@ describe('non-friend group invitations', () => { requester_uin: 456, requester_nick: 'inviter', checked: false, - flag: 'slreq:1:42:999:10:0', + flag: 'slreq:1:42:999:2:0', }), ]); await handleGroupAddRequest(bridge, String(rows[0]!.flag), true, ''); const approval = send.mock.calls.find(([cmd]) => cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'))!; const wire = protobuf_decode>(approval[1]); - expect(wire.body?.body).toMatchObject({ eventType: 10, operateTransInfo }); + expect(wire.body?.body).toMatchObject({ eventType: 2, operateTransInfo }); }); - it.each([{ targetUid: 'u_other' }, { state: 2 }])( - 'rejects a mismatched or processed invitation: %j', + it('corrects the type in an older invitation flag from the current inbox', async () => { + const { bridge, send, operateTransInfo } = setup(true); + await handleGroupAddRequest(bridge, 'slreq:1:42:999:10:0', true, ''); + const approvals = send.mock.calls.filter(([cmd]) => + cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'), + ); + expect(approvals).toHaveLength(1); + const [cmd, bytes] = approvals[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x10c8_2'); + expect(protobuf_decode>(bytes).body?.body).toMatchObject({ + sequence: 42n, + groupUin: 999, + eventType: 2, + operateTransInfo, + }); + }); + + it.each([{ target: { uid: 'u_other' } }, { state: 2 }, { eventType: 10 }])( + 'requires a pending invitation to this account: %j', async (overrides) => { - const { bridge, send, flags, notice } = setup(false, overrides); + const { bridge, send, events, notice } = setup(false, overrides); await notice(); - await expect(handleGroupAddRequest(bridge, flags[0]!, true, '')).rejects.toThrow( + await expect(handleGroupAddRequest(bridge, events[0]!.flag, true, '')).rejects.toThrow( 'matching group request not found', ); expect(send.mock.calls.some(([cmd]) => cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'))).toBe( @@ -147,3 +245,56 @@ describe('non-friend group invitations', () => { }, ); }); + +describe('invitations awaiting administrator approval', () => { + it('keeps the applicant, inviter and approval type through the real codecs', async () => { + const { bridge, send, events, notice, operateTransInfo } = setup(true, { + eventType: 22, + target: { uid: 'u_applicant', name: 'applicant' }, + comment: 'invited to join', + operateTransInfo: Uint8Array.from([8, 42, 16, 231, 7, 24, 22]), + }); + bridge.identity.rememberRequestIdentity({ groupId: 999, uid: 'u_applicant', uin: 123 }); + await notice( + 525, + protobuf_encode({ + cmd: 87, + info: { + inner: { groupUin: 999, invitorUid: 'u_inviter', targetUid: 'u_applicant' }, + }, + }), + ); + expect(events).toEqual([ + expect.objectContaining({ + subType: 'invite', + fromUin: 456, + invitedUin: 123, + flag: 'slreq:1:42:999:22:1', + }), + ]); + expect(await getGroupSystemMessages(bridge)).toEqual([ + expect.objectContaining({ + requester_uin: 123, + invitor_uin: 456, + flag: events[0]!.flag, + }), + ]); + await handleGroupAddRequest(bridge, events[0]!.flag, false, 'declined'); + const approvals = send.mock.calls.filter(([cmd]) => + cmd.startsWith('OidbSvcTrpcTcp.0x10c8_'), + ); + expect(approvals).toHaveLength(1); + const [cmd, bytes] = approvals[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x10c8_2'); + expect(protobuf_decode>(bytes).body).toMatchObject({ + accept: 2, + body: { + sequence: 42n, + groupUin: 999, + eventType: 22, + message: 'declined', + operateTransInfo, + }, + }); + }); +}); diff --git a/packages/onebot/tests/request-actions.test.ts b/packages/onebot/tests/request-actions.test.ts index de1d3b29..27f01f6f 100644 --- a/packages/onebot/tests/request-actions.test.ts +++ b/packages/onebot/tests/request-actions.test.ts @@ -58,7 +58,7 @@ function fakeRequest(overrides: Partial = {}): GroupRequestInf operatorName: 'op', sequence: 42, state: 1, - eventType: 7, + eventType: 2, comment: 'pls', filtered: false, ...overrides, @@ -118,7 +118,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { fakeRequest({ groupId: 999, sequence: 261237407, - eventType: 7, + eventType: 1, filtered: false, }), ], @@ -131,7 +131,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { expect(setAddRequest).toHaveBeenCalledWith( 999, 261237407, - 7, + 1, false, 'no', false, @@ -172,11 +172,12 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { it('matches add requests by groupId and targetUid', async () => { const setAddRequest = vi.fn(async () => {}); const fetchGroupRequestsByUid = vi.fn(async () => [ + fakeRequest({ sequence: 41, targetUid: 'u_t', eventType: 2 }), fakeRequest({ groupId: 999, targetUid: 'u_t', sequence: 42, - eventType: 7, + eventType: 1, filtered: false, }), ]); @@ -188,7 +189,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { await handleGroupAddRequest(bridge, 'add:999:u_t', true, 'ok'); expect(setAddRequest).toHaveBeenCalledOnce(); - expect(setAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false, undefined); + expect(setAddRequest).toHaveBeenCalledWith(999, 42, 1, true, 'ok', false, undefined); expect(fetchGroupRequestsByUid).toHaveBeenCalledWith(false, 100); expect(fetchGroupRequestsByUid).toHaveBeenCalledWith(true, 100); }); @@ -197,11 +198,12 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { const setAddRequest = vi.fn(async () => {}); const bridge = fakeBridge({ fetchGroupRequestsByUid: vi.fn(async () => [ + fakeRequest({ sequence: 96, invitorUid: 'u_i', eventType: 1 }), fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, - eventType: 8, + eventType: 22, filtered: false, }), ]), @@ -212,7 +214,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { await handleGroupAddRequest(bridge, 'invite:999:u_i', false, 'no'); expect(setAddRequest).toHaveBeenCalledOnce(); - expect(setAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false, undefined); + expect(setAddRequest).toHaveBeenCalledWith(999, 97, 22, false, 'no', false, undefined); }); it('finds a request that only lives in the filtered inbox (#197)', async () => { @@ -284,7 +286,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { expect(setAddRequest).toHaveBeenCalledExactlyOnceWith( 999, 124, - 7, + 2, true, '', false, diff --git a/packages/protocol/src/oidb-services/contacts/fetch-group-requests.ts b/packages/protocol/src/oidb-services/contacts/fetch-group-requests.ts index 64fd5abc..670f6fdb 100644 --- a/packages/protocol/src/oidb-services/contacts/fetch-group-requests.ts +++ b/packages/protocol/src/oidb-services/contacts/fetch-group-requests.ts @@ -19,45 +19,31 @@ import type { import type { OidbGroupRequestList } from '@snowluma/proto-defs/oidb-actions/base'; import { invokeOidb, type OidbSender } from '../../oidb-service'; -// Current QQ's EncodeOperateSysNotify maps the high-level list notification -// type to the discriminator sent by 0x10C8. This table was read directly from -// the current Linux client; keeping the distinction prevents list type 7 -// (join request) from being incorrectly sent back as operation type 7. -const GROUP_REQUEST_OPERATION_TYPE = new Map([ +// Field 2 in a list entry and in its approval uses the same wire value. +// Only the client-facing notification type needs translation. +const GROUP_REQUEST_NOTIFY_TYPES = new Map([ [0, 0], - [1, 2], - [2, 10], - [3, 11], - [4, 12], - [5, 22], - [6, 35], - [7, 1], - [8, 3], - [9, 6], - [10, 7], - [11, 13], - [12, 15], - [13, 16], - [14, 17], - [15, 19], - [16, 8], - [17, 100], + [1, 7], + [2, 1], + [3, 8], + [6, 9], + [7, 10], + [8, 16], + [10, 2], + [11, 3], + [12, 4], + [13, 11], + [15, 12], + [16, 13], + [17, 14], + [19, 15], + [22, 5], + [35, 6], + [100, 17], ]); -const GROUP_REQUEST_OPERATION_OUTPUT = new Set(GROUP_REQUEST_OPERATION_TYPE.values()); -export function groupRequestOperationType(notifyType: number): number | null { - const mapped = GROUP_REQUEST_OPERATION_TYPE.get(notifyType); - - if (mapped !== undefined) { - return mapped; - } - - // Some list replies already carry the mapped discriminator (e.g. 22). - if (GROUP_REQUEST_OPERATION_OUTPUT.has(notifyType)) { - return notifyType; - } - - return null; +export function groupRequestNotifyType(eventType: number): number | undefined { + return GROUP_REQUEST_NOTIFY_TYPES.get(eventType); } export interface DecodedGroupRequestUser { diff --git a/packages/protocol/src/qq-info.ts b/packages/protocol/src/qq-info.ts index 0689a997..0063c052 100644 --- a/packages/protocol/src/qq-info.ts +++ b/packages/protocol/src/qq-info.ts @@ -152,19 +152,33 @@ export interface GroupRequestInfo { operatorName: string; sequence: number; state: number; - /** High-level notification type returned by the request list. */ + /** Client notification type corresponding to the wire discriminator, when known. */ notifyType?: number; - /** 0x10C8 operation discriminator derived from notifyType. */ + /** Wire discriminator shared by the request list and approval. */ eventType: number; comment: string; filtered: boolean; operateTransInfo?: Uint8Array; } -/** Invitations handled by the invited account, rather than a group administrator. - * Notification types 1 and 2 use different approval discriminators. */ +/** A member invited the account to join. Wire type 10 reports a refused invitation. */ export function isSelfGroupInvitation(request: Pick): boolean { - return request.eventType === 2 || request.eventType === 10; + return request.eventType === 2; +} + +/** Only joins and invitations correspond to a OneBot group request. */ +export function groupRequestSubType( + request: Pick, +): 'add' | 'invite' | undefined { + if (request.eventType === 1) { + return 'add'; + } + + if (isSelfGroupInvitation(request) || request.eventType === 22) { + return 'invite'; + } + + return undefined; } /** Approval tuple required by OIDB 0x10C8. The OneBot flag is opaque to diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-group-requests.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-group-requests.test.ts index d918a184..185e2d5a 100644 --- a/packages/protocol/tests/oidb-services/contacts/fetch-group-requests.test.ts +++ b/packages/protocol/tests/oidb-services/contacts/fetch-group-requests.test.ts @@ -8,7 +8,7 @@ import type { SendPacketResult } from '@snowluma/common/packet-sender'; import { FetchGroupRequests, FetchGroupRequestsByUid, - groupRequestOperationType, + groupRequestNotifyType, } from '../../../src/oidb-services/contacts/fetch-group-requests'; interface ObservedGroupRequestUserByUin { @@ -49,14 +49,15 @@ function makeSender() { } describe('FetchGroupRequests namespace', () => { - it('maps native list notification types to 0x10C8 operation types', () => { - expect(groupRequestOperationType(1)).toBe(2); - expect(groupRequestOperationType(2)).toBe(10); - expect(groupRequestOperationType(7)).toBe(1); - expect(groupRequestOperationType(17)).toBe(100); - expect(groupRequestOperationType(5)).toBe(22); - expect(groupRequestOperationType(22)).toBe(22); - expect(groupRequestOperationType(99)).toBeNull(); + it('interprets list discriminators in the wire-to-notification direction', () => { + expect(groupRequestNotifyType(1)).toBe(7); + expect(groupRequestNotifyType(2)).toBe(1); + expect(groupRequestNotifyType(7)).toBe(10); + expect(groupRequestNotifyType(10)).toBe(2); + expect(groupRequestNotifyType(22)).toBe(5); + expect(groupRequestNotifyType(100)).toBe(17); + expect(groupRequestNotifyType(5)).toBeUndefined(); + expect(groupRequestNotifyType(99)).toBeUndefined(); }); it('declares 0x10C0', () => { @@ -131,7 +132,7 @@ describe('FetchGroupRequests namespace', () => { requests: [ { sequence: 1_785_525_232_784_291n, - eventType: 7, + eventType: 1, state: 1, group: { groupUin: 1_095_186_374, groupName: 'group' }, target: { uin: 1_234_567_890, name: 'requester' }, @@ -156,6 +157,7 @@ describe('FetchGroupRequests namespace', () => { const response = await FetchGroupRequests.invoke(sender, { filtered: false }); expect(response.requests?.[0]).toMatchObject({ + eventType: 1, target: { uin: 1_234_567_890, uid: '', name: 'requester' }, invitor: { uin: 2_345_678_901, uid: '', name: 'inviter' }, operatorUser: { uin: 3_456_789_012, uid: '', name: 'operator' }, @@ -170,7 +172,7 @@ describe('FetchGroupRequests namespace', () => { requests: [ { sequence: 99n, - eventType: 5, + eventType: 22, state: 1, group: { groupUin: 1001, groupName: 'group' }, target: { uid: 'u_target', name: 'invitee' }, @@ -194,7 +196,7 @@ describe('FetchGroupRequests namespace', () => { const response = await FetchGroupRequests.invoke(sender, { filtered: false }); expect(response.requests?.[0]).toMatchObject({ - eventType: 5, + eventType: 22, target: { uid: 'u_target', uin: 0, name: 'invitee' }, invitor: { uid: 'u_inviter', uin: 0, name: 'inviter' }, comment: 'join us',