refactor(oidb): migrate contacts.ts OIDB cmds to namespaces
6 OIDB cmds moved; pagination + per-group cache + inflight
coalescing stay on the facade because they need cross-call state.
- FetchFriendListPage (0xFD4_1) — facade drives the cursor loop
- FetchGroupList (0xFE5_2) — uinForm; verbatim config blob
- FetchGroupMemberListPage (0xFE7_3) — facade drives the token loop +
owns the TTL cache + inflight
coalescing that keeps busy
OneBot clients from tripping
Tencent risk-control
- FetchUserProfile (0xFE1_2) — uinForm; full property-key
catalogue cross-checked against
LagrangeV2 FetchStrangerService.cs
- FetchGroupRequests (0x10C0_1/_2) — dynamic subcmd via filtered flag
- FetchDownloadRkeys (0x9067_202) — uinForm; respHead.retCode
check moved into deserialize
35 new namespace-level tests covering serialize / deserialize edge
cases (property decoding, sex enum mapping, avatar URL suffix,
empty body handling, pagination cursor behaviour).
Verification:
- typecheck green
- @snowluma/bridge: 30 files / 233 tests
- @snowluma/core: 302 tests
Wire bytes unchanged.
This commit is contained in:
14 files changed
+864
-248
No files matched your search
@@ -131,6 +131,30 @@
|
||||
"types": "./src/oidb-services/extras/fetch-ai-voice.ts",
|
||||
"default": "./src/oidb-services/extras/fetch-ai-voice.ts"
|
||||
},
|
||||
"./oidb-services/contacts/fetch-friend-list-page": {
|
||||
"types": "./src/oidb-services/contacts/fetch-friend-list-page.ts",
|
||||
"default": "./src/oidb-services/contacts/fetch-friend-list-page.ts"
|
||||
},
|
||||
"./oidb-services/contacts/fetch-group-list": {
|
||||
"types": "./src/oidb-services/contacts/fetch-group-list.ts",
|
||||
"default": "./src/oidb-services/contacts/fetch-group-list.ts"
|
||||
},
|
||||
"./oidb-services/contacts/fetch-group-member-list-page": {
|
||||
"types": "./src/oidb-services/contacts/fetch-group-member-list-page.ts",
|
||||
"default": "./src/oidb-services/contacts/fetch-group-member-list-page.ts"
|
||||
},
|
||||
"./oidb-services/contacts/fetch-user-profile": {
|
||||
"types": "./src/oidb-services/contacts/fetch-user-profile.ts",
|
||||
"default": "./src/oidb-services/contacts/fetch-user-profile.ts"
|
||||
},
|
||||
"./oidb-services/contacts/fetch-group-requests": {
|
||||
"types": "./src/oidb-services/contacts/fetch-group-requests.ts",
|
||||
"default": "./src/oidb-services/contacts/fetch-group-requests.ts"
|
||||
},
|
||||
"./oidb-services/contacts/fetch-download-rkeys": {
|
||||
"types": "./src/oidb-services/contacts/fetch-download-rkeys.ts",
|
||||
"default": "./src/oidb-services/contacts/fetch-download-rkeys.ts"
|
||||
},
|
||||
"./bridge-context": {
|
||||
"types": "./src/bridge-context.ts",
|
||||
"default": "./src/bridge-context.ts"
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// 0x9067_202 — fetch download-rkey tokens for private/group/fallback
|
||||
// image scopes. The rkey is a server-issued signed download token used
|
||||
// to authenticate every CDN GET against `gchat.qpic.cn` / similar
|
||||
// endpoints.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
|
||||
const PRIVATE_IMAGE = 10;
|
||||
const GROUP_IMAGE = 20;
|
||||
const FALLBACK_IMAGE = 2;
|
||||
|
||||
export namespace FetchDownloadRkeys {
|
||||
export const command = 0x9067;
|
||||
export const subCommand = 202;
|
||||
export const uinForm = true;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
export interface Params {}
|
||||
|
||||
export type Deps = OidbSender;
|
||||
|
||||
export const serialize = (_: Params): NTV2RichMediaReq => ({
|
||||
reqHead: {
|
||||
common: { requestId: 1, command: 202 },
|
||||
scene: { requestType: 2, businessType: 1, sceneType: 0 },
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
downloadRkey: {
|
||||
types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE],
|
||||
},
|
||||
});
|
||||
|
||||
export const deserialize = (body: NTV2RichMediaResp): NTV2RichMediaResp => {
|
||||
// Propagate server-side OIDB-equivalent error via the embedded
|
||||
// respHead.retCode — bytes-level OIDB errorCode would already
|
||||
// have thrown OidbError before deserialize was called.
|
||||
if (body.respHead?.retCode && body.respHead.retCode !== 0) {
|
||||
throw new Error(body.respHead.message ?? 'fetch download rkey failed');
|
||||
}
|
||||
return body;
|
||||
};
|
||||
|
||||
export const encode = (env: OidbBase<NTV2RichMediaReq>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<NTV2RichMediaReq>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<NTV2RichMediaResp> =>
|
||||
protobuf_decode<OidbBase<NTV2RichMediaResp>>(bytes);
|
||||
|
||||
export const invoke = (deps: Deps): Promise<NTV2RichMediaResp> =>
|
||||
invokeOidb(deps, FetchDownloadRkeys, {});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// 0xFD4_1 — single-page friend-roster fetch.
|
||||
//
|
||||
// QQ paginates the friend list with a wire-level cursor (`nextUin`).
|
||||
// This namespace handles ONE round-trip — the facade drives the
|
||||
// while-loop until the server stops emitting a next cursor and
|
||||
// concatenates results into the public FriendInfo[] shape.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
|
||||
export namespace FetchFriendListPage {
|
||||
export const command = 0xFD4;
|
||||
export const subCommand = 1;
|
||||
|
||||
export interface Params {
|
||||
/** Cursor: `null` for the first page, otherwise the previous
|
||||
* page's `nextUin`. */
|
||||
nextUin: number | null;
|
||||
}
|
||||
|
||||
export type Deps = OidbSender;
|
||||
|
||||
export const serialize = (p: Params): OidbFriendListRequest => {
|
||||
const body: any = {
|
||||
friendCount: 300,
|
||||
field4: 0,
|
||||
field6: 1,
|
||||
field7: 0x7FFFFFFF,
|
||||
body: [
|
||||
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
|
||||
{ type: 4, number: { numbers: [100, 101, 102] } },
|
||||
],
|
||||
field10002: [13578, 13579, 13573, 13572, 13568],
|
||||
field10003: 4051,
|
||||
};
|
||||
if (p.nextUin !== null) {
|
||||
body.nextUin = { uin: p.nextUin };
|
||||
}
|
||||
return body;
|
||||
};
|
||||
|
||||
export const deserialize = (body: OidbSvcTrpcTcp0xFD4_1Response): OidbSvcTrpcTcp0xFD4_1Response => body;
|
||||
|
||||
export const encode = (env: OidbBase<OidbFriendListRequest>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<OidbFriendListRequest>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0xFD4_1Response> =>
|
||||
protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>(bytes);
|
||||
|
||||
export const invoke = (deps: Deps, params: Params): Promise<OidbSvcTrpcTcp0xFD4_1Response> =>
|
||||
invokeOidb(deps, FetchFriendListPage, params);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// 0xFE5_2 — fetch the bot's joined-groups list with full per-group
|
||||
// info.
|
||||
//
|
||||
// The verbose `config` blob in the request body asks QQ which
|
||||
// per-group fields to include. Asking for everything blows the
|
||||
// named-pipe write buffer on accounts with ~200+ groups (see #42),
|
||||
// so we keep `config1.*` mostly on but turn off the costly
|
||||
// `field5002`/`field5003` and entire `config2` block that never map
|
||||
// back to a decoded field anyway.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase, OidbSvcTrpcTcp0xFE5_2Response } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupListRequest } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
|
||||
export namespace FetchGroupList {
|
||||
export const command = 0xFE5;
|
||||
export const subCommand = 2;
|
||||
export const uinForm = true;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
export interface Params {}
|
||||
|
||||
export type Deps = OidbSender;
|
||||
|
||||
const allTrue = true;
|
||||
|
||||
export const serialize = (_: Params): OidbGroupListRequest => ({
|
||||
config: {
|
||||
config1: {
|
||||
groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue,
|
||||
groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue,
|
||||
field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue,
|
||||
field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue,
|
||||
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
|
||||
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
|
||||
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
|
||||
field32: allTrue, field5001: allTrue, field5002: false, field5003: false,
|
||||
},
|
||||
config2: {
|
||||
field1: false, field2: false, field3: false, field4: false,
|
||||
field5: false, field6: false, field7: false, field8: false,
|
||||
},
|
||||
config3: { field5: allTrue, field6: allTrue },
|
||||
},
|
||||
});
|
||||
|
||||
export const deserialize = (body: OidbSvcTrpcTcp0xFE5_2Response): OidbSvcTrpcTcp0xFE5_2Response => body;
|
||||
|
||||
export const encode = (env: OidbBase<OidbGroupListRequest>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<OidbGroupListRequest>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0xFE5_2Response> =>
|
||||
protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>(bytes);
|
||||
|
||||
export const invoke = (deps: Deps): Promise<OidbSvcTrpcTcp0xFE5_2Response> =>
|
||||
invokeOidb(deps, FetchGroupList, {});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// 0xFE7_3 — single-page group-member-roster fetch.
|
||||
//
|
||||
// Pagination cursor is the server-issued `token` string. The facade
|
||||
// drives the loop until `token` comes back empty; per-group caching
|
||||
// + inflight coalescing also stays on the facade since both need
|
||||
// state that's per-Bridge (and is what stops Tencent risk-control
|
||||
// from banning the account on busy clients — see #42).
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase, OidbSvcTrpcTcp0xFE7_3Response } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupMemberListRequest } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
|
||||
export namespace FetchGroupMemberListPage {
|
||||
export const command = 0xFE7;
|
||||
export const subCommand = 3;
|
||||
|
||||
export interface Params {
|
||||
groupId: number;
|
||||
/** Empty string for the first page; pass the previous response's
|
||||
* `token` to fetch the next page. */
|
||||
token: string;
|
||||
}
|
||||
|
||||
export type Deps = OidbSender;
|
||||
|
||||
export const serialize = (p: Params): OidbGroupMemberListRequest => {
|
||||
const body: any = {
|
||||
groupUin: p.groupId,
|
||||
field2: 5,
|
||||
field3: 2,
|
||||
body: {
|
||||
memberName: true, memberCard: true, level: true, field13: true,
|
||||
field16: true, specialTitle: true, field18: true, field20: true,
|
||||
field21: true, joinTimestamp: true, lastMsgTimestamp: true,
|
||||
shutUpTimestamp: true, field103: true, field104: true, field105: true,
|
||||
field106: true, permission: true, field200: true, field201: true,
|
||||
},
|
||||
};
|
||||
if (p.token) body.token = p.token;
|
||||
return body;
|
||||
};
|
||||
|
||||
export const deserialize = (body: OidbSvcTrpcTcp0xFE7_3Response): OidbSvcTrpcTcp0xFE7_3Response => body;
|
||||
|
||||
export const encode = (env: OidbBase<OidbGroupMemberListRequest>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<OidbGroupMemberListRequest>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0xFE7_3Response> =>
|
||||
protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE7_3Response>>(bytes);
|
||||
|
||||
export const invoke = (deps: Deps, params: Params): Promise<OidbSvcTrpcTcp0xFE7_3Response> =>
|
||||
invokeOidb(deps, FetchGroupMemberListPage, params);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// 0x10C0 — fetch pending group-add requests.
|
||||
// subCommand 1 = main inbox, 2 = filtered (low-priority) inbox
|
||||
//
|
||||
// Returns the wire shape verbatim — the facade does the GroupRequestInfo
|
||||
// mapping because it also needs to thread the `filtered` flag onto
|
||||
// each entry, which the wire doesn't carry.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase, OidbSvcTrpcTcp0x10C0Response } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupRequestList } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
|
||||
export namespace FetchGroupRequests {
|
||||
export const command = 0x10C0;
|
||||
|
||||
export interface Params {
|
||||
/** false → subCmd 1 (main inbox), true → subCmd 2 (filtered). */
|
||||
filtered: boolean;
|
||||
}
|
||||
|
||||
export type Deps = OidbSender;
|
||||
|
||||
export const resolveSubCommand = (p: Params): number => p.filtered ? 2 : 1;
|
||||
|
||||
export const serialize = (_: Params): OidbGroupRequestList => ({
|
||||
count: 20,
|
||||
field2: 0,
|
||||
});
|
||||
|
||||
export const deserialize = (body: OidbSvcTrpcTcp0x10C0Response): OidbSvcTrpcTcp0x10C0Response => body;
|
||||
|
||||
export const encode = (env: OidbBase<OidbGroupRequestList>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<OidbGroupRequestList>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<OidbSvcTrpcTcp0x10C0Response> =>
|
||||
protobuf_decode<OidbBase<OidbSvcTrpcTcp0x10C0Response>>(bytes);
|
||||
|
||||
export const invoke = (deps: Deps, params: Params): Promise<OidbSvcTrpcTcp0x10C0Response> =>
|
||||
invokeOidb(deps, FetchGroupRequests, params);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// 0xFE1_2 — fetch a user's profile (nickname / qid / sex / age / sign
|
||||
// / avatar / QQ level).
|
||||
//
|
||||
// `uinForm` is set so the server takes the UIN-form validation path;
|
||||
// without it newer NTQQ versions reject the request with
|
||||
// `[oidb] one of uid/openid is invaild`. Matches Lagrange.Core's
|
||||
// FetchStrangerByUin (Reserved = 1).
|
||||
//
|
||||
// Property key catalogue (cross-checked against LagrangeV2's
|
||||
// FetchStrangerService.cs):
|
||||
// 101 — avatar info (proto-encoded AvatarInfo)
|
||||
// 102 — sign (signature)
|
||||
// 103 — remark
|
||||
// 105 — QQ level (numeric)
|
||||
// 20002 — nickname
|
||||
// 20009 — gender (1 male / 2 female / 255 unknown)
|
||||
// 20037 — age
|
||||
// 27394 — QID
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
AvatarInfo,
|
||||
OidbUserInfoRequest,
|
||||
OidbUserInfoResponse,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { UserProfileInfo } from '../../qq-info';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
|
||||
const REQUESTED_KEYS = [
|
||||
20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026,
|
||||
105, 27372, 27406, 20037,
|
||||
];
|
||||
|
||||
export namespace FetchUserProfile {
|
||||
export const command = 0xFE1;
|
||||
export const subCommand = 2;
|
||||
export const uinForm = true;
|
||||
|
||||
export interface Params {
|
||||
uin: number;
|
||||
}
|
||||
|
||||
export type Deps = OidbSender;
|
||||
|
||||
export const serialize = (p: Params): OidbUserInfoRequest => ({
|
||||
uin: p.uin,
|
||||
keys: REQUESTED_KEYS.map(k => ({ key: k })),
|
||||
});
|
||||
|
||||
export const deserialize = (body: OidbUserInfoResponse, requestedUin: number): UserProfileInfo => {
|
||||
if (!body.body) throw new Error('user info response body missing');
|
||||
|
||||
const info: UserProfileInfo = {
|
||||
uin: body.body.uin ?? requestedUin,
|
||||
uid: body.body.uid ?? '',
|
||||
nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
|
||||
};
|
||||
|
||||
if (body.body.properties) {
|
||||
const bytesMap = new Map<number, Uint8Array>();
|
||||
const numMap = new Map<number, number>();
|
||||
for (const bp of body.body.properties.bytesProperties ?? []) {
|
||||
bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0));
|
||||
}
|
||||
for (const np of body.body.properties.numberProperties ?? []) {
|
||||
numMap.set(np.number1 ?? 0, np.number2 ?? 0);
|
||||
}
|
||||
const getString = (code: number): string => {
|
||||
const b = bytesMap.get(code);
|
||||
return b ? Buffer.from(b).toString('utf8') : '';
|
||||
};
|
||||
info.nickname = getString(20002);
|
||||
info.remark = getString(103);
|
||||
info.qid = getString(27394);
|
||||
info.sign = getString(102);
|
||||
|
||||
const avatarBytes = bytesMap.get(101);
|
||||
if (avatarBytes) {
|
||||
const av = protobuf_decode<AvatarInfo>(avatarBytes);
|
||||
if (av?.url) info.avatar = av.url + '640';
|
||||
}
|
||||
const sexNum = numMap.get(20009) ?? 0;
|
||||
info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown';
|
||||
info.age = numMap.get(20037) ?? 0;
|
||||
info.level = numMap.get(105) ?? 0;
|
||||
}
|
||||
|
||||
return info;
|
||||
};
|
||||
|
||||
export const encode = (env: OidbBase<OidbUserInfoRequest>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<OidbUserInfoRequest>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<OidbUserInfoResponse> =>
|
||||
protobuf_decode<OidbBase<OidbUserInfoResponse>>(bytes);
|
||||
|
||||
export const invoke = (deps: Deps, params: Params): Promise<UserProfileInfo> =>
|
||||
invokeOidb(deps, {
|
||||
...FetchUserProfile,
|
||||
// Bind the original `params.uin` into deserialize so the
|
||||
// namespace can default to it when the server omits its echo.
|
||||
deserialize: body => deserialize(body, params.uin),
|
||||
}, params);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
import { FetchDownloadRkeys } from '../../../src/oidb-services/contacts/fetch-download-rkeys';
|
||||
|
||||
function makeSender(body?: NTV2RichMediaResp) {
|
||||
const responseData = body !== undefined
|
||||
? Buffer.from(protobuf_encode<OidbBase<NTV2RichMediaResp>>({ body }))
|
||||
: Buffer.alloc(0);
|
||||
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
|
||||
return { sendRawPacket: vi.fn(async () => r) };
|
||||
}
|
||||
|
||||
describe('FetchDownloadRkeys namespace', () => {
|
||||
it('declares 0x9067_202 with uinForm=true', () => {
|
||||
expect(FetchDownloadRkeys.command).toBe(0x9067);
|
||||
expect(FetchDownloadRkeys.subCommand).toBe(202);
|
||||
expect(FetchDownloadRkeys.uinForm).toBe(true);
|
||||
});
|
||||
|
||||
describe('serialize', () => {
|
||||
it('requests the (private=10, group=20, fallback=2) image scopes', () => {
|
||||
const out = FetchDownloadRkeys.serialize({});
|
||||
expect(out.downloadRkey?.types).toEqual([10, 20, 2]);
|
||||
});
|
||||
|
||||
it('packages the fixed reqHead { common, scene, client }', () => {
|
||||
const out = FetchDownloadRkeys.serialize({});
|
||||
expect(out.reqHead).toEqual({
|
||||
common: { requestId: 1, command: 202 },
|
||||
scene: { requestType: 2, businessType: 1, sceneType: 0 },
|
||||
client: { agentType: 2 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('deserialize', () => {
|
||||
it('throws when respHead.retCode is non-zero', () => {
|
||||
expect(() => FetchDownloadRkeys.deserialize({
|
||||
respHead: { retCode: 42, message: 'bad' },
|
||||
} as any)).toThrow('bad');
|
||||
});
|
||||
|
||||
it('passes through on retCode = 0', () => {
|
||||
const body = { respHead: { retCode: 0 }, downloadRkey: { rkeys: [] } };
|
||||
expect(FetchDownloadRkeys.deserialize(body as any)).toBe(body);
|
||||
});
|
||||
|
||||
it('falls back to a generic message when none is provided', () => {
|
||||
expect(() => FetchDownloadRkeys.deserialize({
|
||||
respHead: { retCode: 1 },
|
||||
} as any)).toThrow('fetch download rkey failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('invoke (e2e)', () => {
|
||||
it('routes to OidbSvcTrpcTcp.0x9067_202 with reserved=1', async () => {
|
||||
const sender = makeSender({ respHead: { retCode: 0 }, downloadRkey: { rkeys: [] } } as any);
|
||||
await FetchDownloadRkeys.invoke(sender);
|
||||
const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!;
|
||||
expect(wireName).toBe('OidbSvcTrpcTcp.0x9067_202');
|
||||
const env = protobuf_decode<OidbBase<NTV2RichMediaReq>>(bytes);
|
||||
expect(env.reserved).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
import { FetchFriendListPage } from '../../../src/oidb-services/contacts/fetch-friend-list-page';
|
||||
|
||||
function makeSender(body?: OidbSvcTrpcTcp0xFD4_1Response) {
|
||||
const responseData = body !== undefined
|
||||
? Buffer.from(protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>({ body }))
|
||||
: Buffer.alloc(0);
|
||||
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
|
||||
return { sendRawPacket: vi.fn(async () => r) };
|
||||
}
|
||||
|
||||
describe('FetchFriendListPage namespace', () => {
|
||||
it('declares 0xFD4_1', () => {
|
||||
expect(FetchFriendListPage.command).toBe(0xFD4);
|
||||
expect(FetchFriendListPage.subCommand).toBe(1);
|
||||
});
|
||||
|
||||
describe('serialize', () => {
|
||||
it('omits nextUin on the first page', () => {
|
||||
const out = FetchFriendListPage.serialize({ nextUin: null }) as any;
|
||||
expect(out.nextUin).toBeUndefined();
|
||||
expect(out.friendCount).toBe(300);
|
||||
expect(out.field4).toBe(0);
|
||||
});
|
||||
|
||||
it('includes nextUin sub-message on follow-up pages', () => {
|
||||
const out = FetchFriendListPage.serialize({ nextUin: 10001 }) as any;
|
||||
expect(out.nextUin).toEqual({ uin: 10001 });
|
||||
});
|
||||
|
||||
it('emits the verbatim property request list (codes 100/101/102/103/20002/27394)', () => {
|
||||
const out = FetchFriendListPage.serialize({ nextUin: null }) as any;
|
||||
expect(out.body).toEqual([
|
||||
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
|
||||
{ type: 4, number: { numbers: [100, 101, 102] } },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('invoke (e2e)', () => {
|
||||
it('routes to OidbSvcTrpcTcp.0xfd4_1', async () => {
|
||||
const sender = makeSender({ friends: [] });
|
||||
await FetchFriendListPage.invoke(sender, { nextUin: null });
|
||||
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xfd4_1');
|
||||
});
|
||||
|
||||
it('returns the wire body verbatim (facade does the FriendInfo mapping)', async () => {
|
||||
const body = { friends: [{ uin: 10001, uid: 'u', additional: [] }], next: { uin: 0 } };
|
||||
const sender = makeSender(body as any);
|
||||
const out = await FetchFriendListPage.invoke(sender, { nextUin: null });
|
||||
expect(out.friends).toBeDefined();
|
||||
expect(out.next?.uin ?? 0).toBe(0);
|
||||
});
|
||||
|
||||
it('encodes envelope body correctly', async () => {
|
||||
const sender = makeSender({ friends: [] });
|
||||
await FetchFriendListPage.invoke(sender, { nextUin: 10001 });
|
||||
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbFriendListRequest>>(bytes);
|
||||
expect(env.body?.nextUin).toEqual({ uin: 10001 });
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupListRequest } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
import { FetchGroupList } from '../../../src/oidb-services/contacts/fetch-group-list';
|
||||
|
||||
function makeSender() {
|
||||
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
|
||||
return { sendRawPacket: vi.fn(async () => r) };
|
||||
}
|
||||
|
||||
describe('FetchGroupList namespace', () => {
|
||||
it('declares 0xFE5_2 with uinForm=true', () => {
|
||||
expect(FetchGroupList.command).toBe(0xFE5);
|
||||
expect(FetchGroupList.subCommand).toBe(2);
|
||||
expect(FetchGroupList.uinForm).toBe(true);
|
||||
});
|
||||
|
||||
describe('invoke (e2e)', () => {
|
||||
it('routes to OidbSvcTrpcTcp.0xfe5_2 with envelope reserved=1', async () => {
|
||||
const sender = makeSender();
|
||||
await FetchGroupList.invoke(sender);
|
||||
const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!;
|
||||
expect(wireName).toBe('OidbSvcTrpcTcp.0xfe5_2');
|
||||
const env = protobuf_decode<OidbBase<OidbGroupListRequest>>(bytes);
|
||||
expect(env.reserved).toBe(1);
|
||||
});
|
||||
|
||||
it('sends the verbatim config blob (field5002/5003 OFF to avoid EPIPE on big rosters)', async () => {
|
||||
const sender = makeSender();
|
||||
await FetchGroupList.invoke(sender);
|
||||
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbGroupListRequest>>(bytes);
|
||||
expect(env.body?.config?.config1?.groupName).toBe(true);
|
||||
expect(env.body?.config?.config1?.memberCount).toBe(true);
|
||||
// proto3 default false — omitted on wire, decoded as null.
|
||||
expect(env.body?.config?.config1?.field5002 ?? false).toBe(false);
|
||||
expect(env.body?.config?.config1?.field5003 ?? false).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupMemberListRequest } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
import { FetchGroupMemberListPage } from '../../../src/oidb-services/contacts/fetch-group-member-list-page';
|
||||
|
||||
function makeSender() {
|
||||
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
|
||||
return { sendRawPacket: vi.fn(async () => r) };
|
||||
}
|
||||
|
||||
describe('FetchGroupMemberListPage namespace', () => {
|
||||
it('declares 0xFE7_3', () => {
|
||||
expect(FetchGroupMemberListPage.command).toBe(0xFE7);
|
||||
expect(FetchGroupMemberListPage.subCommand).toBe(3);
|
||||
});
|
||||
|
||||
describe('serialize', () => {
|
||||
it('omits the token on the first page', () => {
|
||||
const out = FetchGroupMemberListPage.serialize({ groupId: 12345, token: '' }) as any;
|
||||
expect(out.token).toBeUndefined();
|
||||
expect(out.groupUin).toBe(12345);
|
||||
});
|
||||
|
||||
it('threads the server-issued token into follow-up pages', () => {
|
||||
const out = FetchGroupMemberListPage.serialize({ groupId: 12345, token: 'next-cursor' }) as any;
|
||||
expect(out.token).toBe('next-cursor');
|
||||
});
|
||||
|
||||
it('always requests the full member-field projection', () => {
|
||||
const out = FetchGroupMemberListPage.serialize({ groupId: 1, token: '' }) as any;
|
||||
expect(out.body).toMatchObject({
|
||||
memberName: true, memberCard: true, level: true,
|
||||
joinTimestamp: true, lastMsgTimestamp: true, shutUpTimestamp: true,
|
||||
permission: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('invoke (e2e)', () => {
|
||||
it('routes to OidbSvcTrpcTcp.0xfe7_3', async () => {
|
||||
const sender = makeSender();
|
||||
await FetchGroupMemberListPage.invoke(sender, { groupId: 1, token: '' });
|
||||
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xfe7_3');
|
||||
});
|
||||
|
||||
it('encodes envelope body with the groupId', async () => {
|
||||
const sender = makeSender();
|
||||
await FetchGroupMemberListPage.invoke(sender, { groupId: 12345, token: '' });
|
||||
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbGroupMemberListRequest>>(bytes);
|
||||
expect(env.body?.groupUin).toBe(12345);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupRequestList } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
import { FetchGroupRequests } from '../../../src/oidb-services/contacts/fetch-group-requests';
|
||||
|
||||
function makeSender() {
|
||||
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
|
||||
return { sendRawPacket: vi.fn(async () => r) };
|
||||
}
|
||||
|
||||
describe('FetchGroupRequests namespace', () => {
|
||||
it('declares 0x10C0', () => {
|
||||
expect(FetchGroupRequests.command).toBe(0x10C0);
|
||||
});
|
||||
|
||||
describe('resolveSubCommand', () => {
|
||||
it('returns 1 when filtered=false (main inbox)', () => {
|
||||
expect(FetchGroupRequests.resolveSubCommand({ filtered: false })).toBe(1);
|
||||
});
|
||||
it('returns 2 when filtered=true (low-priority inbox)', () => {
|
||||
expect(FetchGroupRequests.resolveSubCommand({ filtered: true })).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('serialize', () => {
|
||||
it('always sends count=20 / field2=0', () => {
|
||||
expect(FetchGroupRequests.serialize({ filtered: false })).toEqual({ count: 20, field2: 0 });
|
||||
expect(FetchGroupRequests.serialize({ filtered: true })).toEqual({ count: 20, field2: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('invoke (e2e)', () => {
|
||||
it('routes to 0x10c0_1 for the main inbox', async () => {
|
||||
const sender = makeSender();
|
||||
await FetchGroupRequests.invoke(sender, { filtered: false });
|
||||
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x10c0_1');
|
||||
});
|
||||
|
||||
it('routes to 0x10c0_2 for the filtered inbox', async () => {
|
||||
const sender = makeSender();
|
||||
await FetchGroupRequests.invoke(sender, { filtered: true });
|
||||
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x10c0_2');
|
||||
});
|
||||
|
||||
it('encodes envelope body with count=20', async () => {
|
||||
const sender = makeSender();
|
||||
await FetchGroupRequests.invoke(sender, { filtered: false });
|
||||
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbGroupRequestList>>(bytes);
|
||||
expect(env.body?.count).toBe(20);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
AvatarInfo, OidbUserInfoRequest, OidbUserInfoResponse,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
import { FetchUserProfile } from '../../../src/oidb-services/contacts/fetch-user-profile';
|
||||
|
||||
function makeSender(body?: OidbUserInfoResponse) {
|
||||
const responseData = body !== undefined
|
||||
? Buffer.from(protobuf_encode<OidbBase<OidbUserInfoResponse>>({ body }))
|
||||
: Buffer.alloc(0);
|
||||
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
|
||||
return { sendRawPacket: vi.fn(async () => r) };
|
||||
}
|
||||
|
||||
describe('FetchUserProfile namespace', () => {
|
||||
it('declares 0xFE1_2 with uinForm=true', () => {
|
||||
expect(FetchUserProfile.command).toBe(0xFE1);
|
||||
expect(FetchUserProfile.subCommand).toBe(2);
|
||||
expect(FetchUserProfile.uinForm).toBe(true);
|
||||
});
|
||||
|
||||
describe('invoke (e2e)', () => {
|
||||
it('routes to OidbSvcTrpcTcp.0xfe1_2 with reserved=1', async () => {
|
||||
const sender = makeSender({ body: { uin: 10001, uid: 'u' } as any });
|
||||
await FetchUserProfile.invoke(sender, { uin: 10001 });
|
||||
const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!;
|
||||
expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2');
|
||||
const env = protobuf_decode<OidbBase<OidbUserInfoRequest>>(bytes);
|
||||
expect(env.reserved).toBe(1);
|
||||
});
|
||||
|
||||
it('requests every property key in the catalogue (nickname, level, …)', async () => {
|
||||
const sender = makeSender({ body: { uin: 10001, uid: 'u' } as any });
|
||||
await FetchUserProfile.invoke(sender, { uin: 10001 });
|
||||
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbUserInfoRequest>>(bytes);
|
||||
const keys = env.body?.keys?.map(k => k.key);
|
||||
expect(keys).toContain(20002); // nickname
|
||||
expect(keys).toContain(105); // level
|
||||
expect(keys).toContain(101); // avatar
|
||||
expect(keys).toContain(102); // sign
|
||||
expect(keys).toContain(103); // remark
|
||||
});
|
||||
|
||||
it('decodes nickname / remark / qid / sign from bytes-properties', async () => {
|
||||
const enc = (s: string) => new TextEncoder().encode(s);
|
||||
const sender = makeSender({
|
||||
body: {
|
||||
uin: 10001, uid: 'u',
|
||||
properties: {
|
||||
bytesProperties: [
|
||||
{ code: 20002, value: enc('Nick') },
|
||||
{ code: 103, value: enc('Bestie') },
|
||||
{ code: 27394, value: enc('myqid') },
|
||||
{ code: 102, value: enc('Hello') },
|
||||
],
|
||||
numberProperties: [],
|
||||
},
|
||||
} as any,
|
||||
});
|
||||
const out = await FetchUserProfile.invoke(sender, { uin: 10001 });
|
||||
expect(out.nickname).toBe('Nick');
|
||||
expect(out.remark).toBe('Bestie');
|
||||
expect(out.qid).toBe('myqid');
|
||||
expect(out.sign).toBe('Hello');
|
||||
});
|
||||
|
||||
it('decodes sex / age / level from number-properties (sex enum)', async () => {
|
||||
const cases: Array<[number, string]> = [
|
||||
[1, 'male'], [2, 'female'], [255, 'unknown'], [0, 'unknown'],
|
||||
];
|
||||
for (const [sexNum, expected] of cases) {
|
||||
const sender = makeSender({
|
||||
body: {
|
||||
uin: 1, uid: 'u',
|
||||
properties: {
|
||||
bytesProperties: [],
|
||||
numberProperties: [
|
||||
{ number1: 20009, number2: sexNum },
|
||||
{ number1: 20037, number2: 25 },
|
||||
{ number1: 105, number2: 7 },
|
||||
],
|
||||
},
|
||||
} as any,
|
||||
});
|
||||
const out = await FetchUserProfile.invoke(sender, { uin: 1 });
|
||||
expect(out.sex).toBe(expected);
|
||||
expect(out.age).toBe(25);
|
||||
expect(out.level).toBe(7);
|
||||
}
|
||||
});
|
||||
|
||||
it('decodes the avatar URL with the "640" size suffix appended', async () => {
|
||||
const avatarBytes = protobuf_encode<AvatarInfo>({ url: 'https://q.qlogo.cn/abc/' });
|
||||
const sender = makeSender({
|
||||
body: {
|
||||
uin: 10001, uid: 'u',
|
||||
properties: {
|
||||
bytesProperties: [{ code: 101, value: avatarBytes }],
|
||||
numberProperties: [],
|
||||
},
|
||||
} as any,
|
||||
});
|
||||
const out = await FetchUserProfile.invoke(sender, { uin: 10001 });
|
||||
expect(out.avatar).toBe('https://q.qlogo.cn/abc/640');
|
||||
});
|
||||
|
||||
it('defaults uin to the requested value when the server omits its echo', async () => {
|
||||
const sender = makeSender({ body: { uid: 'u' } as any });
|
||||
const out = await FetchUserProfile.invoke(sender, { uin: 99999 });
|
||||
expect(out.uin).toBe(99999);
|
||||
});
|
||||
|
||||
it('throws when body is entirely missing from the envelope', async () => {
|
||||
const sender = makeSender({});
|
||||
await expect(FetchUserProfile.invoke(sender, { uin: 1 }))
|
||||
.rejects.toThrow('user info response body missing');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,40 +1,12 @@
|
||||
// ContactsApi — friend / group / member roster + user-profile +
|
||||
// group-request-list + download-rkey OIDB calls.
|
||||
//
|
||||
// All implementations inlined from the previous `bridge-contacts.ts`
|
||||
// (which gets removed alongside the rest of the actions/* facade
|
||||
// shim in commit 13). The single non-trivial piece carried over is
|
||||
// the per-group inflight + TTL cache for `fetchGroupMemberList`:
|
||||
// without it a busy OneBot client (e.g. MaiBot calling
|
||||
// `get_group_member_info` once per inbound message) would trigger
|
||||
// one OIDB 0xfe7_3 per chat message, sustained >1k/h, which trips
|
||||
// Tencent risk-control and gets the account banned for 7 days.
|
||||
// ContactsApi — facade over the 6 contacts-related OIDB cmds (friend
|
||||
// roster / group roster / member roster / user profile / group request
|
||||
// list / download rkeys). Single-shot cmds forward straight to their
|
||||
// namespace; pagination and the per-group cache + inflight coalescing
|
||||
// for fetchGroupMemberList live here because they need cross-call
|
||||
// state.
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type {
|
||||
OidbBase,
|
||||
OidbSvcTrpcTcp0x10C0Response,
|
||||
OidbSvcTrpcTcp0xFD4_1Response,
|
||||
OidbSvcTrpcTcp0xFE5_2Response,
|
||||
OidbSvcTrpcTcp0xFE7_3Response,
|
||||
} from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
AvatarInfo,
|
||||
OidbFriendListRequest,
|
||||
OidbGroupListRequest,
|
||||
OidbGroupMemberListRequest,
|
||||
OidbGroupRequestList,
|
||||
OidbUserInfoRequest,
|
||||
OidbUserInfoResponse,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type {
|
||||
NTV2RichMediaReq,
|
||||
NTV2RichMediaResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/media';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { DownloadRKeyInfo } from '../bridge';
|
||||
import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type {
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
@@ -42,6 +14,12 @@ import type {
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
} from '@snowluma/bridge/qq-info';
|
||||
import { FetchFriendListPage } from '@snowluma/bridge/oidb-services/contacts/fetch-friend-list-page';
|
||||
import { FetchGroupList } from '@snowluma/bridge/oidb-services/contacts/fetch-group-list';
|
||||
import { FetchGroupMemberListPage } from '@snowluma/bridge/oidb-services/contacts/fetch-group-member-list-page';
|
||||
import { FetchUserProfile } from '@snowluma/bridge/oidb-services/contacts/fetch-user-profile';
|
||||
import { FetchGroupRequests } from '@snowluma/bridge/oidb-services/contacts/fetch-group-requests';
|
||||
import { FetchDownloadRkeys } from '@snowluma/bridge/oidb-services/contacts/fetch-download-rkeys';
|
||||
|
||||
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
|
||||
|
||||
@@ -64,24 +42,17 @@ export function permissionToRole(permission: number): string {
|
||||
}
|
||||
}
|
||||
|
||||
// `runOidb` and the proto-defs helpers take `Bridge` (deep dependency
|
||||
// inside the highway / sendRawPacket plumbing). At runtime `ctx` IS
|
||||
// the Bridge that constructed this Api, so narrowing back via
|
||||
// `ctx as Bridge` is safe — see the same pattern in `MessageApi`
|
||||
// where buildSendElems also expects a Bridge.
|
||||
function asBridge(ctx: BridgeContext): Bridge {
|
||||
return ctx as unknown as Bridge;
|
||||
}
|
||||
|
||||
const MEMBER_LIST_TTL_MS = 60_000;
|
||||
|
||||
export class ContactsApi {
|
||||
/**
|
||||
* Per-group inflight + last-fetch cache for `fetchGroupMemberList`.
|
||||
* Keyed by groupId, lives for the lifetime of the Bridge (so the
|
||||
* cache resets per account, as you'd expect for multi-account
|
||||
* runtimes — `BridgeManager` builds one Bridge per uin and each
|
||||
* gets its own ContactsApi).
|
||||
* Keyed by groupId, lives for the lifetime of the Bridge.
|
||||
*
|
||||
* Without this, a busy OneBot client (e.g. MaiBot calling
|
||||
* `get_group_member_info` once per inbound message) triggers one
|
||||
* OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips
|
||||
* Tencent risk-control and gets the account banned for 7 days.
|
||||
*/
|
||||
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
|
||||
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
|
||||
@@ -89,43 +60,20 @@ export class ContactsApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const friends: FriendInfo[] = [];
|
||||
let nextUin: number | null = null;
|
||||
|
||||
do {
|
||||
const body: any = {
|
||||
friendCount: 300,
|
||||
field4: 0,
|
||||
field6: 1,
|
||||
field7: 0x7FFFFFFF,
|
||||
body: [
|
||||
{ type: 1, number: { numbers: [103, 102, 20002, 27394] } },
|
||||
{ type: 4, number: { numbers: [100, 101, 102] } },
|
||||
],
|
||||
field10002: [13578, 13579, 13573, 13572, 13568],
|
||||
field10003: 4051,
|
||||
};
|
||||
if (nextUin !== null) {
|
||||
body.nextUin = { uin: nextUin };
|
||||
const resp = await FetchFriendListPage.invoke(this.ctx, { nextUin });
|
||||
for (const raw of resp.friends ?? []) {
|
||||
const props = buildFriendProperties(raw);
|
||||
friends.push({
|
||||
uin: raw.uin ?? 0,
|
||||
uid: raw.uid ?? '',
|
||||
nickname: props.get(20002) ?? String(raw.uin ?? 0),
|
||||
remark: props.get(103) ?? '',
|
||||
});
|
||||
}
|
||||
const env = makeOidbEnvelope<OidbFriendListRequest>(0xFD4, 1, body);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfd4_1', protobuf_encode<OidbBase<OidbFriendListRequest>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFD4_1Response>>(respBytes).body;
|
||||
|
||||
if (resp?.friends) {
|
||||
for (const raw of resp.friends) {
|
||||
const props = buildFriendProperties(raw);
|
||||
friends.push({
|
||||
uin: raw.uin ?? 0,
|
||||
uid: raw.uid ?? '',
|
||||
nickname: props.get(20002) ?? String(raw.uin ?? 0),
|
||||
remark: props.get(103) ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
nextUin = resp?.next?.uin ?? null;
|
||||
nextUin = resp.next?.uin ?? null;
|
||||
if (nextUin === 0) nextUin = null;
|
||||
} while (nextUin !== null);
|
||||
|
||||
@@ -134,50 +82,17 @@ export class ContactsApi {
|
||||
}
|
||||
|
||||
async fetchGroupList(): Promise<QQGroupInfo[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
// The config flags ask QQ which per-group fields to include in
|
||||
// the response. Asking for everything looks innocent on small
|
||||
// accounts but on ~200+ groups it makes the QQ NT process write
|
||||
// a payload large enough to blow the named-pipe write buffer —
|
||||
// we then read EPIPE and the whole session dies. See issue #42.
|
||||
// Keep `config1.*` mostly on but turn off the costly groups of
|
||||
// bools that never map back to a decoded field.
|
||||
const allTrue = true;
|
||||
const body = {
|
||||
config: {
|
||||
config1: {
|
||||
groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue,
|
||||
groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue,
|
||||
field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue,
|
||||
field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue,
|
||||
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
|
||||
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
|
||||
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
|
||||
field32: allTrue, field5001: allTrue, field5002: false, field5003: false,
|
||||
},
|
||||
config2: {
|
||||
field1: false, field2: false, field3: false, field4: false,
|
||||
field5: false, field6: false, field7: false, field8: false,
|
||||
},
|
||||
config3: { field5: allTrue, field6: allTrue },
|
||||
},
|
||||
};
|
||||
const env = makeOidbEnvelope<OidbGroupListRequest>(0xFE5, 2, body, true);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe5_2', protobuf_encode<OidbBase<OidbGroupListRequest>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>(respBytes).body;
|
||||
|
||||
const resp = await FetchGroupList.invoke(this.ctx);
|
||||
const groups: QQGroupInfo[] = [];
|
||||
if (resp?.groups) {
|
||||
for (const raw of resp.groups) {
|
||||
groups.push({
|
||||
groupId: raw.groupUin ?? 0,
|
||||
groupName: raw.info?.groupName ?? '',
|
||||
remark: raw.customInfo?.remark ?? '',
|
||||
memberCount: raw.info?.memberCount ?? 0,
|
||||
memberMax: raw.info?.memberMax ?? 0,
|
||||
members: new Map(),
|
||||
});
|
||||
}
|
||||
for (const raw of resp.groups ?? []) {
|
||||
groups.push({
|
||||
groupId: raw.groupUin ?? 0,
|
||||
groupName: raw.info?.groupName ?? '',
|
||||
remark: raw.customInfo?.remark ?? '',
|
||||
memberCount: raw.info?.memberCount ?? 0,
|
||||
memberMax: raw.info?.memberMax ?? 0,
|
||||
members: new Map(),
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroups(groups);
|
||||
return groups;
|
||||
@@ -187,9 +102,6 @@ export class ContactsApi {
|
||||
groupId: number,
|
||||
options: { force?: boolean } = {},
|
||||
): Promise<GroupMemberInfo[]> {
|
||||
// Coalesce in-flight calls + serve a 60s-cached result. Without
|
||||
// this, a busy OneBot client gets the bot 7-day banned within
|
||||
// hours via Tencent risk-control.
|
||||
const now = Date.now();
|
||||
const last = this.memberListLastFetch.get(groupId);
|
||||
if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) {
|
||||
@@ -211,45 +123,25 @@ export class ContactsApi {
|
||||
}
|
||||
|
||||
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const members: GroupMemberInfo[] = [];
|
||||
let token = '';
|
||||
|
||||
do {
|
||||
const body: any = {
|
||||
groupUin: groupId,
|
||||
field2: 5,
|
||||
field3: 2,
|
||||
body: {
|
||||
memberName: true, memberCard: true, level: true, field13: true,
|
||||
field16: true, specialTitle: true, field18: true, field20: true,
|
||||
field21: true, joinTimestamp: true, lastMsgTimestamp: true,
|
||||
shutUpTimestamp: true, field103: true, field104: true, field105: true,
|
||||
field106: true, permission: true, field200: true, field201: true,
|
||||
},
|
||||
};
|
||||
if (token) body.token = token;
|
||||
const env = makeOidbEnvelope<OidbGroupMemberListRequest>(0xFE7, 3, body);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe7_3', protobuf_encode<OidbBase<OidbGroupMemberListRequest>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0xFE7_3Response>>(respBytes).body;
|
||||
|
||||
if (resp?.members) {
|
||||
for (const raw of resp.members) {
|
||||
members.push({
|
||||
uin: raw.uin?.uin ?? 0,
|
||||
uid: raw.uin?.uid ?? '',
|
||||
nickname: raw.memberName ?? '',
|
||||
card: raw.memberCard?.memberCard ?? '',
|
||||
role: permissionToRole(raw.permission ?? 0),
|
||||
level: raw.level?.level ?? 0,
|
||||
title: raw.specialTitle ?? '',
|
||||
joinTime: raw.joinTimestamp ?? 0,
|
||||
lastSentTime: raw.lastMsgTimestamp ?? 0,
|
||||
shutUpTime: raw.shutUpTimestamp ?? 0,
|
||||
});
|
||||
}
|
||||
const resp = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
|
||||
for (const raw of resp.members ?? []) {
|
||||
members.push({
|
||||
uin: raw.uin?.uin ?? 0,
|
||||
uid: raw.uin?.uid ?? '',
|
||||
nickname: raw.memberName ?? '',
|
||||
card: raw.memberCard?.memberCard ?? '',
|
||||
role: permissionToRole(raw.permission ?? 0),
|
||||
level: raw.level?.level ?? 0,
|
||||
title: raw.specialTitle ?? '',
|
||||
joinTime: raw.joinTimestamp ?? 0,
|
||||
lastSentTime: raw.lastMsgTimestamp ?? 0,
|
||||
shutUpTime: raw.shutUpTimestamp ?? 0,
|
||||
});
|
||||
}
|
||||
token = resp?.token ?? '';
|
||||
token = resp.token ?? '';
|
||||
} while (token);
|
||||
|
||||
this.ctx.identity.rememberGroupMembers(groupId, members);
|
||||
@@ -257,76 +149,15 @@ export class ContactsApi {
|
||||
}
|
||||
|
||||
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
|
||||
// Only `uin` and `keys` — see OidbUserInfoRequestSchema for why
|
||||
// sending field 2 makes the server reject the request.
|
||||
const body = {
|
||||
uin,
|
||||
keys: keys.map(k => ({ key: k })),
|
||||
};
|
||||
// Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the
|
||||
// name is historical, the wire semantic is "this is the UIN-form
|
||||
// variant of the call"). Without it newer QQ NT versions take the
|
||||
// UID-form validation path, find neither uid nor openid in the
|
||||
// body and bounce the request with
|
||||
// `[oidb] one of uid/openid is invaild`. Matches Lagrange.Core's
|
||||
// FetchStrangerByUin (Reserved = 1).
|
||||
const env = makeOidbEnvelope<OidbUserInfoRequest>(0xFE1, 2, body, true);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode<OidbBase<OidbUserInfoRequest>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbUserInfoResponse>>(respBytes).body;
|
||||
|
||||
if (!resp?.body) throw new Error('user info response body missing');
|
||||
|
||||
const info: UserProfileInfo = {
|
||||
uin: resp.body.uin ?? uin,
|
||||
uid: resp.body.uid ?? '',
|
||||
nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
|
||||
};
|
||||
|
||||
if (resp.body.properties) {
|
||||
const bytesMap = new Map<number, Uint8Array>();
|
||||
const numMap = new Map<number, number>();
|
||||
for (const bp of resp.body.properties.bytesProperties ?? []) {
|
||||
bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0));
|
||||
}
|
||||
for (const np of resp.body.properties.numberProperties ?? []) {
|
||||
numMap.set(np.number1 ?? 0, np.number2 ?? 0);
|
||||
}
|
||||
const getString = (code: number) => {
|
||||
const b = bytesMap.get(code);
|
||||
return b ? Buffer.from(b).toString('utf8') : '';
|
||||
};
|
||||
info.nickname = getString(20002);
|
||||
info.remark = getString(103);
|
||||
info.qid = getString(27394);
|
||||
info.sign = getString(102);
|
||||
|
||||
const avatarBytes = bytesMap.get(101);
|
||||
if (avatarBytes) {
|
||||
const av = protobuf_decode<AvatarInfo>(avatarBytes);
|
||||
if (av?.url) info.avatar = av.url + '640';
|
||||
}
|
||||
const sexNum = numMap.get(20009) ?? 0;
|
||||
info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown';
|
||||
info.age = numMap.get(20037) ?? 0;
|
||||
info.level = numMap.get(105) ?? 0;
|
||||
}
|
||||
|
||||
const info = await FetchUserProfile.invoke(this.ctx, { uin });
|
||||
this.ctx.identity.rememberUserProfile(info);
|
||||
return info;
|
||||
}
|
||||
|
||||
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const subCmd = filtered ? 2 : 1;
|
||||
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
|
||||
const env = makeOidbEnvelope<OidbGroupRequestList>(0x10C0, subCmd, { count: 20, field2: 0 });
|
||||
const respBytes = await runOidb(bridge, cmd, protobuf_encode<OidbBase<OidbGroupRequestList>>(env));
|
||||
const resp = protobuf_decode<OidbBase<OidbSvcTrpcTcp0x10C0Response>>(respBytes).body;
|
||||
|
||||
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered });
|
||||
const requests: GroupRequestInfo[] = [];
|
||||
for (const raw of resp?.requests ?? []) {
|
||||
for (const raw of resp.requests ?? []) {
|
||||
requests.push({
|
||||
groupId: raw.group?.groupUin ?? 0,
|
||||
groupName: raw.group?.groupName ?? '',
|
||||
@@ -351,31 +182,10 @@ export class ContactsApi {
|
||||
}
|
||||
|
||||
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const PRIVATE_IMAGE = 10;
|
||||
const GROUP_IMAGE = 20;
|
||||
const FALLBACK_IMAGE = 2;
|
||||
|
||||
const body = {
|
||||
reqHead: {
|
||||
common: { requestId: 1, command: 202 },
|
||||
scene: { requestType: 2, businessType: 1, sceneType: 0 },
|
||||
client: { agentType: 2 },
|
||||
},
|
||||
downloadRkey: {
|
||||
types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE],
|
||||
},
|
||||
};
|
||||
const env = makeOidbEnvelope<NTV2RichMediaReq>(0x9067, 202, body, true);
|
||||
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9067_202', protobuf_encode<OidbBase<NTV2RichMediaReq>>(env));
|
||||
const resp = protobuf_decode<OidbBase<NTV2RichMediaResp>>(respBytes).body;
|
||||
|
||||
if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
|
||||
throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
|
||||
}
|
||||
const resp = await FetchDownloadRkeys.invoke(this.ctx);
|
||||
|
||||
const result: DownloadRKeyInfo[] = [];
|
||||
for (const entry of resp?.downloadRkey?.rkeys ?? []) {
|
||||
for (const entry of resp.downloadRkey?.rkeys ?? []) {
|
||||
const rkey = entry.rkey ?? '';
|
||||
const type = entry.type ?? 0;
|
||||
if (rkey && type) {
|
||||
|
||||
Reference in new issue
Block a user