From 6bf53890dcbf5f27c6bce5d50fa0fe4f8389ea11 Mon Sep 17 00:00:00 2001
From: DrSmoothl <1787882683@qq.com>
Date: Wed, 20 May 2026 22:27:32 +0800
Subject: [PATCH] refactor(api): move contacts methods to ContactsApi (#6
commit 2/13)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Second of 13 commits decomposing Bridge. Moves the six "fetch the
roster / a profile / outstanding requests / download rkeys" methods
off Bridge and onto a new `apis.contacts.*`.
Methods moved
-------------
* fetchFriendList — OIDB 0xfd4_1 + identity.rememberFriends
* fetchGroupList — OIDB 0xfe5_2 + identity.rememberGroups
* fetchGroupMemberList — OIDB 0xfe7_3 + identity.rememberGroupMembers
(includes the 60s TTL + per-group inflight
coalesce cache that prevents Tencent
risk-control from triggering)
* fetchUserProfile — OIDB 0xfe1_2 + identity.rememberUserProfile
* fetchGroupRequests — OIDB 0x10c0_{1,2}
* fetchDownloadRKeys — OIDB 0x9067_202
Cache fields moved
------------------
The two member-list throttle maps (`memberListInflight_`,
`memberListLastFetch_`) move from Bridge to `ContactsApi` as private
fields. Same TTL, same semantics — just owned by the Api class that
exposes the method.
Constructor ordering
--------------------
`buildApiHub(this)` now runs BEFORE `identity.setFetcher(...)` in the
Bridge constructor because the `fetchProfile` / `fetchGroupMemberList`
callbacks installed there reach into `this.apis.contacts.*`. With
eager construction this is safe; the alternative (pass a thunk that
forwards once apis is built) was strictly worse for readability.
bridge-contacts.ts removed
--------------------------
The file existed solely as the previous module-function delegate
target; ContactsApi inlines every function body so there's nothing
left to keep.
Caller-site updates
-------------------
* `bridge/actions/friend.ts` — `bridge.fetchFriendList()` →
`bridge.apis.contacts.fetchFriendList()`.
* `onebot/manager.ts`, `onebot/instance-rkey.ts`,
`onebot/modules/contact-actions.ts`, `modules/request-actions.ts`,
`actions/extended.ts` — same shape rewrite (6 method names).
Test plumbing
-------------
* `tests/actions/_helpers.ts` — `mockApiHub()` grows a `contacts`
field built by `mockContactsApi()`.
* `tests/bridge-member-identity.test.ts::RefreshingBridge` — was
`override async fetchGroupMemberList()`. After the move the method
lives on `this.apis.contacts`, not `this`. Switched to patching the
method on the constructed ContactsApi instance directly.
* `tests/actions/friend.test.ts` — `bridge.fetchFriendList` →
`bridge.apis.contacts.fetchFriendList`; the "refresh throws" branch
overrides via `bridge.apis.contacts.fetchFriendList = vi.fn(…)`.
* `tests/onebot/contact-actions.test.ts`, `extended-actions.test.ts`,
`request-actions.test.ts` — local `fakeBridge` helpers gained an
auto-promotion shim that rewrites flat method stubs (the pre-#6
test API) into the new `apis..method` shape. Keeps existing
test setup readable while the production code uses the new path.
Tests: 587/587 pass (same baseline; pre-existing network-manager
native-addon failure unchanged).
---
packages/core/src/bridge/actions/friend.ts | 2 +-
packages/core/src/bridge/apis/contacts.ts | 392 ++++++++++++++++++
packages/core/src/bridge/apis/index.ts | 6 +-
packages/core/src/bridge/bridge-contacts.ts | 354 ----------------
packages/core/src/bridge/bridge-interface.ts | 15 +-
packages/core/src/bridge/bridge.ts | 74 +---
packages/core/src/onebot/actions/extended.ts | 2 +-
packages/core/src/onebot/instance-rkey.ts | 4 +-
packages/core/src/onebot/manager.ts | 8 +-
.../src/onebot/modules/contact-actions.ts | 16 +-
.../src/onebot/modules/request-actions.ts | 2 +-
packages/core/tests/actions/_helpers.ts | 22 +
packages/core/tests/actions/friend.test.ts | 10 +-
.../core/tests/bridge-member-identity.test.ts | 24 +-
.../core/tests/onebot/contact-actions.test.ts | 38 +-
.../tests/onebot/extended-actions.test.ts | 23 +-
.../core/tests/onebot/request-actions.test.ts | 20 +-
17 files changed, 547 insertions(+), 465 deletions(-)
create mode 100644 packages/core/src/bridge/apis/contacts.ts
delete mode 100644 packages/core/src/bridge/bridge-contacts.ts
diff --git a/packages/core/src/bridge/actions/friend.ts b/packages/core/src/bridge/actions/friend.ts
index 722e300f..60f483c6 100644
--- a/packages/core/src/bridge/actions/friend.ts
+++ b/packages/core/src/bridge/actions/friend.ts
@@ -40,7 +40,7 @@ export async function deleteFriend(bridge: Bridge, userId: number, block = false
// Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
// shouldn't make the delete itself look failed.
- try { await bridge.fetchFriendList(); } catch { /* ignore */ }
+ try { await bridge.apis.contacts.fetchFriendList(); } catch { /* ignore */ }
}
export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise {
diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts
new file mode 100644
index 00000000..412388fa
--- /dev/null
+++ b/packages/core/src/bridge/apis/contacts.ts
@@ -0,0 +1,392 @@
+// 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.
+
+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 '../bridge-oidb';
+import type { Bridge } from '../bridge';
+import type {
+ FriendInfo,
+ GroupMemberInfo,
+ GroupRequestInfo,
+ QQGroupInfo,
+ UserProfileInfo,
+} from '../qq-info';
+
+// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
+
+export function buildFriendProperties(raw: any): Map {
+ const props = new Map();
+ for (const additional of raw.additional ?? []) {
+ if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
+ for (const property of additional.layer1.properties ?? []) {
+ props.set(property.code ?? 0, property.value ?? '');
+ }
+ }
+ return props;
+}
+
+export function permissionToRole(permission: number): string {
+ switch (permission) {
+ case 1: return 'owner';
+ case 2: return 'admin';
+ default: return 'member';
+ }
+}
+
+// `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).
+ */
+ private memberListInflight = new Map>();
+ private memberListLastFetch = new Map();
+
+ constructor(private readonly ctx: BridgeContext) {}
+
+ async fetchFriendList(): Promise {
+ 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 env = makeOidbEnvelope(0xFD4, 1, body);
+ const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfd4_1', protobuf_encode>(env));
+ const resp = protobuf_decode>(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;
+ if (nextUin === 0) nextUin = null;
+ } while (nextUin !== null);
+
+ this.ctx.identity.rememberFriends(friends);
+ return friends;
+ }
+
+ async fetchGroupList(): Promise {
+ 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(0xFE5, 2, body, true);
+ const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe5_2', protobuf_encode>(env));
+ const resp = protobuf_decode>(respBytes).body;
+
+ 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(),
+ });
+ }
+ }
+ this.ctx.identity.rememberGroups(groups);
+ return groups;
+ }
+
+ async fetchGroupMemberList(
+ groupId: number,
+ options: { force?: boolean } = {},
+ ): Promise {
+ // 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) {
+ return last.data;
+ }
+ const inflight = this.memberListInflight.get(groupId);
+ if (inflight) return inflight;
+ const task = (async () => {
+ try {
+ const data = await this.fetchGroupMemberListUncached(groupId);
+ this.memberListLastFetch.set(groupId, { at: Date.now(), data });
+ return data;
+ } finally {
+ this.memberListInflight.delete(groupId);
+ }
+ })();
+ this.memberListInflight.set(groupId, task);
+ return task;
+ }
+
+ private async fetchGroupMemberListUncached(groupId: number): Promise {
+ 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(0xFE7, 3, body);
+ const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe7_3', protobuf_encode>(env));
+ const resp = protobuf_decode>(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,
+ });
+ }
+ }
+ token = resp?.token ?? '';
+ } while (token);
+
+ this.ctx.identity.rememberGroupMembers(groupId, members);
+ return members;
+ }
+
+ async fetchUserProfile(uin: number): Promise {
+ 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(0xFE1, 2, body, true);
+ const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode>(env));
+ const resp = protobuf_decode>(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: '',
+ };
+
+ if (resp.body.properties) {
+ const bytesMap = new Map();
+ const numMap = new Map();
+ 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(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;
+ }
+
+ this.ctx.identity.rememberUserProfile(info);
+ return info;
+ }
+
+ async fetchGroupRequests(filtered = false): Promise {
+ const bridge = asBridge(this.ctx);
+ const subCmd = filtered ? 2 : 1;
+ const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
+ const env = makeOidbEnvelope(0x10C0, subCmd, { count: 20, field2: 0 });
+ const respBytes = await runOidb(bridge, cmd, protobuf_encode>(env));
+ const resp = protobuf_decode>(respBytes).body;
+
+ const requests: GroupRequestInfo[] = [];
+ for (const raw of resp?.requests ?? []) {
+ requests.push({
+ groupId: raw.group?.groupUin ?? 0,
+ groupName: raw.group?.groupName ?? '',
+ targetUid: raw.target?.uid ?? '',
+ targetUin: 0,
+ targetName: raw.target?.name ?? '',
+ invitorUid: raw.invitor?.uid ?? '',
+ invitorUin: 0,
+ invitorName: raw.invitor?.name ?? '',
+ operatorUid: raw.operatorUser?.uid ?? '',
+ operatorUin: 0,
+ operatorName: raw.operatorUser?.name ?? '',
+ sequence: Number(raw.sequence ?? 0),
+ state: raw.state ?? 0,
+ eventType: raw.eventType ?? 0,
+ comment: raw.comment ?? '',
+ filtered,
+ });
+ }
+ this.ctx.identity.rememberGroupRequests(requests);
+ return requests;
+ }
+
+ async fetchDownloadRKeys(): Promise {
+ 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(0x9067, 202, body, true);
+ const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9067_202', protobuf_encode>(env));
+ const resp = protobuf_decode>(respBytes).body;
+
+ if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
+ throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
+ }
+
+ const result: DownloadRKeyInfo[] = [];
+ for (const entry of resp?.downloadRkey?.rkeys ?? []) {
+ const rkey = entry.rkey ?? '';
+ const type = entry.type ?? 0;
+ if (rkey && type) {
+ result.push({
+ rkey,
+ ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
+ storeId: entry.storeId ?? 0,
+ createTime: entry.rkeyCreateTime ?? 0,
+ type,
+ });
+ }
+ }
+ return result;
+ }
+}
diff --git a/packages/core/src/bridge/apis/index.ts b/packages/core/src/bridge/apis/index.ts
index 4a4b1505..2f383ae6 100644
--- a/packages/core/src/bridge/apis/index.ts
+++ b/packages/core/src/bridge/apis/index.ts
@@ -21,13 +21,15 @@
// shrinks as each commit lands.
import type { BridgeContext } from '../bridge-context';
+import { ContactsApi } from './contacts';
import { MessageApi } from './message';
export interface ApiHub {
/** Send/recall/markRead operations across c2c + group + c2c-file. */
readonly message: MessageApi;
+ /** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
+ readonly contacts: ContactsApi;
// Pending — added as later commits land:
- // readonly contacts: ContactsApi;
// readonly groupAdmin: GroupAdminApi;
// readonly groupFile: GroupFileApi;
// readonly groupAlbum: GroupAlbumApi;
@@ -51,10 +53,12 @@ export interface ApiHub {
export function buildApiHub(ctx: BridgeContext): ApiHub {
return {
message: new MessageApi(ctx),
+ contacts: new ContactsApi(ctx),
};
}
// Re-export the Api classes themselves so callers can write
// `import type { MessageApi } from '@snowluma/core/.../apis'` for
// signature use. Concrete instances always come from `bridge.apis.*`.
+export { ContactsApi } from './contacts';
export { MessageApi } from './message';
diff --git a/packages/core/src/bridge/bridge-contacts.ts b/packages/core/src/bridge/bridge-contacts.ts
deleted file mode 100644
index 3c3a4149..00000000
--- a/packages/core/src/bridge/bridge-contacts.ts
+++ /dev/null
@@ -1,354 +0,0 @@
-import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
-import type { Bridge, DownloadRKeyInfo } from './bridge';
-import { makeOidbEnvelope, runOidb } from './bridge-oidb';
-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 { FriendInfo, GroupMemberInfo, GroupRequestInfo, QQGroupInfo, UserProfileInfo } from './qq-info';
-
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-export function buildFriendProperties(raw: any): Map {
- const props = new Map();
- for (const additional of raw.additional ?? []) {
- if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
- for (const property of additional.layer1.properties ?? []) {
- props.set(property.code ?? 0, property.value ?? '');
- }
- }
- return props;
-}
-
-export function permissionToRole(permission: number): string {
- switch (permission) {
- case 1: return 'owner';
- case 2: return 'admin';
- default: return 'member';
- }
-}
-
-// ---------------------------------------------------------------------------
-// Friend list
-// ---------------------------------------------------------------------------
-
-export async function fetchFriendList(bridge: Bridge): Promise {
- 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 env = makeOidbEnvelope(0xFD4, 1, body);
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfd4_1', protobuf_encode>(env));
- const resp = protobuf_decode>(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;
- if (nextUin === 0) nextUin = null;
- } while (nextUin !== null);
-
- bridge.identity.rememberFriends(friends);
- return friends;
-}
-
-// ---------------------------------------------------------------------------
-// Group list
-// ---------------------------------------------------------------------------
-
-export async function fetchGroupList(bridge: Bridge): Promise {
- // 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.
- //
- // The user-verified safe combination: keep `config1.*` mostly on
- // (the response decoder pulls groupOwner / memberMax / memberCount /
- // groupName / description / question / announcement from this
- // group), but turn off the costly groups of bools that never map
- // back to a decoded field:
- // - config1.field5002, field5003 (expansive 5xxx-range descriptors)
- // - all of config2 (auxiliary per-group blob the decoder ignores)
- 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(0xFE5, 2, body, true);
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe5_2', protobuf_encode>(env));
- const resp = protobuf_decode>(respBytes).body;
-
- 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(),
- });
- }
- }
- bridge.identity.rememberGroups(groups);
- return groups;
-}
-
-// ---------------------------------------------------------------------------
-// Group member list
-// ---------------------------------------------------------------------------
-
-export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Promise {
- 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(0xFE7, 3, body);
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe7_3', protobuf_encode>(env));
- const resp = protobuf_decode>(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,
- });
- }
- }
-
- token = resp?.token ?? '';
- } while (token);
-
- bridge.identity.rememberGroupMembers(groupId, members);
- return members;
-}
-
-// ---------------------------------------------------------------------------
-// User profile
-// ---------------------------------------------------------------------------
-
-export async function fetchUserProfile(bridge: Bridge, uin: number): Promise {
- 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(0xFE1, 2, body, true);
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode>(env));
- const resp = protobuf_decode>(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: '',
- };
-
- if (resp.body.properties) {
- const bytesMap = new Map();
- const numMap = new Map();
- 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(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;
- }
-
- bridge.identity.rememberUserProfile(info);
- return info;
-}
-
-// ---------------------------------------------------------------------------
-// Group requests
-// ---------------------------------------------------------------------------
-
-export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise {
- const subCmd = filtered ? 2 : 1;
- const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
- const env = makeOidbEnvelope(0x10C0, subCmd, { count: 20, field2: 0 });
- const respBytes = await runOidb(bridge, cmd, protobuf_encode>(env));
- const resp = protobuf_decode>(respBytes).body;
-
- const requests: GroupRequestInfo[] = [];
- for (const raw of resp?.requests ?? []) {
- requests.push({
- groupId: raw.group?.groupUin ?? 0,
- groupName: raw.group?.groupName ?? '',
- targetUid: raw.target?.uid ?? '',
- targetUin: 0,
- targetName: raw.target?.name ?? '',
- invitorUid: raw.invitor?.uid ?? '',
- invitorUin: 0,
- invitorName: raw.invitor?.name ?? '',
- operatorUid: raw.operatorUser?.uid ?? '',
- operatorUin: 0,
- operatorName: raw.operatorUser?.name ?? '',
- sequence: Number(raw.sequence ?? 0),
- state: raw.state ?? 0,
- eventType: raw.eventType ?? 0,
- comment: raw.comment ?? '',
- filtered,
- });
- }
- bridge.identity.rememberGroupRequests(requests);
- return requests;
-}
-
-// ---------------------------------------------------------------------------
-// Download RKeys
-// ---------------------------------------------------------------------------
-
-export async function fetchDownloadRKeys(bridge: Bridge): Promise {
- 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(0x9067, 202, body, true);
- const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9067_202', protobuf_encode>(env));
- const resp = protobuf_decode>(respBytes).body;
-
- if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
- throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
- }
-
- const result: DownloadRKeyInfo[] = [];
- for (const entry of resp?.downloadRkey?.rkeys ?? []) {
- const rkey = entry.rkey ?? '';
- const type = entry.type ?? 0;
- if (rkey && type) {
- result.push({
- rkey,
- ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
- storeId: entry.storeId ?? 0,
- createTime: entry.rkeyCreateTime ?? 0,
- type,
- });
- }
- }
- return result;
-}
diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts
index 9ae7afc3..66e4d462 100644
--- a/packages/core/src/bridge/bridge-interface.ts
+++ b/packages/core/src/bridge/bridge-interface.ts
@@ -10,13 +10,6 @@ import type {
import type { BridgeEventBus } from './event-bus';
import type { ForwardNodePayload } from './events';
import type { IdentityService } from './identity-service';
-import type {
- FriendInfo,
- GroupMemberInfo,
- GroupRequestInfo,
- QQGroupInfo,
- UserProfileInfo,
-} from './qq-info';
import type { WebHonorType } from './web/group-honor';
export interface BridgeInterface {
@@ -49,13 +42,7 @@ export interface BridgeInterface {
// Moved to `apis.message.{sendGroup, sendPrivate, sendC2cFile,
// recallGroup, recallPrivate, markGroupRead, markPrivateRead}`.
- // ─── Fetch (contacts / profile / system) ───
- fetchFriendList(): Promise;
- fetchGroupList(): Promise;
- fetchGroupMemberList(groupId: number, options?: { force?: boolean }): Promise;
- fetchUserProfile(uin: number): Promise;
- fetchGroupRequests(filtered?: boolean): Promise;
- fetchDownloadRKeys(): Promise;
+ // ─── Fetch (contacts / profile / system) — moved to apis.contacts ───
// ─── Group admin ───
muteGroupMember(groupId: number, userId: number, duration: number): Promise;
diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts
index 8897b4ba..fe3e183d 100644
--- a/packages/core/src/bridge/bridge.ts
+++ b/packages/core/src/bridge/bridge.ts
@@ -5,7 +5,8 @@ import type { ForwardNodePayload } from './events';
import { IdentityService } from './identity-service';
import { MSG_PUSH_CMD, parseMsgPush } from './msg-push';
import { IncomingPacketPipeline, type CmdParser } from './packet-pipeline';
-import type { FriendInfo, GroupMemberInfo, GroupRequestInfo, QQGroupInfo, UserProfileInfo } from './qq-info';
+// qq-info types are no longer used directly in this file — they live
+// inside the Api classes that own those fetches (apis/contacts.ts).
import { type ApiHub, buildApiHub } from './apis';
// Delegated modules
@@ -99,14 +100,8 @@ import {
setSelfLongNick as setSelfLongNick_,
} from './actions/profile';
import type { MediaIndexNode } from './actions/shared';
-import {
- fetchDownloadRKeys as fetchDownloadRKeys_,
- fetchFriendList as fetchFriendList_,
- fetchGroupList as fetchGroupList_,
- fetchGroupMemberList as fetchGroupMemberList_,
- fetchGroupRequests as fetchGroupRequests_,
- fetchUserProfile as fetchUserProfile_,
-} from './bridge-contacts';
+// `bridge-contacts.ts` removed — its 6 functions are now methods on
+// `apis.contacts` (see `apis/contacts.ts::ContactsApi`).
import { BridgeEventBus } from './event-bus';
import {
deleteGroupNoticeByFid as deleteGroupNotice_,
@@ -190,15 +185,9 @@ export class Bridge implements BridgeInterface {
readonly apis: ApiHub;
private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
- // Throttle for fetchGroupMemberList(groupId): coalesces in-flight calls
- // and serves a fresh result for `kMemberListTtlMs` to all callers.
- // Without this, a busy OneBot client (e.g. MaiBot calling
- // get_group_member_info(no_cache=true) per inbound message) would
- // trigger one OIDB 0xfe7_3 per chat message per group; sustained rate
- // (>1k/h) is detected by Tencent risk-control and gets the account
- // banned for 7 days.
- private memberListInflight_ = new Map>();
- private memberListLastFetch_ = new Map();
+ // (fetchGroupMemberList throttle cache moved to ContactsApi — same
+ // 60s TTL + inflight coalesce semantics, just owned by the Api class
+ // that exposes the method.)
// ── Uploaded-file metadata cache ────────────────────────────────────
//
@@ -224,9 +213,15 @@ export class Bridge implements BridgeInterface {
constructor(identity: IdentityService) {
this.identity = identity;
+ // Build Api hub FIRST — `setFetcher` below installs callbacks
+ // that reach into `this.apis.contacts.*`, so the hub must exist
+ // by the time those callbacks could fire. The Bridge instance IS
+ // the BridgeContext (Bridge implements BridgeInterface which
+ // includes the BridgeContext surface).
+ this.apis = buildApiHub(this);
this.identity.setFetcher({
- fetchProfile: (uin) => this.fetchUserProfile(uin),
- fetchGroupMemberList: (gid) => this.fetchGroupMemberList(gid),
+ fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
+ fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
});
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
@@ -235,10 +230,6 @@ export class Bridge implements BridgeInterface {
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
});
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
- // Build Api hub eagerly. The Bridge instance IS the BridgeContext
- // — `this implements BridgeContext` is enforced via the
- // `BridgeInterface` declaration, which itself extends BridgeContext.
- this.apis = buildApiHub(this);
}
dispose(): void {
@@ -281,10 +272,10 @@ export class Bridge implements BridgeInterface {
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise {
if (refreshGroupList) {
- try { await this.fetchGroupList(); } catch { /* ignore */ }
+ try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.identity.findGroup(groupId)) return false;
- await this.fetchGroupMemberList(groupId, { force: forceMemberList });
+ await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
@@ -359,34 +350,9 @@ export class Bridge implements BridgeInterface {
return this.identity.resolveUid(uin, groupId);
}
- // --- Delegated: Contact / info queries ---
-
- async fetchFriendList(): Promise { return fetchFriendList_(this); }
- async fetchGroupList(): Promise { return fetchGroupList_(this); }
- async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise {
- const kMemberListTtlMs = 60_000;
- const now = Date.now();
- const last = this.memberListLastFetch_.get(groupId);
- if (!options.force && last && now - last.at < kMemberListTtlMs) {
- return last.data;
- }
- const inflight = this.memberListInflight_.get(groupId);
- if (inflight) return inflight;
- const task = (async () => {
- try {
- const data = await fetchGroupMemberList_(this, groupId);
- this.memberListLastFetch_.set(groupId, { at: Date.now(), data });
- return data;
- } finally {
- this.memberListInflight_.delete(groupId);
- }
- })();
- this.memberListInflight_.set(groupId, task);
- return task;
- }
- async fetchUserProfile(uin: number): Promise { return fetchUserProfile_(this, uin); }
- async fetchGroupRequests(filtered = false): Promise { return fetchGroupRequests_(this, filtered); }
- async fetchDownloadRKeys(): Promise { return fetchDownloadRKeys_(this); }
+ // fetchFriendList / fetchGroupList / fetchGroupMemberList /
+ // fetchUserProfile / fetchGroupRequests / fetchDownloadRKeys
+ // moved to apis.contacts (see apis/contacts.ts::ContactsApi).
// --- Delegated: Admin / action methods ---
diff --git a/packages/core/src/onebot/actions/extended.ts b/packages/core/src/onebot/actions/extended.ts
index 123fdb66..3e328801 100644
--- a/packages/core/src/onebot/actions/extended.ts
+++ b/packages/core/src/onebot/actions/extended.ts
@@ -712,7 +712,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
// OneBot dialects clients use in the wild.
const fetchFilteredGroupRequests = async () => {
try {
- return await ctx.bridge.fetchGroupRequests(true);
+ return await ctx.bridge.apis.contacts.fetchGroupRequests(true);
} catch {
return [];
}
diff --git a/packages/core/src/onebot/instance-rkey.ts b/packages/core/src/onebot/instance-rkey.ts
index 493eb2c2..c9d1ad61 100644
--- a/packages/core/src/onebot/instance-rkey.ts
+++ b/packages/core/src/onebot/instance-rkey.ts
@@ -28,7 +28,7 @@ export class RKeyCache {
private lastRefreshAttempt = 0;
warmUp(bridge: BridgeInterface, uin: string): void {
- bridge.fetchDownloadRKeys().then(
+ bridge.apis.contacts.fetchDownloadRKeys().then(
(rkeys) => {
this.updateCache(rkeys);
log.info('rkeys loaded: UIN=%s count=%d', uin, rkeys.length);
@@ -117,7 +117,7 @@ export class RKeyCache {
this.lastRefreshAttempt = now;
// Schedule async refresh
- bridge.fetchDownloadRKeys().then(
+ bridge.apis.contacts.fetchDownloadRKeys().then(
(rkeys) => this.updateCache(rkeys),
() => { /* ignore */ },
);
diff --git a/packages/core/src/onebot/manager.ts b/packages/core/src/onebot/manager.ts
index dd6f0ac6..73c09872 100644
--- a/packages/core/src/onebot/manager.ts
+++ b/packages/core/src/onebot/manager.ts
@@ -89,7 +89,7 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<
// which used to leave identity.nickname empty — see step 1b for the
// explicit fallback.
try {
- const friends = await bridge.fetchFriendList();
+ const friends = await bridge.apis.contacts.fetchFriendList();
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
for (const f of friends) {
@@ -115,7 +115,7 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<
// back in the friend list.
if (!selfResolved && selfUin > 0) {
try {
- const profile = await bridge.fetchUserProfile(selfUin);
+ const profile = await bridge.apis.contacts.fetchUserProfile(selfUin);
bridge.identity.setSelfProfile(profile);
bridge.identity.nickname = profile.nickname || uin;
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
@@ -129,7 +129,7 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<
// Step 2: Fetch group list
let groups: { groupId: number }[] = [];
try {
- groups = await bridge.fetchGroupList();
+ groups = await bridge.apis.contacts.fetchGroupList();
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
} catch (e) {
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
@@ -141,7 +141,7 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<
let failedGroupCount = 0;
for (const g of groups) {
try {
- const members = await bridge.fetchGroupMemberList(g.groupId);
+ const members = await bridge.apis.contacts.fetchGroupMemberList(g.groupId);
loadedGroupCount += 1;
loadedMemberCount += members.length;
if (VERBOSE_WARMUP) {
diff --git a/packages/core/src/onebot/modules/contact-actions.ts b/packages/core/src/onebot/modules/contact-actions.ts
index f2e00ab2..a7756c5d 100644
--- a/packages/core/src/onebot/modules/contact-actions.ts
+++ b/packages/core/src/onebot/modules/contact-actions.ts
@@ -13,7 +13,7 @@ export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nick
// turn one OneBot request into N OIDB calls, which is risky for busy clients.
async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: number): Promise {
try {
- await bridge.fetchGroupMemberList(groupId);
+ await bridge.apis.contacts.fetchGroupMemberList(groupId);
} catch {
// Use cached data.
}
@@ -21,7 +21,7 @@ async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: numbe
export async function getFriendList(bridge: BridgeInterface): Promise {
try {
- const friends = await bridge.fetchFriendList();
+ const friends = await bridge.apis.contacts.fetchFriendList();
return friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
@@ -42,7 +42,7 @@ export async function getGroupList(
): Promise {
try {
if (noCache || bridge.identity.groups.length === 0) {
- await bridge.fetchGroupList();
+ await bridge.apis.contacts.fetchGroupList();
}
} catch {
// Use cached data.
@@ -62,7 +62,7 @@ export async function getGroupInfo(
): Promise {
if (noCache || !bridge.identity.findGroup(groupId)) {
try {
- await bridge.fetchGroupList();
+ await bridge.apis.contacts.fetchGroupList();
} catch {
// Use cached data.
}
@@ -88,7 +88,7 @@ export async function getGroupMemberList(
}
try {
- const members = await bridge.fetchGroupMemberList(groupId);
+ const members = await bridge.apis.contacts.fetchGroupMemberList(groupId);
return members.map(m => formatGroupMember(groupId, m));
} catch {
return getCachedGroupMembers(bridge.identity, groupId);
@@ -146,7 +146,7 @@ export async function getStrangerInfo(
userId: number,
): Promise {
try {
- const p = await bridge.fetchUserProfile(userId);
+ const p = await bridge.apis.contacts.fetchUserProfile(userId);
return {
user_id: p.uin as any,
nickname: p.nickname as any,
@@ -167,7 +167,7 @@ export async function getStrangerInfo(
export async function getGroupSystemMessages(bridge: BridgeInterface): Promise {
try {
- const reqs = await bridge.fetchGroupRequests();
+ const reqs = await bridge.apis.contacts.fetchGroupRequests();
return reqs.map(r => ({
group_id: r.groupId,
group_name: r.groupName,
@@ -184,7 +184,7 @@ export async function getGroupSystemMessages(bridge: BridgeInterface): Promise {
try {
- const rkeys = await bridge.fetchDownloadRKeys();
+ const rkeys = await bridge.apis.contacts.fetchDownloadRKeys();
return rkeys.map(r => ({
rkey: r.rkey,
type: r.type,
diff --git a/packages/core/src/onebot/modules/request-actions.ts b/packages/core/src/onebot/modules/request-actions.ts
index 9dcdb8b9..5b437a00 100644
--- a/packages/core/src/onebot/modules/request-actions.ts
+++ b/packages/core/src/onebot/modules/request-actions.ts
@@ -15,7 +15,7 @@ export async function handleGroupAddRequest(
if (!groupId) throw new Error('invalid group_id in flag');
if (!targetUid) throw new Error('invalid request target in flag');
- const requests = await bridge.fetchGroupRequests();
+ const requests = await bridge.apis.contacts.fetchGroupRequests();
const matching = requests.find((r) => {
if (r.groupId !== groupId) return false;
if (requestType === 'add') return r.targetUid === targetUid;
diff --git a/packages/core/tests/actions/_helpers.ts b/packages/core/tests/actions/_helpers.ts
index 74b29dcd..d4b9b3f2 100644
--- a/packages/core/tests/actions/_helpers.ts
+++ b/packages/core/tests/actions/_helpers.ts
@@ -41,14 +41,36 @@ export function mockMessageApi(): MockMessageApi {
};
}
+export interface MockContactsApi {
+ fetchFriendList: ReturnType;
+ fetchGroupList: ReturnType;
+ fetchGroupMemberList: ReturnType;
+ fetchUserProfile: ReturnType;
+ fetchGroupRequests: ReturnType;
+ fetchDownloadRKeys: ReturnType;
+}
+
+export function mockContactsApi(): MockContactsApi {
+ return {
+ fetchFriendList: vi.fn(async () => []),
+ fetchGroupList: vi.fn(async () => []),
+ fetchGroupMemberList: vi.fn(async () => []),
+ fetchUserProfile: vi.fn(async () => ({ uid: 'profile-uid' })),
+ fetchGroupRequests: vi.fn(async () => []),
+ fetchDownloadRKeys: vi.fn(async () => []),
+ };
+}
+
export interface MockApiHub {
message: MockMessageApi;
+ contacts: MockContactsApi;
// additional Apis added commit-by-commit as #6 progresses
}
export function mockApiHub(overrides: Partial = {}): MockApiHub {
return {
message: overrides.message ?? mockMessageApi(),
+ contacts: overrides.contacts ?? mockContactsApi(),
};
}
diff --git a/packages/core/tests/actions/friend.test.ts b/packages/core/tests/actions/friend.test.ts
index e78c2418..23a4bd74 100644
--- a/packages/core/tests/actions/friend.test.ts
+++ b/packages/core/tests/actions/friend.test.ts
@@ -41,13 +41,15 @@ describe('actions/friend', () => {
expect(cmd).toBe('OidbSvcTrpcTcp.0x126b_0');
const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2];
expect((body as any).field1.block).toBe(true);
- expect(bridge.fetchFriendList).toHaveBeenCalled();
+ expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalled();
});
it('deleteFriend still succeeds when the friend-list refresh throws', async () => {
- const bridge = mockBridge({
- fetchFriendList: vi.fn(async () => { throw new Error('cache miss'); }),
- });
+ 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 deleteFriend swallows the error.
+ bridge.apis.contacts.fetchFriendList = vi.fn(async () => { throw new Error('cache miss'); });
await expect(friend.deleteFriend(bridge as any, 10001))
.resolves.toBeUndefined();
});
diff --git a/packages/core/tests/bridge-member-identity.test.ts b/packages/core/tests/bridge-member-identity.test.ts
index 6e62f84e..9a59a876 100644
--- a/packages/core/tests/bridge-member-identity.test.ts
+++ b/packages/core/tests/bridge-member-identity.test.ts
@@ -39,14 +39,22 @@ class RefreshingBridge extends Bridge {
constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) {
super(identity);
- }
-
- override async fetchGroupMemberList(groupId: number, options: { force?: boolean } = {}): Promise {
- this.memberFetches.push({ groupId, force: Boolean(options.force) });
- for (const member of this.refreshedMembers) {
- this.identity.updateGroupMember(groupId, member);
- }
- return this.refreshedMembers;
+ // `fetchGroupMemberList` moved from Bridge onto `apis.contacts`
+ // under the #6 refactor — patch the method on the constructed
+ // ContactsApi instance to intercept calls + record them for
+ // assertions. (Direct property assignment works because the
+ // method is just an own property on the Api instance, not on
+ // its prototype.)
+ this.apis.contacts.fetchGroupMemberList = async (
+ groupId: number,
+ options: { force?: boolean } = {},
+ ): Promise => {
+ this.memberFetches.push({ groupId, force: Boolean(options.force) });
+ for (const member of this.refreshedMembers) {
+ this.identity.updateGroupMember(groupId, member);
+ }
+ return this.refreshedMembers;
+ };
}
}
diff --git a/packages/core/tests/onebot/contact-actions.test.ts b/packages/core/tests/onebot/contact-actions.test.ts
index a9432785..6529a1d5 100644
--- a/packages/core/tests/onebot/contact-actions.test.ts
+++ b/packages/core/tests/onebot/contact-actions.test.ts
@@ -25,8 +25,28 @@ import type { OneBotInstanceContext } from '../../src/onebot/instance-context';
* fail loudly if they exercise a code path the fake hasn't been told
* about. Tests just spread the methods they care about.
*/
-function fakeBridge(overrides: Partial = {}): BridgeInterface {
- return new Proxy(overrides as BridgeInterface, {
+// `apisAutoPromote` lets tests written before #6 (which stubbed flat
+// methods like `fetchFriendList: vi.fn()` on bridge directly) keep
+// working without restructuring — the helper rewrites flat stubs into
+// the new `apis..method` shape automatically. New code can also
+// pass `apis: { contacts: { … } }` explicitly; the two merge.
+const APIS_ROUTING: Record = {
+ fetchFriendList: 'contacts', fetchGroupList: 'contacts',
+ fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
+ fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
+};
+
+function fakeBridge(overrides: Record = {}): BridgeInterface {
+ const apisSynth: Record> = {};
+ for (const [k, v] of Object.entries(overrides)) {
+ const area = APIS_ROUTING[k];
+ if (area) {
+ if (!apisSynth[area]) apisSynth[area] = {};
+ apisSynth[area][k] = v;
+ }
+ }
+ const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
+ return new Proxy(merged as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
@@ -99,7 +119,7 @@ describe('onebot/contact-actions / getFriendList', () => {
});
const out = await getFriendList(bridge);
expect(out).toEqual([{ user_id: 22222, nickname: 'alice', remark: 'best-friend' }]);
- expect(bridge.fetchFriendList).toHaveBeenCalledOnce();
+ expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalledOnce();
});
it('falls back to identity.friends on fetch failure', async () => {
@@ -117,7 +137,7 @@ describe('onebot/contact-actions / getGroupList', () => {
it('triggers fetch when the in-memory roster is empty', async () => {
const fetched = [makeGroup(100, 'Group A')];
// `groups` starts empty; the fetch callback flips it to mimic
- // bridge.fetchGroupList writing back through identity.rememberGroups.
+ // bridge.apis.contacts.fetchGroupList writing back through identity.rememberGroups.
let groups: QQGroupInfo[] = [];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => { groups = fetched; return fetched; }),
@@ -126,7 +146,7 @@ describe('onebot/contact-actions / getGroupList', () => {
}),
});
const out = await getGroupList(bridge);
- expect(bridge.fetchGroupList).toHaveBeenCalledOnce();
+ expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce();
expect(out).toEqual([{
group_id: 100, group_name: 'Group A',
member_count: 0, max_member_count: 500,
@@ -140,7 +160,7 @@ describe('onebot/contact-actions / getGroupList', () => {
identity: fakeIdentity({ groups: cached }),
});
await getGroupList(bridge);
- expect(bridge.fetchGroupList).not.toHaveBeenCalled();
+ expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled();
});
it('forces fetch when noCache=true even with a populated cache', async () => {
@@ -150,7 +170,7 @@ describe('onebot/contact-actions / getGroupList', () => {
identity: fakeIdentity({ groups: cached }),
});
await getGroupList(bridge, true);
- expect(bridge.fetchGroupList).toHaveBeenCalledOnce();
+ expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce();
});
it('serves the stale cache when the fetch path throws', async () => {
@@ -174,7 +194,7 @@ describe('onebot/contact-actions / getGroupInfo', () => {
});
const out = await getGroupInfo(bridge, 500);
expect(out).toMatchObject({ group_id: 500, group_name: 'Group E' });
- expect(bridge.fetchGroupList).not.toHaveBeenCalled();
+ expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled();
});
it('triggers fetch when the group is unknown to the cache', async () => {
@@ -245,7 +265,7 @@ describe('onebot/contact-actions / getGroupMemberInfo', () => {
});
const out = await getGroupMemberInfo(bridge, 1000, 44);
expect(out).toMatchObject({ user_id: 44, nickname: 'dave', card: 'D' });
- expect(bridge.fetchGroupMemberList).not.toHaveBeenCalled();
+ expect(bridge.apis.contacts.fetchGroupMemberList).not.toHaveBeenCalled();
});
it('triggers fetch when member is unknown and re-queries the cache', async () => {
diff --git a/packages/core/tests/onebot/extended-actions.test.ts b/packages/core/tests/onebot/extended-actions.test.ts
index 95ddbb8e..3922194d 100644
--- a/packages/core/tests/onebot/extended-actions.test.ts
+++ b/packages/core/tests/onebot/extended-actions.test.ts
@@ -28,8 +28,27 @@ function fakeMeta(overrides: Partial = {}): MessageMeta {
* pre-stubbed for the test. Same pattern as contact-actions.test.ts —
* keeps tests honest about which surface they actually need.
*/
-function fakeBridge(overrides: Partial = {}): BridgeInterface {
- return new Proxy(overrides as BridgeInterface, {
+// Maps flat method names → ApiHub area they moved to under the #6
+// refactor. Auto-promotion lets tests written against the pre-refactor
+// flat surface (`fetchGroupRequests: vi.fn()`) keep working without
+// per-test restructure.
+const APIS_ROUTING: Record = {
+ fetchFriendList: 'contacts', fetchGroupList: 'contacts',
+ fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
+ fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
+};
+
+function fakeBridge(overrides: Record = {}): BridgeInterface {
+ const apisSynth: Record> = {};
+ for (const [k, v] of Object.entries(overrides)) {
+ const area = APIS_ROUTING[k];
+ if (area) {
+ if (!apisSynth[area]) apisSynth[area] = {};
+ apisSynth[area][k] = v;
+ }
+ }
+ const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
+ return new Proxy(merged as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`);
diff --git a/packages/core/tests/onebot/request-actions.test.ts b/packages/core/tests/onebot/request-actions.test.ts
index 6e51dcf5..044bd724 100644
--- a/packages/core/tests/onebot/request-actions.test.ts
+++ b/packages/core/tests/onebot/request-actions.test.ts
@@ -3,8 +3,24 @@ import { handleGroupAddRequest } from '../../src/onebot/modules/request-actions'
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { GroupRequestInfo } from '../../src/bridge/qq-info';
-function fakeBridge(overrides: Partial = {}): BridgeInterface {
- return new Proxy(overrides as BridgeInterface, {
+// See `contact-actions.test.ts` for the auto-promotion rationale.
+const APIS_ROUTING: Record = {
+ fetchFriendList: 'contacts', fetchGroupList: 'contacts',
+ fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
+ fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
+};
+
+function fakeBridge(overrides: Record = {}): BridgeInterface {
+ const apisSynth: Record> = {};
+ for (const [k, v] of Object.entries(overrides)) {
+ const area = APIS_ROUTING[k];
+ if (area) {
+ if (!apisSynth[area]) apisSynth[area] = {};
+ apisSynth[area][k] = v;
+ }
+ }
+ const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
+ return new Proxy(merged as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`);