refactor(oidb): replace 3 positional helpers with one named runOidb

bridge-oidb.ts used to expose three thin functions —
makeOidbRequest / sendOidbAndCheck / sendOidbAndDecode — and every
action file repeated the same five-step envelope assembly with long
positional argument lists. Collapse them into one `runOidb(bridge,
call)` taking an OidbCall object: cmd / oidbCmd / subCmd / request
{ schema, value, isUid? } / response? { schema }.

Behavioural contract is preserved:
  - No `response`: verify success + gotResponse, peek envelope retCode
    iff response data is present (fire-and-check semantics).
  - With `response`: require responseData, decode through the base
    schema, validate retCode, return the inner body typed as TResp.

Migration touches 51 call sites across 9 source files (bridge-contacts,
actions/{group-file, group-admin, profile, group-message, friend,
interaction, misc}, web-actions/cookies) plus 9 test files that used
to assert on positional `.mock.calls[0]![4]` indices and now read
through `.mock.calls[0]![1].request.value` / `.cmd` / `.oidbCmd`.

Net effect: callers now name what each piece is for, and adding
cross-cutting OIDB behaviour (retry / timeout / per-cmd logging) is a
single-site change inside runOidb instead of a sweep across 9 files.
This commit is contained in:
DrSmoothl committed 2026-05-15 01:03:25 +08:00
1 parent ac10c663f1
commit 59cdfa98a2
19 files changed
+544 -456

No files matched your search

+19 -8
View File
@@ -3,7 +3,7 @@
// protocol uses opaque UIDs rather than QQ uin numbers. // protocol uses opaque UIDs rather than QQ uin numbers.
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { sendOidbAndCheck } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
OidbDeleteFriendSchema, OidbDeleteFriendSchema,
OidbFriendRequestActionSchema, OidbFriendRequestActionSchema,
@@ -15,14 +15,21 @@ export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, app
if (/^\d+$/.test(uidOrFlag)) { if (/^\d+$/.test(uidOrFlag)) {
targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10)); targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10));
} }
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb5d_44', 0xB5D, 44, await runOidb(bridge, {
{ accept: approve ? 3 : 5, targetUid }, OidbFriendRequestActionSchema); cmd: 'OidbSvcTrpcTcp.0xb5d_44',
oidbCmd: 0xB5D, subCmd: 44,
request: { schema: OidbFriendRequestActionSchema, value: { accept: approve ? 3 : 5, targetUid } },
});
} }
export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise<void> { export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise<void> {
const targetUid = await bridge.resolveUserUid(userId); const targetUid = await bridge.resolveUserUid(userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x126b_0', 0x126B, 0, await runOidb(bridge, {
{ cmd: 'OidbSvcTrpcTcp.0x126b_0',
oidbCmd: 0x126B, subCmd: 0,
request: {
schema: OidbDeleteFriendSchema,
value: {
field1: { field1: {
targetUid, targetUid,
field2: { field2: {
@@ -38,7 +45,8 @@ export async function deleteFriend(bridge: Bridge, userId: number, block = false
field4: false, field4: false,
}, },
}, },
OidbDeleteFriendSchema); },
});
// Refresh friend cache after deletion so subsequent reads don't // Refresh friend cache after deletion so subsequent reads don't
// surface a ghost entry. Best-effort: a transient OIDB hiccup here // surface a ghost entry. Best-effort: a transient OIDB hiccup here
@@ -48,6 +56,9 @@ export async function deleteFriend(bridge: Bridge, userId: number, block = false
export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise<void> { export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId); const uid = await bridge.resolveUserUid(userId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xb6e_2', 0xB6E, 2, await runOidb(bridge, {
{ targetUid: uid, remark }, OidbSetFriendRemarkSchema); cmd: 'OidbSvcTrpcTcp.0xb6e_2',
oidbCmd: 0xB6E, subCmd: 2,
request: { schema: OidbSetFriendRemarkSchema, value: { targetUid: uid, remark } },
});
} }
+100 -37
View File
@@ -4,7 +4,7 @@
// so callers can grep across the two layers. // so callers can grep across the two layers.
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { sendOidbAndCheck, sendOidbAndDecode } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
Oidb0x89a_0AddOptionSchema, Oidb0x89a_0AddOptionSchema,
Oidb0x89a_0SearchSchema, Oidb0x89a_0SearchSchema,
@@ -27,25 +27,49 @@ import {
export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> { export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId); const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1253_1', 0x1253, 1, await runOidb(bridge, {
{ groupUin: groupId, type: 1, body: { targetUid: uid, duration } }, OidbMuteMemberSchema); cmd: 'OidbSvcTrpcTcp.0x1253_1',
oidbCmd: 0x1253, subCmd: 1,
request: {
schema: OidbMuteMemberSchema,
value: { groupUin: groupId, type: 1, body: { targetUid: uid, duration } },
},
});
} }
export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise<void> { export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0, await runOidb(bridge, {
{ groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } }, OidbMuteAllSchema); cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: OidbMuteAllSchema,
value: { groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } },
},
});
} }
// ─────────────── join-policy ─────────────── // ─────────────── join-policy ───────────────
export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> { export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0, await runOidb(bridge, {
{ groupUin: BigInt(groupId), settings: { addType }, field12: 0 }, Oidb0x89a_0AddOptionSchema); cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0AddOptionSchema,
value: { groupUin: BigInt(groupId), settings: { addType }, field12: 0 },
},
});
} }
export async function setGroupSearch(bridge: Bridge, groupId: number): Promise<void> { export async function setGroupSearch(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_0', 0x89A, 0, await runOidb(bridge, {
{ groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 }, Oidb0x89a_0SearchSchema); cmd: 'OidbSvcTrpcTcp.0x89a_0',
oidbCmd: 0x89A, subCmd: 0,
request: {
schema: Oidb0x89a_0SearchSchema,
value: { groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 },
},
});
} }
export async function setGroupAddRequest( export async function setGroupAddRequest(
@@ -54,53 +78,92 @@ export async function setGroupAddRequest(
): Promise<void> { ): Promise<void> {
const subCmd = filtered ? 2 : 1; const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1'; const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1';
await sendOidbAndCheck(bridge, cmd, 0x10C8, subCmd, await runOidb(bridge, {
{ accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } }, cmd,
OidbGroupRequestActionSchema, true); oidbCmd: 0x10C8, subCmd,
request: {
schema: OidbGroupRequestActionSchema,
value: { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } },
isUid: true,
},
});
} }
// ─────────────── kick / leave ─────────────── // ─────────────── kick / leave ───────────────
export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> { export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId); const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1, await runOidb(bridge, {
{ groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason }, OidbKickMemberSchema); cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: OidbKickMemberSchema,
value: { groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason },
},
});
} }
export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise<void> { export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise<void> {
const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId))); const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId)));
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8a0_1', 0x8A0, 1, await runOidb(bridge, {
{ groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 }, Oidb0x8a0ReqSchema); cmd: 'OidbSvcTrpcTcp.0x8a0_1',
oidbCmd: 0x8A0, subCmd: 1,
request: {
schema: Oidb0x8a0ReqSchema,
value: { groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0 },
},
});
} }
export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void> { export async function leaveGroup(bridge: Bridge, groupId: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1097_1', 0x1097, 1, await runOidb(bridge, {
{ groupUin: groupId }, OidbLeaveGroupSchema); cmd: 'OidbSvcTrpcTcp.0x1097_1',
oidbCmd: 0x1097, subCmd: 1,
request: { schema: OidbLeaveGroupSchema, value: { groupUin: groupId } },
});
} }
// ─────────────── role / display name ─────────────── // ─────────────── role / display name ───────────────
export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise<void> { export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId); const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x1096_1', 0x1096, 1, await runOidb(bridge, {
{ groupUin: groupId, uid, isAdmin: enable }, OidbSetAdminSchema); cmd: 'OidbSvcTrpcTcp.0x1096_1',
oidbCmd: 0x1096, subCmd: 1,
request: { schema: OidbSetAdminSchema, value: { groupUin: groupId, uid, isAdmin: enable } },
});
} }
export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise<void> { export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId); const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_3', 0x8FC, 3, await runOidb(bridge, {
{ groupUin: groupId, body: { targetUid: uid, targetName: card } }, OidbRenameMemberSchema); cmd: 'OidbSvcTrpcTcp.0x8fc_3',
oidbCmd: 0x8FC, subCmd: 3,
request: {
schema: OidbRenameMemberSchema,
value: { groupUin: groupId, body: { targetUid: uid, targetName: card } },
},
});
} }
export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise<void> { export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x89a_15', 0x89A, 15, await runOidb(bridge, {
{ groupUin: groupId, body: { targetName: name } }, OidbRenameGroupSchema); cmd: 'OidbSvcTrpcTcp.0x89a_15',
oidbCmd: 0x89A, subCmd: 15,
request: { schema: OidbRenameGroupSchema, value: { groupUin: groupId, body: { targetName: name } } },
});
} }
export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise<void> { export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise<void> {
const uid = await bridge.resolveUserUid(userId, groupId); const uid = await bridge.resolveUserUid(userId, groupId);
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x8fc_2', 0x8FC, 2, await runOidb(bridge, {
{ groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } }, OidbSpecialTitleSchema); cmd: 'OidbSvcTrpcTcp.0x8fc_2',
oidbCmd: 0x8FC, subCmd: 2,
request: {
schema: OidbSpecialTitleSchema,
value: { groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } },
},
});
} }
// ─────────────── personal-side metadata ─────────────── // ─────────────── personal-side metadata ───────────────
@@ -109,8 +172,11 @@ export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, user
// here rather than in friend.ts because the semantic is "operate on a // here rather than in friend.ts because the semantic is "operate on a
// group" rather than "operate on a contact list". // group" rather than "operate on a contact list".
export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> { export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xf16_1', 0xF16, 1, await runOidb(bridge, {
{ inner: { groupId: BigInt(groupId), remark }, field12: 0 }, Oidb0xf16ReqSchema); cmd: 'OidbSvcTrpcTcp.0xf16_1',
oidbCmd: 0xF16, subCmd: 1,
request: { schema: Oidb0xf16ReqSchema, value: { inner: { groupId: BigInt(groupId), remark }, field12: 0 } },
});
} }
// ─────────────── group-level quota query ─────────────── // ─────────────── group-level quota query ───────────────
@@ -128,15 +194,12 @@ export async function getGroupAtAllRemain(
type: 0, type: 0,
}; };
const result = await sendOidbAndDecode<any>( const result = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x8a7_0',
'OidbSvcTrpcTcp.0x8a7_0', oidbCmd: 0x8A7, subCmd: 0,
0x8A7, request: { schema: Oidb0x8a7ReqSchema, value: req },
0, response: { schema: Oidb0x8a7RespSchema },
req, });
Oidb0x8a7ReqSchema,
Oidb0x8a7RespSchema,
);
if (!result) { if (!result) {
throw new Error('get group at all remain result empty'); throw new Error('get group at all remain result empty');
+114 -114
View File
@@ -7,7 +7,7 @@
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode'; import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndDecode } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils'; import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils';
import { import {
@@ -241,16 +241,12 @@ async function fetchNtv2DownloadUrl(
oidbCmd: number, oidbCmd: number,
payload: Record<string, unknown>, payload: Record<string, unknown>,
): Promise<string> { ): Promise<string> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: serviceCmd,
serviceCmd, oidbCmd, subCmd: 200,
oidbCmd, request: { schema: NTV2RichMediaReqSchema, value: payload, isUid: true },
200, response: { schema: NTV2RichMediaRespSchema },
payload, });
NTV2RichMediaReqSchema,
NTV2RichMediaRespSchema,
true,
);
ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined); ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined);
const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : ''; const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : '';
@@ -266,11 +262,15 @@ async function fetchNtv2DownloadUrl(
// ─────────────── file count ─────────────── // ─────────────── file count ───────────────
export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> { export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> {
const resp = await sendOidbAndDecode<any>(bridge, const resp = await runOidb<any>(bridge, {
'OidbSvcTrpcTcp.0x6d8_3', 0x6D8, 3, cmd: 'OidbSvcTrpcTcp.0x6d8_3',
{ count: { groupUin: groupId, appId: 7, busId: 0 } }, oidbCmd: 0x6D8, subCmd: 3,
OidbGroupFileCountViewReqSchema, request: {
OidbGroupFileCountViewRespSchema); schema: OidbGroupFileCountViewReqSchema,
value: { count: { groupUin: groupId, appId: 7, busId: 0 } },
},
response: { schema: OidbGroupFileCountViewRespSchema },
});
return { return {
fileCount: toInt(resp?.count?.fileCount ?? 0), fileCount: toInt(resp?.count?.fileCount ?? 0),
maxCount: toInt(resp?.count?.maxCount ?? 10000), maxCount: toInt(resp?.count?.maxCount ?? 10000),
@@ -293,12 +293,12 @@ export async function uploadGroupFile(
const fileName = normalizeUploadFileName(name, loaded.fileName); const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes); const hashes = computeHashes(loaded.bytes);
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d6_0',
'OidbSvcTrpcTcp.0x6d6_0', oidbCmd: 0x6D6, subCmd: 0,
0x6D6, request: {
0, schema: OidbGroupFileReqSchema,
{ value: {
file: { file: {
groupUin: groupId, groupUin: groupId,
appId: 4, appId: 4,
@@ -314,10 +314,10 @@ export async function uploadGroupFile(
field15: true, field15: true,
}, },
}, },
OidbGroupFileReqSchema, isUid: true,
OidbGroupFileRespSchema, },
true, response: { schema: OidbGroupFileRespSchema },
); });
const upload = resp?.upload; const upload = resp?.upload;
if (!upload) throw new Error('group file upload response missing'); if (!upload) throw new Error('group file upload response missing');
@@ -384,12 +384,12 @@ export async function uploadPrivateFile(
const fileName = normalizeUploadFileName(name, loaded.fileName); const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes); const hashes = computeHashes(loaded.bytes);
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0xe37_1700',
'OidbSvcTrpcTcp.0xe37_1700', oidbCmd: 0xE37, subCmd: 1700,
0xE37, request: {
1700, schema: OidbPrivateFileUploadReqSchema,
{ value: {
command: 1700, command: 1700,
seq: 0, seq: 0,
upload: { upload: {
@@ -407,9 +407,9 @@ export async function uploadPrivateFile(
clientType: 1, clientType: 1,
flagSupportMediaPlatform: 1, flagSupportMediaPlatform: 1,
}, },
OidbPrivateFileUploadReqSchema, },
OidbPrivateFileUploadRespSchema, response: { schema: OidbPrivateFileUploadRespSchema },
); });
const upload = resp?.upload; const upload = resp?.upload;
if (!upload) throw new Error('private file upload response missing'); if (!upload) throw new Error('private file upload response missing');
@@ -458,12 +458,12 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
const pageSize = 20; const pageSize = 20;
let startIndex = 0; let startIndex = 0;
for (let page = 0; page < 200; page++) { for (let page = 0; page < 200; page++) {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d8_1',
'OidbSvcTrpcTcp.0x6d8_1', oidbCmd: 0x6D8, subCmd: 1,
0x6D8, request: {
1, schema: OidbGroupFileViewReqSchema,
{ value: {
list: { list: {
groupUin: groupId, groupUin: groupId,
appId: 7, appId: 7,
@@ -475,10 +475,10 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
field18: 0, field18: 0,
}, },
}, },
OidbGroupFileViewReqSchema, isUid: true,
OidbGroupFileViewRespSchema, },
true, response: { schema: OidbGroupFileViewRespSchema },
); });
const list = resp?.list; const list = resp?.list;
if (!list) break; if (!list) break;
@@ -533,12 +533,12 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId
// ─────────────── url fetch (group / private files) ─────────────── // ─────────────── url fetch (group / private files) ───────────────
export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise<string> { export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise<string> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d6_2',
'OidbSvcTrpcTcp.0x6d6_2', oidbCmd: 0x6D6, subCmd: 2,
0x6D6, request: {
2, schema: OidbGroupFileReqSchema,
{ value: {
download: { download: {
groupUin: groupId, groupUin: groupId,
appId: 7, appId: 7,
@@ -546,10 +546,10 @@ export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId:
fileId, fileId,
}, },
}, },
OidbGroupFileReqSchema, isUid: true,
OidbGroupFileRespSchema, },
true, response: { schema: OidbGroupFileRespSchema },
); });
const download = resp?.download; const download = resp?.download;
if (!download) throw new Error('group file url response missing'); if (!download) throw new Error('group file url response missing');
@@ -569,12 +569,12 @@ export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId:
export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> { export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise<string> {
const uid = await bridge.resolveUserUid(userId); const uid = await bridge.resolveUserUid(userId);
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0xe37_1200',
'OidbSvcTrpcTcp.0xe37_1200', oidbCmd: 0xE37, subCmd: 1200,
0xE37, request: {
1200, schema: OidbPrivateFileDownloadReqSchema,
{ value: {
subCommand: 1200, subCommand: 1200,
field2: 1, field2: 1,
body: { body: {
@@ -589,9 +589,9 @@ export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId
field200: 1, field200: 1,
field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]),
}, },
OidbPrivateFileDownloadReqSchema, },
OidbPrivateFileDownloadRespSchema, response: { schema: OidbPrivateFileDownloadRespSchema },
); });
const result = resp?.body?.result; const result = resp?.body?.result;
const server = typeof result?.server === 'string' ? result.server : ''; const server = typeof result?.server === 'string' ? result.server : '';
@@ -606,22 +606,22 @@ export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId
// ─────────────── delete / move ─────────────── // ─────────────── delete / move ───────────────
export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise<void> { export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise<void> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d6_3',
'OidbSvcTrpcTcp.0x6d6_3', oidbCmd: 0x6D6, subCmd: 3,
0x6D6, request: {
3, schema: OidbGroupFileReqSchema,
{ value: {
delete: { delete: {
groupUin: groupId, groupUin: groupId,
busId: 102, busId: 102,
fileId, fileId,
}, },
}, },
OidbGroupFileReqSchema, isUid: true,
OidbGroupFileRespSchema, },
true, response: { schema: OidbGroupFileRespSchema },
); });
const result = resp?.delete; const result = resp?.delete;
if (!result) throw new Error('group file delete response missing'); if (!result) throw new Error('group file delete response missing');
@@ -635,12 +635,12 @@ export async function moveGroupFile(
parentDirectory: string, parentDirectory: string,
targetDirectory: string, targetDirectory: string,
): Promise<void> { ): Promise<void> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d6_5',
'OidbSvcTrpcTcp.0x6d6_5', oidbCmd: 0x6D6, subCmd: 5,
0x6D6, request: {
5, schema: OidbGroupFileReqSchema,
{ value: {
move: { move: {
groupUin: groupId, groupUin: groupId,
appId: 7, appId: 7,
@@ -650,10 +650,10 @@ export async function moveGroupFile(
targetDirectory, targetDirectory,
}, },
}, },
OidbGroupFileReqSchema, isUid: true,
OidbGroupFileRespSchema, },
true, response: { schema: OidbGroupFileRespSchema },
); });
const result = resp?.move; const result = resp?.move;
if (!result) throw new Error('group file move response missing'); if (!result) throw new Error('group file move response missing');
@@ -663,22 +663,22 @@ export async function moveGroupFile(
// ─────────────── folders ─────────────── // ─────────────── folders ───────────────
export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise<void> { export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise<void> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d7_0',
'OidbSvcTrpcTcp.0x6d7_0', oidbCmd: 0x6D7, subCmd: 0,
0x6D7, request: {
0, schema: OidbGroupFileFolderReqSchema,
{ value: {
create: { create: {
groupUin: groupId, groupUin: groupId,
rootDirectory: normalizeDirectory(parentId), rootDirectory: normalizeDirectory(parentId),
folderName: name, folderName: name,
}, },
}, },
OidbGroupFileFolderReqSchema, isUid: true,
OidbGroupFileFolderRespSchema, },
true, response: { schema: OidbGroupFileFolderRespSchema },
); });
const result = resp?.create; const result = resp?.create;
if (!result) throw new Error('group folder create response missing'); if (!result) throw new Error('group folder create response missing');
@@ -686,21 +686,21 @@ export async function createGroupFileFolder(bridge: Bridge, groupId: number, nam
} }
export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise<void> { export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise<void> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d7_1',
'OidbSvcTrpcTcp.0x6d7_1', oidbCmd: 0x6D7, subCmd: 1,
0x6D7, request: {
1, schema: OidbGroupFileFolderReqSchema,
{ value: {
delete: { delete: {
groupUin: groupId, groupUin: groupId,
folderId, folderId,
}, },
}, },
OidbGroupFileFolderReqSchema, isUid: true,
OidbGroupFileFolderRespSchema, },
true, response: { schema: OidbGroupFileFolderRespSchema },
); });
const result = resp?.delete; const result = resp?.delete;
if (!result) throw new Error('group folder delete response missing'); if (!result) throw new Error('group folder delete response missing');
@@ -708,22 +708,22 @@ export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, fol
} }
export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise<void> { export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise<void> {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x6d7_2',
'OidbSvcTrpcTcp.0x6d7_2', oidbCmd: 0x6D7, subCmd: 2,
0x6D7, request: {
2, schema: OidbGroupFileFolderReqSchema,
{ value: {
rename: { rename: {
groupUin: groupId, groupUin: groupId,
folderId, folderId,
newFolderName, newFolderName,
}, },
}, },
OidbGroupFileFolderReqSchema, isUid: true,
OidbGroupFileFolderRespSchema, },
true, response: { schema: OidbGroupFileFolderRespSchema },
); });
const result = resp?.rename; const result = resp?.rename;
if (!result) throw new Error('group folder rename response missing'); if (!result) throw new Error('group folder rename response missing');
@@ -5,7 +5,7 @@
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode'; import { protoEncode } from '../../protobuf/decode';
import { sendOidbAndCheck } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
C2CRecallRequestSchema, C2CRecallRequestSchema,
GroupRecallRequestSchema, GroupRecallRequestSchema,
@@ -96,6 +96,9 @@ export async function markGroupMessageRead(
export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise<void> { export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
const subCmd = enable ? 1 : 2; const subCmd = enable ? 1 : 2;
const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2'; const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2';
await sendOidbAndCheck(bridge, cmd, 0xEAC, subCmd, await runOidb(bridge, {
{ groupUin: groupId, sequence, random }, OidbEssenceSchema); cmd,
oidbCmd: 0xEAC, subCmd,
request: { schema: OidbEssenceSchema, value: { groupUin: groupId, sequence, random } },
});
} }
@@ -3,7 +3,7 @@
// edit message content — they're purely social signals. // edit message content — they're purely social signals.
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { sendOidbAndCheck, sendOidbAndDecode } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
Oidb0x9083ReqSchema, Oidb0x9083ReqSchema,
Oidb0x9083RespSchema, Oidb0x9083RespSchema,
@@ -13,18 +13,27 @@ import {
} from '../proto/oidb-action'; } from '../proto/oidb-action';
export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> { export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0xed3_1', 0xED3, 1, await runOidb(bridge, {
{ cmd: 'OidbSvcTrpcTcp.0xed3_1',
oidbCmd: 0xED3, subCmd: 1,
request: {
schema: OidbPokeSchema,
value: {
uin: targetUin ?? peerUin, uin: targetUin ?? peerUin,
groupUin: isGroup ? peerUin : 0, groupUin: isGroup ? peerUin : 0,
friendUin: isGroup ? 0 : peerUin, friendUin: isGroup ? 0 : peerUin,
ext: 0, ext: 0,
}, OidbPokeSchema); },
},
});
} }
export async function sendLike(bridge: Bridge, userId: number, count: number): Promise<void> { export async function sendLike(bridge: Bridge, userId: number, count: number): Promise<void> {
await sendOidbAndCheck(bridge, 'OidbSvcTrpcTcp.0x7e5_104', 0x7E5, 104, await runOidb(bridge, {
{ targetUin: userId, count }, OidbLikeSchema); cmd: 'OidbSvcTrpcTcp.0x7e5_104',
oidbCmd: 0x7E5, subCmd: 104,
request: { schema: OidbLikeSchema, value: { targetUin: userId, count } },
});
} }
export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> { export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
@@ -35,8 +44,14 @@ export async function setGroupReaction(bridge: Bridge, groupId: number, sequence
// type field to pick the right resolution table; omitting it makes // type field to pick the right resolution table; omitting it makes
// unicode reactions silently fail. // unicode reactions silently fail.
const type = code.length > 3 ? 2 : 1; const type = code.length > 3 ? 2 : 1;
await sendOidbAndCheck(bridge, cmd, 0x9082, subCmd, await runOidb(bridge, {
{ groupUin: groupId, sequence, code, type }, OidbGroupReactionSchema); cmd,
oidbCmd: 0x9082, subCmd,
request: {
schema: OidbGroupReactionSchema,
value: { groupUin: groupId, sequence, code, type },
},
});
} }
export async function getEmojiLikes( export async function getEmojiLikes(
@@ -58,7 +73,12 @@ export async function getEmojiLikes(
count, count,
field12: 1, field12: 1,
}; };
const resp = await sendOidbAndDecode<any>(bridge, 'OidbSvcTrpcTcp.0x9083_1', 0x9083, 1, req, Oidb0x9083ReqSchema, Oidb0x9083RespSchema); const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0x9083_1',
oidbCmd: 0x9083, subCmd: 1,
request: { schema: Oidb0x9083ReqSchema, value: req },
response: { schema: Oidb0x9083RespSchema },
});
const uin = resp?.inner?.userInfo?.uin; const uin = resp?.inner?.userInfo?.uin;
const users = uin ? [{ uin: Number(uin) }] : []; const users = uin ? [{ uin: Number(uin) }] : [];
const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : ''; const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : '';
+19 -28
View File
@@ -4,7 +4,7 @@
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode'; import { protoDecode, protoEncode } from '../../protobuf/decode';
import { sendOidbAndDecode } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
MiniAppShareReqSchema, MiniAppShareReqSchema,
MiniAppShareRespSchema, MiniAppShareRespSchema,
@@ -30,15 +30,12 @@ export async function translateEn2Zh(
tag12: 1, tag12: 1,
}; };
const result = await sendOidbAndDecode<any>( const result = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x990_2',
'OidbSvcTrpcTcp.0x990_2', oidbCmd: 0x990, subCmd: 2,
0x990, request: { schema: Oidb0x990ReqSchema, value: req },
2, response: { schema: Oidb0x990RespSchema },
req, });
Oidb0x990ReqSchema,
Oidb0x990RespSchema,
);
const resp = result?.translateResp; const resp = result?.translateResp;
if (!resp) { if (!resp) {
@@ -125,15 +122,12 @@ export async function clickInlineKeyboardButton(
unknown9: 1, unknown9: 1,
}; };
const result = await sendOidbAndDecode<any>( const result = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x112e_1',
'OidbSvcTrpcTcp.0x112e_1', oidbCmd: 0x112E, subCmd: 1,
0x112E, request: { schema: Oidb0x112eReqSchema, value: req },
1, response: { schema: Oidb0x112eRespSchema },
req, });
Oidb0x112eReqSchema,
Oidb0x112eRespSchema,
);
if (!result) { if (!result) {
throw new Error('click inline keyboard button result empty'); throw new Error('click inline keyboard button result empty');
@@ -161,13 +155,10 @@ export async function sendGroupSign(
}, },
}; };
await sendOidbAndDecode<any>( await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0xEB7_1',
'OidbSvcTrpcTcp.0xEB7_1', oidbCmd: 0xEB7, subCmd: 1,
0xEB7, request: { schema: Oidb0xeb7ReqSchema, value: req },
1, response: { schema: Oidb0xeb7RespSchema },
req, });
Oidb0xeb7ReqSchema,
Oidb0xeb7RespSchema,
);
} }
+30 -45
View File
@@ -4,7 +4,7 @@
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { protoDecode, protoEncode } from '../../protobuf/decode'; import { protoDecode, protoEncode } from '../../protobuf/decode';
import { sendOidbAndCheck, sendOidbAndDecode } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, loadBinarySource } from '../highway/utils'; import { computeHashes, loadBinarySource } from '../highway/utils';
import { import {
@@ -81,14 +81,11 @@ export async function setProfile(
stringProfiles, stringProfiles,
}; };
await sendOidbAndCheck( await runOidb(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x112a_2',
'OidbSvcTrpcTcp.0x112a_2', oidbCmd: 0x112A, subCmd: 2,
0x112A, request: { schema: OidbSetProfileSchema, value: req },
2, });
req,
OidbSetProfileSchema,
);
} }
export async function setSelfLongNick( export async function setSelfLongNick(
@@ -103,15 +100,12 @@ export async function setSelfLongNick(
}, },
}; };
await sendOidbAndDecode<any>( await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x112a_2',
'OidbSvcTrpcTcp.0x112a_2', oidbCmd: 0x112A, subCmd: 2,
0x112A, request: { schema: Oidb0x112aReqSchema, value: req },
2, response: { schema: Oidb0x112aRespSchema },
req, });
Oidb0x112aReqSchema,
Oidb0x112aRespSchema,
);
} }
export async function setInputStatus( export async function setInputStatus(
@@ -133,15 +127,12 @@ export async function setInputStatus(
}, },
}; };
await sendOidbAndDecode<any>( await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0xcd4_1',
'OidbSvcTrpcTcp.0xcd4_1', oidbCmd: 0xCD4, subCmd: 1,
0xCD4, request: { schema: Oidb0xcd4ReqSchema, value: req },
1, response: { schema: Oidb0xcd4RespSchema },
req, });
Oidb0xcd4ReqSchema,
Oidb0xcd4RespSchema,
);
} }
export async function setAvatar( export async function setAvatar(
@@ -182,15 +173,12 @@ export async function getProfileLike(
limit: limit, limit: limit,
}; };
const result = await sendOidbAndDecode<any>( const result = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x7ed_12',
'OidbSvcTrpcTcp.0x7ed_12', oidbCmd: 0x7ED, subCmd: 12,
0x7ED, request: { schema: Oidb0x7edReqSchema, value: req },
12, response: { schema: Oidb0x7edRespSchema },
req, });
Oidb0x7edReqSchema,
Oidb0x7edRespSchema,
);
const data = result?.userLikeInfos?.[0]; const data = result?.userLikeInfos?.[0];
if (!data) { if (!data) {
@@ -230,15 +218,12 @@ export async function getUnidirectionalFriendList(
jsonBody: JSON.stringify(reqObj), jsonBody: JSON.stringify(reqObj),
}; };
const result = await sendOidbAndDecode<any>( const result = await runOidb<any>(bridge, {
bridge, cmd: 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0',
'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', oidbCmd: 0xE17, subCmd: 0,
0xE17, request: { schema: Oidb0xe17ReqSchema, value: req },
0, response: { schema: Oidb0xe17RespSchema },
req, });
Oidb0xe17ReqSchema,
Oidb0xe17RespSchema,
);
if (!result || !result.jsonBody) { if (!result || !result.jsonBody) {
throw new Error('get unidirectional friend list empty'); throw new Error('get unidirectional friend list empty');
+37 -19
View File
@@ -4,7 +4,7 @@ import type { Bridge } from './bridge';
import type { DownloadRKeyInfo } from './bridge'; import type { DownloadRKeyInfo } from './bridge';
import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info';
import { protoDecode } from '../protobuf/decode'; import { protoDecode } from '../protobuf/decode';
import { sendOidbAndDecode } from './bridge-oidb'; import { runOidb } from './bridge-oidb';
import { import {
OidbSvcTrpcTcp0xFD4_1ResponseSchema, OidbSvcTrpcTcp0xFD4_1ResponseSchema,
OidbSvcTrpcTcp0xFE5_2ResponseSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema,
@@ -71,9 +71,12 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
body.nextUin = { uin: nextUin }; body.nextUin = { uin: nextUin };
} }
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, 'OidbSvcTrpcTcp.0xfd4_1', 0xFD4, 1, body, cmd: 'OidbSvcTrpcTcp.0xfd4_1',
OidbFriendListRequestSchema, OidbSvcTrpcTcp0xFD4_1ResponseSchema); oidbCmd: 0xFD4, subCmd: 1,
request: { schema: OidbFriendListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFD4_1ResponseSchema },
});
if (resp?.friends) { if (resp?.friends) {
for (const raw of resp.friends) { for (const raw of resp.friends) {
@@ -121,9 +124,12 @@ export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
}, },
}; };
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, 'OidbSvcTrpcTcp.0xfe5_2', 0xFE5, 2, body, cmd: 'OidbSvcTrpcTcp.0xfe5_2',
OidbGroupListRequestSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema, true); oidbCmd: 0xFE5, subCmd: 2,
request: { schema: OidbGroupListRequestSchema, value: body, isUid: true },
response: { schema: OidbSvcTrpcTcp0xFE5_2ResponseSchema },
});
const groups: QQGroupInfo[] = []; const groups: QQGroupInfo[] = [];
if (resp?.groups) { if (resp?.groups) {
@@ -165,9 +171,12 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
}; };
if (token) body.token = token; if (token) body.token = token;
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, 'OidbSvcTrpcTcp.0xfe7_3', 0xFE7, 3, body, cmd: 'OidbSvcTrpcTcp.0xfe7_3',
OidbGroupMemberListRequestSchema, OidbSvcTrpcTcp0xFE7_3ResponseSchema); oidbCmd: 0xFE7, subCmd: 3,
request: { schema: OidbGroupMemberListRequestSchema, value: body },
response: { schema: OidbSvcTrpcTcp0xFE7_3ResponseSchema },
});
if (resp?.members) { if (resp?.members) {
for (const raw of resp.members) { for (const raw of resp.members) {
@@ -205,9 +214,12 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<Use
keys: keys.map(k => ({ key: k })), keys: keys.map(k => ({ key: k })),
}; };
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, 'OidbSvcTrpcTcp.0xfe1_2', 0xFE1, 2, body, cmd: 'OidbSvcTrpcTcp.0xfe1_2',
OidbUserInfoRequestSchema, OidbUserInfoResponseSchema); oidbCmd: 0xFE1, subCmd: 2,
request: { schema: OidbUserInfoRequestSchema, value: body },
response: { schema: OidbUserInfoResponseSchema },
});
if (!resp?.body) throw new Error('user info response body missing'); if (!resp?.body) throw new Error('user info response body missing');
@@ -259,9 +271,12 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<Use
export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise<GroupRequestInfo[]> { export async function fetchGroupRequests(bridge: Bridge, filtered = false): Promise<GroupRequestInfo[]> {
const subCmd = filtered ? 2 : 1; const subCmd = filtered ? 2 : 1;
const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1'; const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1';
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd, 0x10C0, subCmd, { count: 20, field2: 0 }, cmd,
OidbGroupRequestListSchema, OidbSvcTrpcTcp0x10C0ResponseSchema); oidbCmd: 0x10C0, subCmd,
request: { schema: OidbGroupRequestListSchema, value: { count: 20, field2: 0 } },
response: { schema: OidbSvcTrpcTcp0x10C0ResponseSchema },
});
const requests: GroupRequestInfo[] = []; const requests: GroupRequestInfo[] = [];
for (const raw of resp?.requests ?? []) { for (const raw of resp?.requests ?? []) {
@@ -308,9 +323,12 @@ export async function fetchDownloadRKeys(bridge: Bridge): Promise<DownloadRKeyIn
}, },
}; };
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, 'OidbSvcTrpcTcp.0x9067_202', 0x9067, 202, body, cmd: 'OidbSvcTrpcTcp.0x9067_202',
NTV2RichMediaReqSchema, NTV2RichMediaRespSchema, true); oidbCmd: 0x9067, subCmd: 202,
request: { schema: NTV2RichMediaReqSchema, value: body, isUid: true },
response: { schema: NTV2RichMediaRespSchema },
});
if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) { if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) {
throw new Error(resp.respHead.message ?? 'fetch download rkey failed'); throw new Error(resp.respHead.message ?? 'fetch download rkey failed');
+68 -47
View File
@@ -1,69 +1,90 @@
// OIDB protocol helpers -- encode requests, send+check, send+decode. // One deep entry point for a single OIDB round-trip: build the envelope,
// dispatch via Bridge.sendRawPacket, validate the response status, and
// optionally decode the body. Replaces the three positional helpers
// (makeOidbRequest / sendOidbAndCheck / sendOidbAndDecode) that used to
// scatter the same five-step pattern across every action file.
import type { Bridge } from './bridge'; import type { Bridge } from './bridge';
import type { ProtoSchema } from '../protobuf/decode'; import type { ProtoSchema } from '../protobuf/decode';
import { protoEncode, protoDecode } from '../protobuf/decode'; import { protoEncode, protoDecode } from '../protobuf/decode';
import { makeOidbBaseSchema } from './proto/oidb'; import { makeOidbBaseSchema } from './proto/oidb';
export interface OidbCall<TResp = void> {
/** Service-cmd string sent on the wire, e.g. 'OidbSvcTrpcTcp.0x1253_1'. */
cmd: string;
/** OIDB command number, e.g. 0x1253. */
oidbCmd: number;
/** OIDB sub-command, e.g. 1. */
subCmd: number;
request: {
schema: ProtoSchema;
value: any;
/** /**
* Build a raw OIDB request buffer (base envelope wrapping a typed body). * Sets the OIDB envelope `reserved` field to 1 when true. A handful
* of commands (group/friend list, rkey download) operate on
* UID-keyed data and require this flag — the wire format is
* otherwise identical.
*/ */
export function makeOidbRequest( isUid?: boolean;
command: number, subCommand: number, };
body: any, bodySchema: ProtoSchema, isUid = false, /** Omit to skip decoding the response body (fire-and-check). */
): Uint8Array { response?: {
const baseSchema = makeOidbBaseSchema(bodySchema); schema: ProtoSchema;
return protoEncode({ };
command,
subCommand,
errorCode: 0,
body,
errorMsg: '',
reserved: isUid ? 1 : 0,
}, baseSchema);
} }
/** /**
* Send an OIDB packet and verify it succeeded (no decode of body). * Issue one OIDB request. Without `response`, returns void after
* verifying the envelope's retCode. With `response`, decodes the
* envelope, validates retCode, and returns the inner body.
*
* Throws on transport failure, missing response, decode failure, or any
* non-zero envelope retCode. Action modules layer their own retCode
* checks (on inner sub-replies like `upload.retCode`) on top of this.
*/ */
export async function sendOidbAndCheck( export function runOidb(bridge: Bridge, call: OidbCall<void> & { response?: undefined }): Promise<void>;
bridge: Bridge, export function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp> & { response: { schema: ProtoSchema } }): Promise<TResp>;
serviceCmd: string, command: number, subCommand: number, export async function runOidb<TResp>(bridge: Bridge, call: OidbCall<TResp>): Promise<TResp | void> {
body: any, bodySchema: ProtoSchema, isUid = false, const envelope = encodeOidbEnvelope(call);
): Promise<void> { const result = await bridge.sendRawPacket(call.cmd, envelope);
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid);
const result = await bridge.sendRawPacket(serviceCmd, request);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed'); if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (call.response) {
if (!result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'no response');
}
const baseSchema = makeOidbBaseSchema(call.response.schema);
const resp = protoDecode(result.responseData, baseSchema);
if (!resp) throw new Error('failed to decode OIDB response');
throwIfOidbError(resp);
return (resp as any).body as TResp;
}
// Fire-and-check: response data is optional, but if present we still
// peek at the envelope so a server-side retCode doesn't silently slip past.
if (!result.gotResponse) throw new Error(result.errorMessage || 'no response'); if (!result.gotResponse) throw new Error(result.errorMessage || 'no response');
// Check OIDB error code if response present
if (result.responseData && result.responseData.length > 0) { if (result.responseData && result.responseData.length > 0) {
const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } }); const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } });
const resp = protoDecode(result.responseData, emptyBase); const resp = protoDecode(result.responseData, emptyBase);
if (resp && (resp as any).errorCode && (resp as any).errorCode !== 0) { if (resp) throwIfOidbError(resp);
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
}
} }
} }
/** function encodeOidbEnvelope(call: OidbCall<unknown>): Uint8Array {
* Send an OIDB packet and decode the response body with the given schema. const baseSchema = makeOidbBaseSchema(call.request.schema);
*/ return protoEncode({
export async function sendOidbAndDecode<T>( command: call.oidbCmd,
bridge: Bridge, subCommand: call.subCmd,
serviceCmd: string, command: number, subCommand: number, errorCode: 0,
body: any, bodySchema: ProtoSchema, responseSchema: ProtoSchema, isUid = false, body: call.request.value,
): Promise<T> { errorMsg: '',
const request = makeOidbRequest(command, subCommand, body, bodySchema, isUid); reserved: call.request.isUid ? 1 : 0,
const result = await bridge.sendRawPacket(serviceCmd, request); }, baseSchema);
if (!result.success) throw new Error(result.errorMessage || 'packet send failed');
if (!result.gotResponse || !result.responseData) throw new Error(result.errorMessage || 'no response');
const baseSchema = makeOidbBaseSchema(responseSchema);
const resp = protoDecode(result.responseData, baseSchema);
if (!resp) throw new Error('failed to decode OIDB response');
if ((resp as any).errorCode && (resp as any).errorCode !== 0) {
throw new Error(`OIDB error ${(resp as any).errorCode}: ${(resp as any).errorMsg ?? ''}`);
}
return (resp as any).body as T;
} }
function throwIfOidbError(resp: unknown): void {
const code = (resp as any).errorCode;
if (code && code !== 0) {
throw new Error(`OIDB error ${code}: ${(resp as any).errorMsg ?? ''}`);
}
}
+13 -19
View File
@@ -4,7 +4,7 @@
// thread the cookies into a qun.qq.com REST endpoint. // thread the cookies into a qun.qq.com REST endpoint.
import type { Bridge } from '../bridge'; import type { Bridge } from '../bridge';
import { sendOidbAndDecode } from '../bridge-oidb'; import { runOidb } from '../bridge-oidb';
import { import {
OidbClientKeyRespSchema, OidbClientKeyRespSchema,
OidbClientKeyReqSchema, OidbClientKeyReqSchema,
@@ -14,15 +14,12 @@ import {
import { RequestUtil } from '../web/request-util'; import { RequestUtil } from '../web/request-util';
export async function forceFetchClientKey(bridge: Bridge) { export async function forceFetchClientKey(bridge: Bridge) {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x102a_1',
'OidbSvcTrpcTcp.0x102a_1', oidbCmd: 0x102A, subCmd: 1,
0x102A, request: { schema: OidbClientKeyReqSchema, value: {} },
1, response: { schema: OidbClientKeyRespSchema },
{}, });
OidbClientKeyReqSchema,
OidbClientKeyRespSchema,
);
const clientKey = resp?.clientKey || ''; const clientKey = resp?.clientKey || '';
// keyIndex falls back to "19" — origin unknown but the value is what // keyIndex falls back to "19" — origin unknown but the value is what
@@ -37,15 +34,12 @@ export async function forceFetchClientKey(bridge: Bridge) {
} }
export async function getPSkey(bridge: Bridge, domainList: string[]) { export async function getPSkey(bridge: Bridge, domainList: string[]) {
const resp = await sendOidbAndDecode<any>( const resp = await runOidb<any>(bridge, {
bridge, cmd: 'OidbSvcTrpcTcp.0x102a_0',
'OidbSvcTrpcTcp.0x102a_0', oidbCmd: 0x102A, subCmd: 0,
0x102A, request: { schema: OidbGetPskeyReqSchema, value: { domainList } },
0, response: { schema: OidbGetPskeyRespSchema },
{ domainList }, });
OidbGetPskeyReqSchema,
OidbGetPskeyRespSchema,
);
const domainPskeyMap = new Map<string, string>(); const domainPskeyMap = new Map<string, string>();
+1 -3
View File
@@ -1,9 +1,7 @@
import { describe, it, expect, vi } from 'vitest'; import { describe, it, expect, vi } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
// element-builder reaches into protoEncode with element-specific schemas // element-builder reaches into protoEncode with element-specific schemas
+12 -14
View File
@@ -1,9 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
import * as oidb from '../../src/bridge/bridge-oidb'; import * as oidb from '../../src/bridge/bridge-oidb';
@@ -12,32 +10,32 @@ import { mockBridge } from './_helpers';
describe('actions/friend', () => { describe('actions/friend', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockClear();
}); });
it('setFriendAddRequest: numeric input is treated as UIN and resolved', async () => { it('setFriendAddRequest: numeric input is treated as UIN and resolved', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await friend.setFriendAddRequest(bridge as any, '10001', true); await friend.setFriendAddRequest(bridge as any, '10001', true);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(payload).toMatchObject({ accept: 3, targetUid: 'resolved-uid' }); expect(call.request.value).toMatchObject({ accept: 3, targetUid: 'resolved-uid' });
}); });
it('setFriendAddRequest: non-numeric flag is forwarded as-is', async () => { it('setFriendAddRequest: non-numeric flag is forwarded as-is', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await friend.setFriendAddRequest(bridge as any, 'flag-abc', false); await friend.setFriendAddRequest(bridge as any, 'flag-abc', false);
expect(bridge.resolveUserUid).not.toHaveBeenCalled(); expect(bridge.resolveUserUid).not.toHaveBeenCalled();
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(payload).toMatchObject({ accept: 5, targetUid: 'flag-abc' }); expect(call.request.value).toMatchObject({ accept: 5, targetUid: 'flag-abc' });
}); });
it('deleteFriend resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => { it('deleteFriend resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await friend.deleteFriend(bridge as any, 10001, true); await friend.deleteFriend(bridge as any, 10001, true);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0x126b_0'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0x126b_0');
expect((call[4] as any).field1.block).toBe(true); expect((call.request.value as any).field1.block).toBe(true);
expect(bridge.fetchFriendList).toHaveBeenCalled(); expect(bridge.fetchFriendList).toHaveBeenCalled();
}); });
@@ -52,8 +50,8 @@ describe('actions/friend', () => {
it('setFriendRemark resolves UID and sends 0xb6e_2', async () => { it('setFriendRemark resolves UID and sends 0xb6e_2', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await friend.setFriendRemark(bridge as any, 10001, 'best-friend'); await friend.setFriendRemark(bridge as any, 10001, 'best-friend');
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0xb6e_2'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0xb6e_2');
expect(call[4]).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' }); expect(call.request.value).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' });
}); });
}); });
+22 -25
View File
@@ -3,9 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// Stub the OIDB shim so we can assert WHICH command + payload each // Stub the OIDB shim so we can assert WHICH command + payload each
// action constructs without booting a real Bridge / native pipe. // action constructs without booting a real Bridge / native pipe.
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
import * as oidb from '../../src/bridge/bridge-oidb'; import * as oidb from '../../src/bridge/bridge-oidb';
@@ -14,20 +12,19 @@ import { mockBridge } from './_helpers';
describe('actions/group-admin', () => { describe('actions/group-admin', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockClear();
vi.mocked(oidb.sendOidbAndDecode).mockClear();
}); });
it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => { it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await admin.muteGroupMember(bridge as any, 12345, 67890, 600); await admin.muteGroupMember(bridge as any, 12345, 67890, 600);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
expect(oidb.sendOidbAndCheck).toHaveBeenCalledOnce(); expect(oidb.runOidb).toHaveBeenCalledOnce();
const args = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(args[1]).toBe('OidbSvcTrpcTcp.0x1253_1'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1253_1');
expect(args[2]).toBe(0x1253); expect(call.oidbCmd).toBe(0x1253);
expect(args[3]).toBe(1); expect(call.subCmd).toBe(1);
expect(args[4]).toMatchObject({ expect(call.request.value).toMatchObject({
groupUin: 12345, groupUin: 12345,
type: 1, type: 1,
body: { targetUid: 'resolved-uid', duration: 600 }, body: { targetUid: 'resolved-uid', duration: 600 },
@@ -37,13 +34,13 @@ describe('actions/group-admin', () => {
it('muteGroupAll flips the muteState flag based on enable', async () => { it('muteGroupAll flips the muteState flag based on enable', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await admin.muteGroupAll(bridge as any, 12345, true); await admin.muteGroupAll(bridge as any, 12345, true);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({ expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
groupUin: 12345, groupUin: 12345,
muteState: { state: 0xFFFFFFFF }, muteState: { state: 0xFFFFFFFF },
}); });
await admin.muteGroupAll(bridge as any, 12345, false); await admin.muteGroupAll(bridge as any, 12345, false);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[1]![4]).toMatchObject({ expect(vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value).toMatchObject({
muteState: { state: 0 }, muteState: { state: 0 },
}); });
}); });
@@ -52,7 +49,7 @@ describe('actions/group-admin', () => {
const bridge = mockBridge(); const bridge = mockBridge();
await admin.kickGroupMember(bridge as any, 12345, 67890, true, 'bad behaviour'); await admin.kickGroupMember(bridge as any, 12345, 67890, true, 'bad behaviour');
expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({ expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
groupUin: 12345, groupUin: 12345,
targetUid: 'resolved-uid', targetUid: 'resolved-uid',
rejectAddRequest: true, rejectAddRequest: true,
@@ -68,7 +65,7 @@ describe('actions/group-admin', () => {
await admin.kickGroupMembers(bridge as any, 12345, [11, 22], false); await admin.kickGroupMembers(bridge as any, 12345, [11, 22], false);
expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const payload: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value;
expect(payload.targetUids).toEqual(['uid-a', 'uid-b']); expect(payload.targetUids).toEqual(['uid-a', 'uid-b']);
expect(payload.rejectAddRequest).toBe(0); expect(payload.rejectAddRequest).toBe(0);
}); });
@@ -76,15 +73,15 @@ describe('actions/group-admin', () => {
it('leaveGroup sends 0x1097_1 with the groupUin', async () => { it('leaveGroup sends 0x1097_1 with the groupUin', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await admin.leaveGroup(bridge as any, 12345); await admin.leaveGroup(bridge as any, 12345);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0x1097_1'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1097_1');
expect(call[4]).toMatchObject({ groupUin: 12345 }); expect(call.request.value).toMatchObject({ groupUin: 12345 });
}); });
it('setGroupAdmin resolves UID and sends 0x1096_1', async () => { it('setGroupAdmin resolves UID and sends 0x1096_1', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await admin.setGroupAdmin(bridge as any, 12345, 67890, true); await admin.setGroupAdmin(bridge as any, 12345, 67890, true);
expect(vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]).toMatchObject({ expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({
groupUin: 12345, uid: 'resolved-uid', isAdmin: true, groupUin: 12345, uid: 'resolved-uid', isAdmin: true,
}); });
}); });
@@ -98,7 +95,7 @@ describe('actions/group-admin', () => {
await admin.setGroupAddOption(bridge as any, 1, 2); await admin.setGroupAddOption(bridge as any, 1, 2);
await admin.setGroupSearch(bridge as any, 1); await admin.setGroupSearch(bridge as any, 1);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(call => call[1]); const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd);
expect(cmds).toEqual([ expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x8fc_3', 'OidbSvcTrpcTcp.0x8fc_3',
'OidbSvcTrpcTcp.0x89a_15', 'OidbSvcTrpcTcp.0x89a_15',
@@ -114,23 +111,23 @@ describe('actions/group-admin', () => {
await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, true, 'ok', false); await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, true, 'ok', false);
await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, false, 'no', true); await admin.setGroupAddRequest(bridge as any, 12345, 5, 1, false, 'no', true);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(call => call[1]); const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd);
expect(cmds).toEqual([ expect(cmds).toEqual([
'OidbSvcTrpcTcp.0x10c8_1', 'OidbSvcTrpcTcp.0x10c8_1',
'OidbSvcTrpcTcp.0x10c8_2', 'OidbSvcTrpcTcp.0x10c8_2',
]); ]);
const firstBody: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const firstBody: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value;
expect(firstBody.accept).toBe(1); expect(firstBody.accept).toBe(1);
expect(firstBody.body.message).toBe('ok'); expect(firstBody.body.message).toBe('ok');
const secondBody: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[1]![4]; const secondBody: any = vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value;
expect(secondBody.accept).toBe(2); expect(secondBody.accept).toBe(2);
}); });
it('getGroupAtAllRemain decodes the response and converts BigInts', async () => { it('getGroupAtAllRemain decodes the response and converts BigInts', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
canAtAll: 1, canAtAll: 1,
groupRemain: 12n, groupRemain: 12n,
uinRemain: 5n, uinRemain: 5n,
@@ -145,7 +142,7 @@ describe('actions/group-admin', () => {
it('getGroupAtAllRemain throws when the response is empty', async () => { it('getGroupAtAllRemain throws when the response is empty', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce(null); vi.mocked(oidb.runOidb).mockResolvedValueOnce(null);
await expect(admin.getGroupAtAllRemain(bridge as any, 12345)).rejects.toThrow(/empty/); await expect(admin.getGroupAtAllRemain(bridge as any, 12345)).rejects.toThrow(/empty/);
}); });
}); });
+18 -20
View File
@@ -1,9 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
vi.mock('../../src/bridge/highway/highway-client', () => ({ vi.mock('../../src/bridge/highway/highway-client', () => ({
@@ -27,15 +25,15 @@ import { mockBridge } from './_helpers';
describe('actions/group-file', () => { describe('actions/group-file', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.sendOidbAndDecode).mockClear(); vi.mocked(oidb.runOidb).mockResolvedValue({});
vi.mocked(highwayClient.fetchHighwaySession).mockClear(); vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
}); });
it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => { it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
count: { fileCount: 42, maxCount: 1000 }, count: { fileCount: 42, maxCount: 1000 },
}); });
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
@@ -44,14 +42,14 @@ describe('actions/group-file', () => {
it('fetchGroupFileCount falls back to defaults on partial response', async () => { it('fetchGroupFileCount falls back to defaults on partial response', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ count: {} }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ count: {} });
const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); const out = await groupFile.fetchGroupFileCount(bridge as any, 12345);
expect(out).toEqual({ fileCount: 0, maxCount: 10000 }); expect(out).toEqual({ fileCount: 0, maxCount: 10000 });
}); });
it('uploadGroupFile skips highway when boolFileExist is true', async () => { it('uploadGroupFile skips highway when boolFileExist is true', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { upload: {
retCode: 0, retCode: 0,
fileId: 'fid-xyz', fileId: 'fid-xyz',
@@ -66,7 +64,7 @@ describe('actions/group-file', () => {
it('uploadGroupFile runs highway PUT when boolFileExist is false', async () => { it('uploadGroupFile runs highway PUT when boolFileExist is false', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { upload: {
retCode: 0, retCode: 0,
fileId: 'fid-xyz', fileId: 'fid-xyz',
@@ -84,14 +82,14 @@ describe('actions/group-file', () => {
it('uploadGroupFile throws on missing upload response', async () => { it('uploadGroupFile throws on missing upload response', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({}); vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
.rejects.toThrow(/response missing/); .rejects.toThrow(/response missing/);
}); });
it('uploadGroupFile bubbles up OIDB retCode errors', async () => { it('uploadGroupFile bubbles up OIDB retCode errors', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { retCode: 999, retMsg: 'quota exceeded' }, upload: { retCode: 999, retMsg: 'quota exceeded' },
}); });
await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'))
@@ -112,7 +110,7 @@ describe('actions/group-file', () => {
vi.mocked(bridge.resolveUserUid) vi.mocked(bridge.resolveUserUid)
.mockResolvedValueOnce('target-uid') // target user .mockResolvedValueOnce('target-uid') // target user
.mockResolvedValueOnce('self-uid-resolved'); // self fallback .mockResolvedValueOnce('self-uid-resolved'); // self fallback
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
upload: { retCode: 0, uuid: 'fid', fileAddon: 'hash', boolFileExist: true }, upload: { retCode: 0, uuid: 'fid', fileAddon: 'hash', boolFileExist: true },
}); });
const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file'); const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file');
@@ -122,7 +120,7 @@ describe('actions/group-file', () => {
it('fetchGroupFiles paginates files + folders out of OIDB items', async () => { it('fetchGroupFiles paginates files + folders out of OIDB items', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
list: { list: {
retCode: 0, retCode: 0,
isEnd: true, isEnd: true,
@@ -141,7 +139,7 @@ describe('actions/group-file', () => {
it('fetchGroupFileUrl builds the https URL from downloadDns + hex-encoded path', async () => { it('fetchGroupFileUrl builds the https URL from downloadDns + hex-encoded path', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
download: { download: {
retCode: 0, retCode: 0,
downloadDns: 'cdn.example.com', downloadDns: 'cdn.example.com',
@@ -154,7 +152,7 @@ describe('actions/group-file', () => {
it('fetchGroupFileUrl throws when response is missing dns or url', async () => { it('fetchGroupFileUrl throws when response is missing dns or url', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
download: { retCode: 0 }, download: { retCode: 0 },
}); });
await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz')) await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz'))
@@ -163,29 +161,29 @@ describe('actions/group-file', () => {
it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => { it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode) vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ delete: { retCode: 0 } }) .mockResolvedValueOnce({ delete: { retCode: 0 } })
.mockResolvedValueOnce({ move: { retCode: 0 } }); .mockResolvedValueOnce({ move: { retCode: 0 } });
await groupFile.deleteGroupFile(bridge as any, 12345, 'fid'); await groupFile.deleteGroupFile(bridge as any, 12345, 'fid');
await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b'); await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b');
expect(vi.mocked(oidb.sendOidbAndDecode).mock.calls.map(c => c[3])).toEqual([3, 5]); expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].subCmd)).toEqual([3, 5]);
}); });
it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => { it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode) vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ create: { retcode: 0 } }) .mockResolvedValueOnce({ create: { retcode: 0 } })
.mockResolvedValueOnce({ delete: { retcode: 0 } }) .mockResolvedValueOnce({ delete: { retcode: 0 } })
.mockResolvedValueOnce({ rename: { retcode: 0 } }); .mockResolvedValueOnce({ rename: { retcode: 0 } });
await groupFile.createGroupFileFolder(bridge as any, 1, 'folder'); await groupFile.createGroupFileFolder(bridge as any, 1, 'folder');
await groupFile.deleteGroupFileFolder(bridge as any, 1, 'fid'); await groupFile.deleteGroupFileFolder(bridge as any, 1, 'fid');
await groupFile.renameGroupFileFolder(bridge as any, 1, 'fid', 'newname'); await groupFile.renameGroupFileFolder(bridge as any, 1, 'fid', 'newname');
expect(vi.mocked(oidb.sendOidbAndDecode).mock.calls.map(c => c[2])).toEqual([0x6D7, 0x6D7, 0x6D7]); expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].oidbCmd)).toEqual([0x6D7, 0x6D7, 0x6D7]);
}); });
it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => { it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValue({ vi.mocked(oidb.runOidb).mockResolvedValue({
respHead: { retCode: 0 }, respHead: { retCode: 0 },
download: { download: {
info: { domain: 'media.example.com', urlPath: '/path/x' }, info: { domain: 'media.example.com', urlPath: '/path/x' },
@@ -1,9 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
import * as oidb from '../../src/bridge/bridge-oidb'; import * as oidb from '../../src/bridge/bridge-oidb';
@@ -12,7 +10,7 @@ import { mockBridge } from './_helpers';
describe('actions/group-message', () => { describe('actions/group-message', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockClear();
}); });
it('recallGroupMessage sends to SsoGroupRecallMsg with the group sequence', async () => { it('recallGroupMessage sends to SsoGroupRecallMsg with the group sequence', async () => {
@@ -61,7 +59,7 @@ describe('actions/group-message', () => {
const bridge = mockBridge(); const bridge = mockBridge();
await msg.setGroupEssence(bridge as any, 12345, 5, 7, true); await msg.setGroupEssence(bridge as any, 12345, 5, 7, true);
await msg.setGroupEssence(bridge as any, 12345, 5, 7, false); await msg.setGroupEssence(bridge as any, 12345, 5, 7, false);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(c => c[1]); const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']); expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']);
}); });
}); });
+13 -15
View File
@@ -1,9 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
import * as oidb from '../../src/bridge/bridge-oidb'; import * as oidb from '../../src/bridge/bridge-oidb';
@@ -12,43 +10,43 @@ import { mockBridge } from './_helpers';
describe('actions/interaction', () => { describe('actions/interaction', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.sendOidbAndDecode).mockClear(); vi.mocked(oidb.runOidb).mockResolvedValue({});
}); });
it('sendPoke group: groupUin set, friendUin=0', async () => { it('sendPoke group: groupUin set, friendUin=0', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await inter.sendPoke(bridge as any, true, 12345, 67890); await inter.sendPoke(bridge as any, true, 12345, 67890);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(payload).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 }); expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 });
}); });
it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => { it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await inter.sendPoke(bridge as any, false, 67890); await inter.sendPoke(bridge as any, false, 67890);
const payload: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(payload).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 }); expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 });
}); });
it('sendLike forwards target + count to 0x7e5_104', async () => { it('sendLike forwards target + count to 0x7e5_104', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await inter.sendLike(bridge as any, 10001, 3); await inter.sendLike(bridge as any, 10001, 3);
const call = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0x7e5_104'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0x7e5_104');
expect(call[4]).toMatchObject({ targetUin: 10001, count: 3 }); expect(call.request.value).toMatchObject({ targetUin: 10001, count: 3 });
}); });
it('setGroupReaction picks _1 for set and _2 for unset', async () => { it('setGroupReaction picks _1 for set and _2 for unset', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await inter.setGroupReaction(bridge as any, 12345, 99, '128516', true); await inter.setGroupReaction(bridge as any, 12345, 99, '128516', true);
await inter.setGroupReaction(bridge as any, 12345, 99, '128516', false); await inter.setGroupReaction(bridge as any, 12345, 99, '128516', false);
const cmds = vi.mocked(oidb.sendOidbAndCheck).mock.calls.map(c => c[1]); const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd);
expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']); expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']);
}); });
it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => { it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
inner: { userInfo: { uin: 10001 } }, inner: { userInfo: { uin: 10001 } },
cookie: new Uint8Array([0xCA, 0xFE]), cookie: new Uint8Array([0xCA, 0xFE]),
}); });
@@ -60,7 +58,7 @@ describe('actions/interaction', () => {
it('getEmojiLikes reports isLast=true when no cookie comes back', async () => { it('getEmojiLikes reports isLast=true when no cookie comes back', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({}); vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516'); const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516');
expect(out.users).toEqual([]); expect(out.users).toEqual([]);
expect(out.isLast).toBe(true); expect(out.isLast).toBe(true);
+8 -9
View File
@@ -1,9 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
import * as oidb from '../../src/bridge/bridge-oidb'; import * as oidb from '../../src/bridge/bridge-oidb';
@@ -12,12 +10,13 @@ import { mockBridge } from './_helpers';
describe('actions/misc', () => { describe('actions/misc', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockClear(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.runOidb).mockResolvedValue({});
}); });
it('translateEn2Zh returns dstWords when present', async () => { it('translateEn2Zh returns dstWords when present', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
translateResp: { dstWords: ['你好', '世界'] }, translateResp: { dstWords: ['你好', '世界'] },
}); });
const out = await misc.translateEn2Zh(bridge as any, ['hello', 'world']); const out = await misc.translateEn2Zh(bridge as any, ['hello', 'world']);
@@ -26,7 +25,7 @@ describe('actions/misc', () => {
it('translateEn2Zh throws on empty response', async () => { it('translateEn2Zh throws on empty response', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({}); vi.mocked(oidb.runOidb).mockResolvedValueOnce({});
await expect(misc.translateEn2Zh(bridge as any, ['hello'])) await expect(misc.translateEn2Zh(bridge as any, ['hello']))
.rejects.toThrow(/empty/); .rejects.toThrow(/empty/);
}); });
@@ -61,7 +60,7 @@ describe('actions/misc', () => {
it('clickInlineKeyboardButton returns shaped result', async () => { it('clickInlineKeyboardButton returns shaped result', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
result: 1, errMsg: 'ok', promptText: 'hi', result: 1, errMsg: 'ok', promptText: 'hi',
}); });
const out = await misc.clickInlineKeyboardButton(bridge as any, 1, 2, 'btn', 'data', 100); const out = await misc.clickInlineKeyboardButton(bridge as any, 1, 2, 'btn', 'data', 100);
@@ -71,7 +70,7 @@ describe('actions/misc', () => {
it('sendGroupSign dispatches to 0xEB7_1', async () => { it('sendGroupSign dispatches to 0xEB7_1', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await misc.sendGroupSign(bridge as any, 12345); await misc.sendGroupSign(bridge as any, 12345);
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0xEB7_1'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0xEB7_1');
}); });
}); });
+14 -16
View File
@@ -1,9 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndCheck: vi.fn(async () => undefined), runOidb: vi.fn(async () => ({})),
sendOidbAndDecode: vi.fn(async () => ({})),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
vi.mock('../../src/bridge/highway/highway-client', () => ({ vi.mock('../../src/bridge/highway/highway-client', () => ({
@@ -24,8 +22,8 @@ import { mockBridge } from './_helpers';
describe('actions/profile', () => { describe('actions/profile', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndCheck).mockClear(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(oidb.sendOidbAndDecode).mockClear(); vi.mocked(oidb.runOidb).mockResolvedValue({});
vi.mocked(highwayClient.fetchHighwaySession).mockClear(); vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
}); });
@@ -40,30 +38,30 @@ describe('actions/profile', () => {
it('setProfile is a no-op when both arguments are undefined', async () => { it('setProfile is a no-op when both arguments are undefined', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await profile.setProfile(bridge as any); await profile.setProfile(bridge as any);
expect(oidb.sendOidbAndCheck).not.toHaveBeenCalled(); expect(oidb.runOidb).not.toHaveBeenCalled();
}); });
it('setProfile only sends non-undefined fields', async () => { it('setProfile only sends non-undefined fields', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await profile.setProfile(bridge as any, 'New Nick'); await profile.setProfile(bridge as any, 'New Nick');
expect(oidb.sendOidbAndCheck).toHaveBeenCalledOnce(); expect(oidb.runOidb).toHaveBeenCalledOnce();
const body: any = vi.mocked(oidb.sendOidbAndCheck).mock.calls[0]![4]; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(body.stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]); expect((call.request.value as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]);
}); });
it('setSelfLongNick wraps the long nick in profile tag 102', async () => { it('setSelfLongNick wraps the long nick in profile tag 102', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await profile.setSelfLongNick(bridge as any, 'hello world'); await profile.setSelfLongNick(bridge as any, 'hello world');
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect((call[4] as any).profile).toEqual({ tag: 102, value: 'hello world' }); expect((call.request.value as any).profile).toEqual({ tag: 102, value: 'hello world' });
}); });
it('setInputStatus resolves UID first and sends 0xcd4_1', async () => { it('setInputStatus resolves UID first and sends 0xcd4_1', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
await profile.setInputStatus(bridge as any, 10001, 1); await profile.setInputStatus(bridge as any, 10001, 1);
expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001);
const call = vi.mocked(oidb.sendOidbAndDecode).mock.calls[0]!; const call = vi.mocked(oidb.runOidb).mock.calls[0]![1];
expect(call[1]).toBe('OidbSvcTrpcTcp.0xcd4_1'); expect(call.cmd).toBe('OidbSvcTrpcTcp.0xcd4_1');
}); });
it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => { it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => {
@@ -77,7 +75,7 @@ describe('actions/profile', () => {
it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => { it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
userLikeInfos: [{ userLikeInfos: [{
uid: 'u', uid: 'u',
time: 1700000000n, time: 1700000000n,
@@ -92,13 +90,13 @@ describe('actions/profile', () => {
it('getProfileLike throws on empty result', async () => { it('getProfileLike throws on empty result', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ userLikeInfos: [] }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ userLikeInfos: [] });
await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/); await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/);
}); });
it('getUnidirectionalFriendList parses the embedded JSON body', async () => { it('getUnidirectionalFriendList parses the embedded JSON body', async () => {
const bridge = mockBridge(); const bridge = mockBridge();
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }), jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }),
}); });
const out = await profile.getUnidirectionalFriendList(bridge as any); const out = await profile.getUnidirectionalFriendList(bridge as any);
+18 -20
View File
@@ -3,9 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock the OIDB shim so we can control what `forceFetchClientKey` and // Mock the OIDB shim so we can control what `forceFetchClientKey` and
// `getPSkey` see without standing up a Bridge. // `getPSkey` see without standing up a Bridge.
vi.mock('../../src/bridge/bridge-oidb', () => ({ vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndDecode: vi.fn(async () => ({})), runOidb: vi.fn(async () => ({})),
sendOidbAndCheck: vi.fn(async () => undefined),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
})); }));
// Mock the actual HTTP cookie fetch. // Mock the actual HTTP cookie fetch.
@@ -31,10 +29,10 @@ import {
const bridge = { identity: { uin: '10001' } } as any; const bridge = { identity: { uin: '10001' } } as any;
describe('cookies — forceFetchClientKey', () => { describe('cookies — forceFetchClientKey', () => {
beforeEach(() => { vi.mocked(oidb.sendOidbAndDecode).mockReset(); }); beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); });
it('returns clientKey + keyIndex + expireTime from the OIDB response', async () => { it('returns clientKey + keyIndex + expireTime from the OIDB response', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600, clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600,
}); });
const out = await forceFetchClientKey(bridge); const out = await forceFetchClientKey(bridge);
@@ -42,17 +40,17 @@ describe('cookies — forceFetchClientKey', () => {
}); });
it('falls back to default keyIndex/expireTime when the response omits them', async () => { it('falls back to default keyIndex/expireTime when the response omits them', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck' }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck' });
const out = await forceFetchClientKey(bridge); const out = await forceFetchClientKey(bridge);
expect(out).toEqual({ clientKey: 'ck', keyIndex: '19', expireTime: '1800' }); expect(out).toEqual({ clientKey: 'ck', keyIndex: '19', expireTime: '1800' });
}); });
}); });
describe('cookies — getPSkey', () => { describe('cookies — getPSkey', () => {
beforeEach(() => { vi.mocked(oidb.sendOidbAndDecode).mockReset(); }); beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); });
it('folds pskeyItems into a domain → pskey Map', async () => { it('folds pskeyItems into a domain → pskey Map', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ vi.mocked(oidb.runOidb).mockResolvedValueOnce({
pskeyItems: [ pskeyItems: [
{ domain: 'qun.qq.com', pskey: 'psk-a' }, { domain: 'qun.qq.com', pskey: 'psk-a' },
{ domain: 'qzone.qq.com', pskey: 'psk-b' }, { domain: 'qzone.qq.com', pskey: 'psk-b' },
@@ -68,12 +66,12 @@ describe('cookies — getPSkey', () => {
describe('cookies — getCookies', () => { describe('cookies — getCookies', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockReset(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset(); vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
}); });
it('builds the ptlogin2 jump URL with the right query params', async () => { it('builds the ptlogin2 jump URL with the right query params', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({
p_skey: 'psk', p_skey: 'psk',
skey: 'sk', skey: 'sk',
@@ -90,7 +88,7 @@ describe('cookies — getCookies', () => {
}); });
it('falls back to getPSkey when p_skey is missing in the cookie response', async () => { it('falls back to getPSkey when p_skey is missing in the cookie response', async () => {
vi.mocked(oidb.sendOidbAndDecode) vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) // forceFetchClientKey .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) // forceFetchClientKey
.mockResolvedValueOnce({ // getPSkey .mockResolvedValueOnce({ // getPSkey
pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }], pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }],
@@ -102,7 +100,7 @@ describe('cookies — getCookies', () => {
}); });
it('returns whatever cookies it got if getPSkey fallback throws', async () => { it('returns whatever cookies it got if getPSkey fallback throws', async () => {
vi.mocked(oidb.sendOidbAndDecode) vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockRejectedValueOnce(new Error('pskey unavailable')); .mockRejectedValueOnce(new Error('pskey unavailable'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'sk' }); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'sk' });
@@ -114,23 +112,23 @@ describe('cookies — getCookies', () => {
describe('cookies — getSKey', () => { describe('cookies — getSKey', () => {
beforeEach(() => { beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockReset(); vi.mocked(oidb.runOidb).mockReset();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset(); vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
}); });
it('returns skey from the qzone-targeted ptlogin2 jump', async () => { it('returns skey from the qzone-targeted ptlogin2 jump', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'the-skey' }); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'the-skey' });
expect(await getSKey(bridge)).toBe('the-skey'); expect(await getSKey(bridge)).toBe('the-skey');
}); });
it('throws when clientKey comes back empty', async () => { it('throws when clientKey comes back empty', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: '' }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: '' });
await expect(getSKey(bridge)).rejects.toThrow(/clientKey is empty/); await expect(getSKey(bridge)).rejects.toThrow(/clientKey is empty/);
}); });
it('throws when the jump response omits skey', async () => { it('throws when the jump response omits skey', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
await expect(getSKey(bridge)).rejects.toThrow(/SKey is Empty/); await expect(getSKey(bridge)).rejects.toThrow(/SKey is Empty/);
}); });
@@ -149,21 +147,21 @@ describe('cookies — pure helpers', () => {
}); });
it('getCookiesStr: joins cookies with "; "', async () => { it('getCookiesStr: joins cookies with "; "', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' }); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCookiesStr(bridge, 'qun.qq.com'); const out = await getCookiesStr(bridge, 'qun.qq.com');
expect(out).toBe('p_skey=p; skey=s'); expect(out).toBe('p_skey=p; skey=s');
}); });
it('getCsrfToken: combines getSKey + getBknFromSKey', async () => { it('getCsrfToken: combines getSKey + getBknFromSKey', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'abc' }); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'abc' });
const csrf = await getCsrfToken(bridge); const csrf = await getCsrfToken(bridge);
expect(csrf).toBe(getBknFromSKey('abc')); expect(csrf).toBe(getBknFromSKey('abc'));
}); });
it('getCredentials: returns { cookies, token, csrf_token } with bkn(p_skey)', async () => { it('getCredentials: returns { cookies, token, csrf_token } with bkn(p_skey)', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' }); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCredentials(bridge, 'qun.qq.com'); const out = await getCredentials(bridge, 'qun.qq.com');
@@ -173,7 +171,7 @@ describe('cookies — pure helpers', () => {
}); });
it('getCredentials: token is 0 when no skey/p_skey available', async () => { it('getCredentials: token is 0 when no skey/p_skey available', async () => {
vi.mocked(oidb.sendOidbAndDecode) vi.mocked(oidb.runOidb)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockRejectedValueOnce(new Error('no pskey')); .mockRejectedValueOnce(new Error('no pskey'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});