refactor(oidb): migrate friend.ts to namespaces

3 OIDB cmds moved to self-contained namespaces:
  - HandleFriendRequest (0xB5D_44) — digit-only flag still
                                     auto-resolves via resolveUserUid
  - DeleteFriend        (0x126B_0) — verbatim magic constants in the
                                     nested field2 sub-message
                                     (130/109/8/8/50 — server-side
                                     discriminator, MUST stay byte-
                                     equal to NTQQ wire)
  - SetFriendRemark     (0xB6E_2)

Cache invalidation (fetchFriendList after deletion) stays in the
facade — that side-effect needs `ctx.apis.contacts`, which namespaces
deliberately can't reach.

Tests migrated to assert against bridge.sendRawPacket. 15 new
namespace-level tests covering each invoke branch + serialize edge
cases.

Verification:
  - typecheck green
  - @snowluma/bridge: 15 files / 133 tests
  - friend.test.ts: 5/5
Wire bytes unchanged.
This commit is contained in:
DrSmoothl committed 2026-05-22 23:33:22 +08:00
1 parent a38f7ea26e
commit f78431242c
9 files changed
+370 -75

No files matched your search

+12
View File
@@ -83,6 +83,18 @@
"types": "./src/oidb-services/profile/get-unidirectional-friend-list.ts",
"default": "./src/oidb-services/profile/get-unidirectional-friend-list.ts"
},
"./oidb-services/friend/handle-friend-request": {
"types": "./src/oidb-services/friend/handle-friend-request.ts",
"default": "./src/oidb-services/friend/handle-friend-request.ts"
},
"./oidb-services/friend/delete-friend": {
"types": "./src/oidb-services/friend/delete-friend.ts",
"default": "./src/oidb-services/friend/delete-friend.ts"
},
"./oidb-services/friend/set-friend-remark": {
"types": "./src/oidb-services/friend/set-friend-remark.ts",
"default": "./src/oidb-services/friend/set-friend-remark.ts"
},
"./bridge-context": {
"types": "./src/bridge-context.ts",
"default": "./src/bridge-context.ts"
@@ -0,0 +1,58 @@
// 0x126B_0 — delete a friend (optionally with block flag).
//
// The deeply-nested field2 sub-message is a server-side discriminator
// that must be sent verbatim — the magic numbers (130 / 109 / 8/8/50)
// match the wire shape NTQQ's own client emits and aren't a SnowLuma
// invention. Server rejects the request if any of them is wrong.
//
// Cache invalidation (re-fetching the friend list after deletion)
// lives in the facade — keeps this namespace dependency-free of
// `apis.contacts` and the OneBot-side caches.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbDeleteFriend } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace DeleteFriend {
export const command = 0x126B;
export const subCommand = 0;
export interface Params {
userId: number;
/** Also block (拉黑) the user. Default false. */
block?: boolean;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = (p: Params, targetUid: string): OidbDeleteFriend => ({
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: { field1: 8, field2: 8, field3: 50 },
},
block: p.block ?? false,
field4: false,
},
});
export const deserialize = (_: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbDeleteFriend>): Uint8Array =>
protobuf_encode<OidbBase<OidbDeleteFriend>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = async (deps: Deps, params: Params): Promise<void> => {
const targetUid = await deps.resolveUserUid(params.userId);
await invokeOidb(deps, {
...DeleteFriend,
serialize: p => serialize(p, targetUid),
}, params);
};
}
@@ -0,0 +1,50 @@
// 0xB5D_44 — accept (3) / reject (5) an inbound friend request.
//
// Caller passes either a pre-resolved UID string or a numeric uin
// (encoded as a digit-only string); we detect the latter and resolve
// to UID first.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbFriendRequestAction } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace HandleFriendRequest {
export const command = 0xB5D;
export const subCommand = 44;
export interface Params {
/** Pre-resolved UID, or a digit-only numeric uin to resolve on demand. */
uidOrFlag: string;
approve: boolean;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = (p: Params, targetUid: string): OidbFriendRequestAction => ({
// Server discriminator: 3 = accept, 5 = reject. Pre-fix values
// verified against current production behaviour.
accept: p.approve ? 3 : 5,
targetUid,
});
export const deserialize = (_: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbFriendRequestAction>): Uint8Array =>
protobuf_encode<OidbBase<OidbFriendRequestAction>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = async (deps: Deps, params: Params): Promise<void> => {
let targetUid = params.uidOrFlag;
if (/^\d+$/.test(params.uidOrFlag)) {
targetUid = await deps.resolveUserUid(parseInt(params.uidOrFlag, 10));
}
await invokeOidb(deps, {
...HandleFriendRequest,
serialize: p => serialize(p, targetUid),
}, params);
};
}
@@ -0,0 +1,41 @@
// 0xB6E_2 — set the remark (备注) shown for a friend in the bot's
// own roster. Doesn't affect what the friend sees.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbSetFriendRemark } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
export namespace SetFriendRemark {
export const command = 0xB6E;
export const subCommand = 2;
export interface Params {
userId: number;
remark: string;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
export const serialize = (p: Params, targetUid: string): OidbSetFriendRemark => ({
targetUid,
remark: p.remark,
});
export const deserialize = (_: OidbEmpty): void => {};
export const encode = (env: OidbBase<OidbSetFriendRemark>): Uint8Array =>
protobuf_encode<OidbBase<OidbSetFriendRemark>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = async (deps: Deps, params: Params): Promise<void> => {
const targetUid = await deps.resolveUserUid(params.userId);
await invokeOidb(deps, {
...SetFriendRemark,
serialize: p => serialize(p, targetUid),
}, params);
};
}
@@ -0,0 +1,61 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbDeleteFriend } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { DeleteFriend } from '../../../src/oidb-services/friend/delete-friend';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
};
}
describe('DeleteFriend namespace', () => {
it('declares 0x126B_0', () => {
expect(DeleteFriend.command).toBe(0x126B);
expect(DeleteFriend.subCommand).toBe(0);
});
describe('invoke', () => {
it('routes to OidbSvcTrpcTcp.0x126b_0', async () => {
const deps = makeDeps();
await DeleteFriend.invoke(deps, { userId: 10001 });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x126b_0');
});
it('resolves the target uid before encoding', async () => {
const deps = makeDeps();
await DeleteFriend.invoke(deps, { userId: 10001 });
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
});
it('packages the nested envelope with verbatim magic constants', async () => {
const deps = makeDeps();
await DeleteFriend.invoke(deps, { userId: 10001, block: true });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbDeleteFriend>>(bytes);
expect(env.body?.field1).toMatchObject({
targetUid: 'resolved-uid',
block: true,
field2: {
field1: 130,
field2: 109,
field3: { field1: 8, field2: 8, field3: 50 },
},
});
});
it('defaults block to false (no block flag)', async () => {
const deps = makeDeps();
await DeleteFriend.invoke(deps, { userId: 10001 });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbDeleteFriend>>(bytes);
// proto3 false omitted on wire — decoded as null/undefined.
expect(env.body?.field1?.block ?? false).toBe(false);
});
});
});
@@ -0,0 +1,64 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbFriendRequestAction } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { HandleFriendRequest } from '../../../src/oidb-services/friend/handle-friend-request';
function makeDeps(resolvedUid = 'resolved-uid') {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => resolvedUid),
};
}
describe('HandleFriendRequest namespace', () => {
it('declares 0xB5D_44', () => {
expect(HandleFriendRequest.command).toBe(0xB5D);
expect(HandleFriendRequest.subCommand).toBe(44);
});
describe('invoke', () => {
it('routes to OidbSvcTrpcTcp.0xb5d_44', async () => {
const deps = makeDeps();
await HandleFriendRequest.invoke(deps, { uidOrFlag: 'uid', approve: true });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xb5d_44');
});
it('detects digit-only flag → resolves via resolveUserUid', async () => {
const deps = makeDeps('resolved-from-uin');
await HandleFriendRequest.invoke(deps, { uidOrFlag: '10001', approve: true });
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body?.targetUid).toBe('resolved-from-uin');
});
it('passes non-numeric flag through verbatim (no resolveUserUid call)', async () => {
const deps = makeDeps();
await HandleFriendRequest.invoke(deps, { uidOrFlag: 'flag-abc', approve: false });
expect(deps.resolveUserUid).not.toHaveBeenCalled();
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body?.targetUid).toBe('flag-abc');
});
it('encodes accept=3 when approve=true', async () => {
const deps = makeDeps();
await HandleFriendRequest.invoke(deps, { uidOrFlag: 'u', approve: true });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body?.accept).toBe(3);
});
it('encodes accept=5 when approve=false', async () => {
const deps = makeDeps();
await HandleFriendRequest.invoke(deps, { uidOrFlag: 'u', approve: false });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body?.accept).toBe(5);
});
});
});
@@ -0,0 +1,44 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbSetFriendRemark } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetFriendRemark } from '../../../src/oidb-services/friend/set-friend-remark';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
};
}
describe('SetFriendRemark namespace', () => {
it('declares 0xB6E_2', () => {
expect(SetFriendRemark.command).toBe(0xB6E);
expect(SetFriendRemark.subCommand).toBe(2);
});
describe('invoke', () => {
it('routes to OidbSvcTrpcTcp.0xb6e_2', async () => {
const deps = makeDeps();
await SetFriendRemark.invoke(deps, { userId: 10001, remark: 'x' });
expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xb6e_2');
});
it('resolves the target uid before encoding', async () => {
const deps = makeDeps();
await SetFriendRemark.invoke(deps, { userId: 10001, remark: 'best-friend' });
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
});
it('packages uid + remark in body', async () => {
const deps = makeDeps();
await SetFriendRemark.invoke(deps, { userId: 10001, remark: 'best-friend' });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbSetFriendRemark>>(bytes);
expect(env.body).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
});
});
});
+15 -48
View File
@@ -1,21 +1,15 @@
// FriendApi — friend roster mutations (handle add request /
// delete / set remark). Inlined from `actions/friend.ts` (deleted
// alongside actions/* in commit 13). The READ side of friends
// (fetchFriendList) lives on ContactsApi because friends/groups
// share the same roster pipeline.
// FriendApi — facade over friend-roster OIDB cmds. Every method is a
// one-line forwarder to a self-contained namespace under
// @snowluma/bridge/oidb-services/friend. The `delete()` facade method
// adds a best-effort friend-list cache invalidation after the OIDB
// call succeeds — that side-effect stays on the facade because it
// reaches into `ctx.apis.contacts`, which the namespace deliberately
// can't see.
import { protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbDeleteFriend,
OidbFriendRequestAction,
OidbSetFriendRemark,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
import { HandleFriendRequest } from '@snowluma/bridge/oidb-services/friend/handle-friend-request';
import { DeleteFriend } from '@snowluma/bridge/oidb-services/friend/delete-friend';
import { SetFriendRemark } from '@snowluma/bridge/oidb-services/friend/set-friend-remark';
export class FriendApi {
constructor(private readonly ctx: BridgeContext) {}
@@ -24,36 +18,12 @@ export class FriendApi {
* Accept or reject an inbound friend request. `uidOrFlag` is either a
* pre-resolved UID string or a numeric uin (then resolved on the fly).
*/
async handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
const bridge = asBridge(this.ctx);
let targetUid = uidOrFlag;
if (/^\d+$/.test(uidOrFlag)) {
targetUid = await this.ctx.resolveUserUid(parseInt(uidOrFlag, 10));
}
const env = makeOidbEnvelope<OidbFriendRequestAction>(0xB5D, 44, { accept: approve ? 3 : 5, targetUid });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xb5d_44', protobuf_encode<OidbBase<OidbFriendRequestAction>>(env));
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
}
async delete(userId: number, block = false): Promise<void> {
const bridge = asBridge(this.ctx);
const targetUid = await this.ctx.resolveUserUid(userId);
const env = makeOidbEnvelope<OidbDeleteFriend>(0x126B, 0, {
field1: {
targetUid,
field2: {
field1: 130,
field2: 109,
field3: {
field1: 8,
field2: 8,
field3: 50,
},
},
block,
field4: false,
},
});
await runOidb(bridge, 'OidbSvcTrpcTcp.0x126b_0', protobuf_encode<OidbBase<OidbDeleteFriend>>(env));
await DeleteFriend.invoke(this.ctx, { userId, block });
// Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
@@ -61,10 +31,7 @@ export class FriendApi {
try { await this.ctx.apis.contacts.fetchFriendList(); } catch { /* ignore */ }
}
async setRemark(userId: number, remark: string): Promise<void> {
const bridge = asBridge(this.ctx);
const uid = await this.ctx.resolveUserUid(userId);
const env = makeOidbEnvelope<OidbSetFriendRemark>(0xB6E, 2, { targetUid: uid, remark });
await runOidb(bridge, 'OidbSvcTrpcTcp.0xb6e_2', protobuf_encode<OidbBase<OidbSetFriendRemark>>(env));
setRemark(userId: number, remark: string): Promise<void> {
return SetFriendRemark.invoke(this.ctx, { userId, remark });
}
}
+25 -27
View File
@@ -1,54 +1,52 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbDeleteFriend,
OidbFriendRequestAction,
OidbSetFriendRemark,
} from '@snowluma/proto-defs/oidb-actions/base';
vi.mock('@snowluma/bridge/bridge-oidb', () => ({
runOidb: vi.fn(async () => new Uint8Array()),
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
encodeOidbEnv: vi.fn(() => new Uint8Array()),
decodeOidbEnv: vi.fn(() => ({ body: {} })),
}));
import * as oidb from '@snowluma/bridge/bridge-oidb';
// Post-namespace migration: FriendApi is a thin facade over the
// namespaces under @snowluma/bridge/oidb-services/friend. Tests assert
// against the bridge mock's sendRawPacket directly — no need for
// module-level bridge-oidb mocks anymore.
import { FriendApi } from '../../src/bridge/apis/friend';
import { mockBridge } from './_helpers';
describe('apis/friend', () => {
beforeEach(() => {
vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.makeOidbEnvelope).mockClear();
});
it('handleRequest: numeric input is treated as UIN and resolved', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).handleRequest('10001', true);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ accept: 3, targetUid: 'resolved-uid' });
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xb5d_44');
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body).toMatchObject({ accept: 3, targetUid: 'resolved-uid' });
});
it('handleRequest: non-numeric flag is forwarded as-is', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).handleRequest('flag-abc', false);
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ accept: 5, targetUid: 'flag-abc' });
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbFriendRequestAction>>(bytes);
expect(env.body).toMatchObject({ accept: 5, targetUid: 'flag-abc' });
});
it('delete resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).delete(10001, true);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0x126b_0');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect((body as any).field1.block).toBe(true);
const env = protobuf_decode<OidbBase<OidbDeleteFriend>>(bytes);
expect(env.body?.field1?.block).toBe(true);
expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalled();
});
it('delete still succeeds when the friend-list refresh throws', async () => {
const bridge = mockBridge();
// `fetchFriendList` lives on `apis.contacts` post-#6 refactor;
// override the default no-op stub to make the friend-list refresh
// throw and verify delete swallows the error.
bridge.apis.contacts.fetchFriendList = vi.fn(async () => { throw new Error('cache miss'); });
await expect(new FriendApi(bridge as any).delete(10001))
.resolves.toBeUndefined();
@@ -57,9 +55,9 @@ describe('apis/friend', () => {
it('setRemark resolves UID and sends 0xb6e_2', async () => {
const bridge = mockBridge();
await new FriendApi(bridge as any).setRemark(10001, 'best-friend');
const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!;
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xb6e_2');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect(body).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
const env = protobuf_decode<OidbBase<OidbSetFriendRemark>>(bytes);
expect(env.body).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
});
});