fix(protocol): restore filtered friend request approvals

Correct approval handling for filtered friend requests and preserve clear failures when an account cannot be resolved or the request is rejected.

Add regression coverage for separate account identities, approval errors, and existing list and rejection behavior.

Fixes #460
This commit is contained in:
DrSmoothl committed 2026-09-26 16:59:52 +08:00
1 parent 7a07119ee9
commit 797a4d754c
8 files changed
+164 -80

No files matched your search

+7 -8
View File
@@ -64,11 +64,8 @@ export class FriendApi {
if (userId <= 0 && uid) { if (userId <= 0 && uid) {
userId = this.ctx.identity.findUinByUid(uid) ?? 0; userId = this.ctx.identity.findUinByUid(uid) ?? 0;
} }
// Current Linux replies often omit the account id even though the // Applicants need not be friends or share a group. Use Identity's
// official decoder still reads it as a string. The approval packet // profile lookup when the list only supplies an account number.
// cannot accept a raw number, so fill from the same uin→uid path
// used by ordinary friend requests. Cache-only lookup is not
// enough: filtered applicants are not friends or group members.
if (!uid && userId > 0) { if (!uid && userId > 0) {
try { try {
uid = await this.ctx.resolveUserUid(userId); uid = await this.ctx.resolveUserUid(userId);
@@ -86,9 +83,11 @@ export class FriendApi {
/** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */ /** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */
async approveDoubtRequest(uidOrFlag: string): Promise<void> { async approveDoubtRequest(uidOrFlag: string): Promise<void> {
return ApproveDoubtBuddyReq.invoke(this.ctx, { log.trace('doubt-request approval: resolving applicant');
uid: await this.resolveDoubtFlag(uidOrFlag), const uid = await this.resolveDoubtFlag(uidOrFlag);
}); log.trace('doubt-request approval: submitting request');
await ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
log.trace('doubt-request approval: completed');
} }
/** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */ /** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */
+34 -3
View File
@@ -19,6 +19,7 @@ import type {
// against the bridge mock's sendRawPacket directly — no need for // against the bridge mock's sendRawPacket directly — no need for
// module-level bridge-oidb mocks anymore. // module-level bridge-oidb mocks anymore.
import { DATALINE_UIN_PAD } from '@snowluma/protocol/dataline/device-contacts'; import { DATALINE_UIN_PAD } from '@snowluma/protocol/dataline/device-contacts';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { FriendApi } from '../../src/bridge/apis/friend'; import { FriendApi } from '../../src/bridge/apis/friend';
import { mockBridge } from './_helpers'; import { mockBridge } from './_helpers';
@@ -183,9 +184,9 @@ describe('apis/friend', () => {
await new FriendApi(bridge as any).approveDoubtRequest('12345'); await new FriendApi(bridge as any).approveDoubtRequest('12345');
expect(bridge.resolveUserUid).toHaveBeenCalledWith(12345); expect(bridge.resolveUserUid).toHaveBeenCalledWith(12345);
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!; const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xd69_0'); expect(cmd).toBe('OidbSvcTrpcTcp.0xd72_0');
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes); const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
expect(env.body).toMatchObject({ uid: 'resolved-uid', targetUid: 'resolved-uid' }); expect(env.body).toMatchObject({ selfUid: 'self-uid', targetUid: 'resolved-uid', field3: 0, field4: '' });
}); });
it('approveDoubtRequest forwards a uid flag without resolving', async () => { it('approveDoubtRequest forwards a uid flag without resolving', async () => {
@@ -194,7 +195,37 @@ describe('apis/friend', () => {
expect(bridge.resolveUserUid).not.toHaveBeenCalled(); expect(bridge.resolveUserUid).not.toHaveBeenCalled();
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!; const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes); const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
expect(env.body).toMatchObject({ uid: 'u_abc', targetUid: 'u_abc' }); expect(env.body).toMatchObject({ selfUid: 'self-uid', targetUid: 'u_abc' });
});
it('approves a filtered stranger through Identity without requiring a shared roster', async () => {
const identity = new IdentityService('10001', null);
const bridge = mockBridge();
const fetchProfile = vi.fn(async (uin: number) => ({
uin, uid: uin === 10001 ? 'u_self' : 'u_stranger',
}));
identity.setFetcher({ fetchProfile: fetchProfile as any });
bridge.identity = identity as any;
bridge.resolveUserUid = vi.fn((uin: number) => identity.resolveUid(uin));
try {
await new FriendApi(bridge as any).approveDoubtRequest('12345');
expect(fetchProfile.mock.calls.map(([uin]) => uin)).toEqual([12345, 10001]);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
expect(env.body).toMatchObject({ selfUid: 'u_self', targetUid: 'u_stranger' });
} finally {
identity.close();
}
});
it('does not send an approval when the applicant cannot be resolved', async () => {
const bridge = mockBridge({
resolveUserUid: vi.fn(async () => { throw new Error('applicant lookup failed'); }),
});
await expect(new FriendApi(bridge as any).approveDoubtRequest('12345'))
.rejects.toThrow('applicant lookup failed');
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
}); });
it('rejectDoubtRequest resolves a digit-only flag before sending', async () => { it('rejectDoubtRequest resolves a digit-only flag before sending', async () => {
+2 -7
View File
@@ -1902,11 +1902,8 @@ export const actions = [
return okResponse(list); return okResponse(list);
}, },
}), }),
// set_doubt_friends_add_request — handle a 可疑好友申请 (0xd69_0). `flag` is // Accept the list UID or resolve the applicant's account number.
// the uid from the get list, or the applicant's account number (resolved // Approval and rejection use their respective friend API operations.
// before the packet is built). approve → approvalDoubtBuddyReq; approve:false
// → delDoubtBuddyReq (reject/decline). NapCat only ever approves; we add the
// reject path since we RE'd delDoubtBuddyReq too.
defineAction({ defineAction({
name: 'set_doubt_friends_add_request', name: 'set_doubt_friends_add_request',
summary: '处理可疑好友申请', summary: '处理可疑好友申请',
@@ -1915,8 +1912,6 @@ export const actions = [
approve: f.bool().default(true), approve: f.bool().default(true),
}, },
run: async (p, ctx) => { run: async (p, ctx) => {
// approve → approvalDoubtBuddyReq (0xd69_0); reject → delDoubtBuddyReq
// (also 0xd69_0, distinct body) — both RE'd from the binary.
if (p.approve) { if (p.approve) {
await ctx.bridge.apis.friend.approveDoubtRequest(p.flag); await ctx.bridge.apis.friend.approveDoubtRequest(p.flag);
} else { } else {
@@ -2162,6 +2162,16 @@ describe('extended-actions / TierB ③ share + doubt + robot-option', () => {
expect(approveDoubtRequest).not.toHaveBeenCalled(); expect(approveDoubtRequest).not.toHaveBeenCalled();
}); });
it('set_doubt_friends_add_request reports an approval error without rejecting the applicant', async () => {
const approveDoubtRequest = vi.fn(async () => { throw new Error('approval denied'); });
const rejectDoubtRequest = vi.fn(async () => {});
const bridge = fakeBridge({ apis: { friend: { approveDoubtRequest, rejectDoubtRequest } } });
const res = await makeHandler(fakeCtx(bridge)).handle('set_doubt_friends_add_request', { flag: 'u_abc' });
expect(res).toMatchObject({ status: 'failed', wording: 'approval denied' });
expect(approveDoubtRequest).toHaveBeenCalledOnce();
expect(rejectDoubtRequest).not.toHaveBeenCalled();
});
it('set_group_robot_add_option forwards group + switch/examine', async () => { it('set_group_robot_add_option forwards group + switch/examine', async () => {
const setRobotAddOption = vi.fn(async () => {}); const setRobotAddOption = vi.fn(async () => {});
const bridge = fakeBridge({ apis: { groupAdmin: { setRobotAddOption } } }); const bridge = fakeBridge({ apis: { groupAdmin: { setRobotAddOption } } });
@@ -1,24 +1,7 @@
// Doubt-buddy (可能认识的人 / 被过滤的好友申请) protobufs, RE'd from QQNT // Filtered friend requests: listing, approval, and rejection have distinct
// wrapper.linux.node. Both get + approval ride OidbSvcTrpcTcp.0xd69_0 // request contracts. List responses can carry an account number or a UID.
// (worker ctors both pass cmd=0xd69, sub=0; codec `doubt_codec.cc`).
//
// GET request (EncodeRequest sub_3F3DC20): {1:const 1, 2:{1:num, 2:uk}}.
// reqId is NOT serialized (kernel uses it only for JS callback correlation).
// GET response: status (==1 ok) + body{1:repeated item, 2:reason}.
// Linux 3.2.32 sends the account number at tag 1 (varint), request time at
// tag 8, and source group at tag 9; it carries no string uid. Some builds
// send a string uid at tag 1 instead, so the service decodes both wire
// types and keeps whichever is present.
// The string tags' semantic NAMES (nick/source/msg) come
// from the GENERIC buddy serializer registry, not a doubt-specific table,
// so they are MEDIUM confidence — but this is a READ, so a mislabel is
// cosmetic, never a malformed-packet/ban risk. We model the ones NapCat
// surfaces and leave the rest unmapped.
// APPROVAL request (EncodeRequest sub_3F3EC90): {1:uid, 2:uid, [3:u32],
// [4:str]}. tags 3/4 are emitted only when present; NapCat passes empty
// str1/str2, so the approve flow is just {1:uid, 2:uid}.
import type { pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton'; import type { pb, pb_optional, pb_repeated, uint_32, uint_64 } from '@snowluma/proton';
export interface OidbDoubtGetReqInner { export interface OidbDoubtGetReqInner {
num?: pb<1, uint_32>; num?: pb<1, uint_32>;
@@ -50,18 +33,14 @@ export interface OidbDoubtGetResp {
body?: pb<2, OidbDoubtGetRespBody>; body?: pb<2, OidbDoubtGetRespBody>;
} }
// tag1 and tag2 come from two DIFFERENT kernel attrs (21503 vs 21001), but
// both are uid-class and NapCat sends the same friendUid into both — so the
// service sets them to the same value. They are NOT equal by schema design.
export interface OidbDoubtApprovalReq { export interface OidbDoubtApprovalReq {
uid?: pb<1, string>; selfUid?: pb<1, string>;
targetUid?: pb<2, string>; targetUid?: pb<2, string>;
field3?: pb_optional<3, uint_32>;
field4?: pb_optional<4, string>;
} }
// delDoubtBuddyReq (reject/decline) — same cmd 0xd69_0 as get/approval, but a // Reject an existing filtered friend request.
// distinct body. RE'd from doubt_buddy_del_worker.cc EncodeRequest sub_3F3E860:
// {1: varint const 3 (op discriminator; get uses 1), 3: {1: string uid}}.
// The uid comes from kernel attr 21001.
export interface OidbDoubtDelReqInner { export interface OidbDoubtDelReqInner {
uid?: pb<1, string>; uid?: pb<1, string>;
} }
@@ -1,28 +1,31 @@
// 0xd69_0 — approvalDoubtBuddyReq: approve a doubtful friend-add request // Approve an existing filtered friend request.
// (可能认识的人). RE'd from QQNT doubt_codec.cc EncodeRequest sub_3F3EC90:
// {1:uid, 2:uid, [3:u32], [4:str]} — tags 3/4 emitted only when present, and
// NapCat passes empty str1/str2, so the approve flow is just {1:uid, 2:uid}.
// Same OIDB cmd as the getter; the server discriminates by body shape.
// uin-form OIDB (envelope reserved=1). The reject/decline path is a separate
// cmd (delDoubtBuddyReq) — see sibling reject-doubt-buddy-req.ts.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbDoubtApprovalReq } from '@snowluma/proto-defs/oidb-actions/doubt-buddy'; import type { OidbDoubtApprovalReq } from '@snowluma/proto-defs/oidb-actions/doubt-buddy';
import type { BridgeContext } from '../../bridge-context';
import { invokeOidb, type OidbSender } from '../../oidb-service'; import { invokeOidb, type OidbSender } from '../../oidb-service';
import { resolveSelfUid } from '../../self-uid';
export namespace ApproveDoubtBuddyReq { export namespace ApproveDoubtBuddyReq {
export const command = 0xD69; export const command = 0xD72;
export const subCommand = 0; export const subCommand = 0;
export const uinForm = true; export const uinForm = false;
export interface Params { uid: string } export interface Params { uid: string }
export type Deps = OidbSender; export type Deps = OidbSender & Pick<BridgeContext, 'identity' | 'resolveUserUid'>;
export const serialize = (_ctx: Deps, p: Params): OidbDoubtApprovalReq => ({ export const serialize = async (ctx: Deps, p: Params): Promise<OidbDoubtApprovalReq> => {
uid: p.uid, if (!p.uid.trim()) throw new Error('cannot approve doubt request: applicant uid is unavailable');
targetUid: p.uid, const selfUid = await resolveSelfUid(ctx);
}); if (!selfUid.trim()) throw new Error('cannot approve doubt request: self uid is unavailable');
return {
selfUid,
targetUid: p.uid,
field3: 0,
field4: '',
};
};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
@@ -2,7 +2,7 @@
// request. RE'd from QQNT doubt_buddy_del_worker.cc (worker ctor sub_3F3F320 // request. RE'd from QQNT doubt_buddy_del_worker.cc (worker ctor sub_3F3F320
// → cmd 0xd69 sub 0; EncodeRequest sub_3F3E860 writes {1: const 3, 3:{1:uid}}). // → cmd 0xd69 sub 0; EncodeRequest sub_3F3E860 writes {1: const 3, 3:{1:uid}}).
// The top-level tag-1 constant 3 is the op discriminator (getDoubtBuddyReq // The top-level tag-1 constant 3 is the op discriminator (getDoubtBuddyReq
// uses 1). Same OIDB cmd as get/approval; the server routes by body shape. // uses 1). Rejection shares the listing command, not the approval command.
// uin-form OIDB (envelope reserved=1). // uin-form OIDB (envelope reserved=1).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
@@ -3,35 +3,102 @@ import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { SendPacketResult } from '@snowluma/common/packet-sender'; import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { ApproveDoubtBuddyReq } from '../../../src/oidb-services/friend/approve-doubt-buddy-req'; import { ApproveDoubtBuddyReq } from '../../../src/oidb-services/friend/approve-doubt-buddy-req';
import { env, s } from '../_pb-oracle'; import { env, s, v } from '../_pb-oracle';
function makeSender() { function makeSender(selfUid = 'u_self', selfUin = '10001') {
const respEnv: OidbBase<OidbEmpty> = { command: 0xD69, subCommand: 0, body: {} }; const respEnv: OidbBase<OidbEmpty> = { command: 0xD72, subCommand: 0, body: {} };
const r: SendPacketResult = { const r: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '', success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<OidbEmpty>>(respEnv)), responseData: Buffer.from(protobuf_encode<OidbBase<OidbEmpty>>(respEnv)),
}; };
return { sendRawPacket: vi.fn(async () => r) }; return {
sendRawPacket: vi.fn(async (_cmd: string, _bytes: Uint8Array) => r),
identity: { selfUid, uin: selfUin } as ApproveDoubtBuddyReq.Deps['identity'],
resolveUserUid: vi.fn(async () => 'u_lookup_self'),
};
} }
describe('ApproveDoubtBuddyReq namespace', () => { describe('ApproveDoubtBuddyReq namespace', () => {
it('declares command 0xD69 sub 0, uin form', () => { it('keeps the approving account separate from the applicant', async () => {
expect(ApproveDoubtBuddyReq.command).toBe(0xD69);
expect(ApproveDoubtBuddyReq.subCommand).toBe(0);
expect(ApproveDoubtBuddyReq.uinForm).toBe(true);
});
it('serializes the uid into both tag 1 and tag 2 (str1/str2 omitted, matching NapCat approve flow)', () => {
expect(ApproveDoubtBuddyReq.serialize({} as any, { uid: 'u_x' })).toEqual({ uid: 'u_x', targetUid: 'u_x' });
});
it('byte-oracle: routes to 0xd69_0 and locks req tags {1:uid, 2:uid}', async () => {
const sender = makeSender(); const sender = makeSender();
await ApproveDoubtBuddyReq.invoke(sender, { uid: 'u_abc' }); expect(await ApproveDoubtBuddyReq.serialize(sender, { uid: 'u_applicant' })).toEqual({
selfUid: 'u_self', targetUid: 'u_applicant', field3: 0, field4: '',
});
expect(sender.resolveUserUid).not.toHaveBeenCalled();
});
it('matches the approval request bytes including explicit default options', async () => {
const sender = makeSender();
await ApproveDoubtBuddyReq.invoke(sender, { uid: 'u_applicant' });
expect(sender.sendRawPacket).toHaveBeenCalledOnce();
const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!; const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xd69_0'); expect(cmd).toBe('OidbSvcTrpcTcp.0xd72_0');
const body = [...s(1, 'u_abc'), ...s(2, 'u_abc')]; const body = [...s(1, 'u_self'), ...s(2, 'u_applicant'), ...v(3, 0), ...s(4, '')];
expect(Buffer.from(bytes).toString('hex')).toBe(env(0xD69, 0, body, true)); expect(Buffer.from(bytes).toString('hex')).toBe(env(0xD72, 0, body, false));
});
it('resolves the current account when its self profile is not cached', async () => {
const sender = makeSender('');
await ApproveDoubtBuddyReq.invoke(sender, { uid: 'u_applicant' });
expect(sender.resolveUserUid).toHaveBeenCalledWith(10001);
const body = [...s(1, 'u_lookup_self'), ...s(2, 'u_applicant'), ...v(3, 0), ...s(4, '')];
expect(Buffer.from(sender.sendRawPacket.mock.calls[0]![1]).toString('hex'))
.toBe(env(0xD72, 0, body, false));
});
it('does not send when the current account cannot be identified', async () => {
const sender = makeSender('', '0');
await expect(ApproveDoubtBuddyReq.invoke(sender, { uid: 'u_applicant' }))
.rejects.toThrow('self uid is unavailable');
expect(sender.sendRawPacket).not.toHaveBeenCalled();
expect(sender.resolveUserUid).not.toHaveBeenCalled();
});
it('propagates self identity lookup errors without sending', async () => {
const sender = makeSender('');
sender.resolveUserUid.mockRejectedValue(new Error('profile lookup failed'));
await expect(ApproveDoubtBuddyReq.invoke(sender, { uid: 'u_applicant' }))
.rejects.toThrow('profile lookup failed');
expect(sender.sendRawPacket).not.toHaveBeenCalled();
});
it('rejects an empty resolved self identity before sending', async () => {
const sender = makeSender('');
sender.resolveUserUid.mockResolvedValue('');
await expect(ApproveDoubtBuddyReq.invoke(sender, { uid: 'u_applicant' }))
.rejects.toThrow('self uid is unavailable');
expect(sender.sendRawPacket).not.toHaveBeenCalled();
});
it.each(['', ' '])('rejects an absent applicant identity (%j)', async (uid) => {
const sender = makeSender();
await expect(ApproveDoubtBuddyReq.invoke(sender, { uid }))
.rejects.toThrow('applicant uid is unavailable');
expect(sender.sendRawPacket).not.toHaveBeenCalled();
});
it('propagates a rejected approval without retrying a different operation', async () => {
const sender = makeSender();
sender.sendRawPacket.mockResolvedValue({
success: false, gotResponse: true, errorCode: 1201,
errorMessage: 'request rejected', responseData: Buffer.alloc(0),
});
await expect(ApproveDoubtBuddyReq.invoke(sender, { uid: 'u_applicant' }))
.rejects.toThrow('request rejected');
expect(sender.sendRawPacket).toHaveBeenCalledOnce();
});
it('does not mistake a successful transport for an accepted approval', async () => {
const sender = makeSender();
sender.sendRawPacket.mockResolvedValue({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<OidbEmpty>>({
command: 0xD72, subCommand: 0, errorCode: 1201, errorMsg: 'approval denied', body: {},
})),
});
await expect(ApproveDoubtBuddyReq.invoke(sender, { uid: 'u_applicant' }))
.rejects.toThrow('approval denied');
expect(sender.sendRawPacket).toHaveBeenCalledOnce();
}); });
}); });