From 58028123927df461acd30e12091116bf9d4a0817 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 19 May 2026 07:56:04 +0800 Subject: [PATCH] =?UTF-8?q?feat(proton):=20finish=20OIDB=20migration=20?= =?UTF-8?q?=E2=80=94=20runOidb=20on=20protobuf=5Fencode>?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the OIDB phase of the proton migration. Every consumer that talked to the OIDB service through the old runtime `makeOidbBaseSchema()` factory now goes through the compile-time generic `OidbBase` instead — proton monomorphizes the codec per call-site instantiation. @snowluma/proton — two analyzer fixes uncovered by the migration: 1. Skip queuing call-site type-args that reference an *enclosing generic function's* type parameter for monomorphization. Before this, a wrapper like export function encodeOidbEnv(env: OidbBase): Uint8Array { return protobuf_encode>(env); } would cause the analyzer to mint a literal `OidbBase__T` registry entry with `body.typeName = 'T'`, which the post-walk wire-type guard then tripped on. The enclosing-scope type params are tracked on a stack as the walker descends into FunctionDeclaration, FunctionExpression, ArrowFunction, MethodDeclaration nodes; matching call sites are skipped (the wrapper-binding path is still responsible for materialising concrete codecs at downstream call sites). 2. Register *explicitly* empty interfaces (`interface X {}`) as zero-field proto messages. OIDB has a handful of these ('this call has no meaningful response body' placeholders — Oidb0xeb7Resp, Oidb0xcd4Resp, Oidb0x112aResp, Oidb0x8a0Resp, Oidb0xf16Resp, OidbClientKeyReq). Proto3 wire allows zero-field messages, and downstream code does `protobuf_decode>` where X is one of these — the wire-type guard would otherwise trip on the missing `X` registration. Interfaces that have members but no pb-marked fields are still NOT registered. @snowluma/core — the OIDB-layer refactor itself: bridge-oidb.ts ditches the runtime ProtoSchema factory and exposes: - makeOidbEnvelope(oidbCmd, subCmd, body, isUid) pure helper - encodeOidbEnv(env) pass-through - decodeOidbEnv(bytes) pass-through - runOidb(bridge, cmd, envelopeBytes) non-generic raw `encodeOidbEnv` / `decodeOidbEnv` are pure pass-through generic wrappers — proton wrapper-binds them and substitutes every call site with the inlined `protobuf_encode_OidbBase__X` / `protobuf_decode_…` function. `runOidb` is non-generic (proton leaves it alone) so it can be mocked in tests. `makeOidbEnvelope` is plain TS — also mockable for introspection. 56 `runOidb` call sites across 11 files migrated to the new API: - bridge-contacts.ts, actions/extras.ts, actions/friend.ts, actions/group-admin.ts, actions/group-file.ts, actions/group-message.ts, actions/interaction.ts, actions/misc.ts, actions/profile.ts, web-actions/cookies.ts, highway/pipeline.ts pipeline.ts also drops `makeOidbBaseSchema(NTV2UploadRichMediaReqSchema)` and the residual `protoEncode({...}, EncodableMediaMsgInfoSchema)` — both go through proton now. Tests: - 8 test files migrated from `vi.mocked(decodeOidbEnv).mockReturnValueOnce` to `vi.mocked(runOidb).mockResolvedValueOnce(protobuf_encode>({body: …}))` — the proton substitution means the old mock layer is bypassed at build time, so the only mockable point is the bytes layer at `runOidb`. - 2 new parity tests pinning `OidbBase` ↔ legacy `makeOidbBaseSchema(InnerSchema)` byte equivalence. Verification: - @snowluma/proton: 95/95 tests pass, tsc --noEmit clean - @snowluma/core: 605/605 tests pass (network-manager.test.ts fails to load due to a missing darwin-arm64 native binary in this environment — pre-existing), tsc --noEmit clean --- packages/core/src/bridge/actions/extras.ts | 93 ++--- packages/core/src/bridge/actions/friend.ts | 58 ++- .../core/src/bridge/actions/group-admin.ts | 169 +++----- .../core/src/bridge/actions/group-file.ts | 370 ++++++++---------- .../core/src/bridge/actions/group-message.ts | 11 +- .../core/src/bridge/actions/interaction.ts | 62 ++- packages/core/src/bridge/actions/misc.ts | 44 +-- packages/core/src/bridge/actions/profile.ts | 67 ++-- packages/core/src/bridge/bridge-contacts.ts | 90 ++--- packages/core/src/bridge/bridge-oidb.ts | 171 ++++---- packages/core/src/bridge/highway/pipeline.ts | 29 +- .../core/src/bridge/web-actions/cookies.ts | 32 +- packages/core/tests/actions/extras.test.ts | 138 ++++--- packages/core/tests/actions/forward.test.ts | 5 +- packages/core/tests/actions/friend.test.ts | 30 +- .../core/tests/actions/group-admin.test.ts | 79 ++-- .../core/tests/actions/group-file.test.ts | 187 +++++---- .../core/tests/actions/group-message.test.ts | 10 +- .../core/tests/actions/interaction.test.ts | 59 ++- packages/core/tests/actions/misc.test.ts | 51 ++- packages/core/tests/actions/profile.test.ts | 71 ++-- packages/core/tests/proton-parity.test.ts | 19 + .../core/tests/web-actions/cookies.test.ts | 128 ++++-- packages/proton/src/ast/analyzer.ts | 138 ++++--- packages/proton/src/ast/collector.ts | 10 +- 25 files changed, 1144 insertions(+), 977 deletions(-) diff --git a/packages/core/src/bridge/actions/extras.ts b/packages/core/src/bridge/actions/extras.ts index 3aca81ae..ae8e2a6f 100644 --- a/packages/core/src/bridge/actions/extras.ts +++ b/packages/core/src/bridge/actions/extras.ts @@ -4,42 +4,33 @@ // the NTQQ NodeIKernel — every wire trip is one runOidb round-trip. import type { Bridge } from '../bridge'; -import { runOidb } from '../bridge-oidb'; -import { - OidbGroupTodoSchema, - OidbStrangerStatusReqSchema, - OidbStrangerStatusRespSchema, - OidbAiVoiceListReqSchema, - OidbAiVoiceListRespSchema, - OidbAiVoiceReqSchema, - OidbAiVoiceRespSchema, -} from '../proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; +import type { + OidbAiVoiceListReq, + OidbAiVoiceListResp, + OidbAiVoiceReq, + OidbAiVoiceResp, + OidbGroupTodo, + OidbStrangerStatusReq, + OidbStrangerStatusResp, +} from '../proto/proton/oidb-action'; import type { MediaIndexNode } from './shared'; // ─────────────── Group todo (0xF90) ─────────────── export async function setGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xf90_1', - oidbCmd: 0xF90, subCmd: 1, - request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } }, - }); + const env = makeOidbEnvelope(0xF90, 1, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', encodeOidbEnv(env)); } export async function completeGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xf90_2', - oidbCmd: 0xF90, subCmd: 2, - request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } }, - }); + const env = makeOidbEnvelope(0xF90, 2, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', encodeOidbEnv(env)); } export async function cancelGroupTodo(bridge: Bridge, groupId: number, msgSeq: bigint): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xf90_3', - oidbCmd: 0xF90, subCmd: 3, - request: { schema: OidbGroupTodoSchema, value: { groupUin: groupId, msgSeq } }, - }); + const env = makeOidbEnvelope(0xF90, 3, { groupUin: groupId, msgSeq }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', encodeOidbEnv(env)); } // ─────────────── Stranger online/ext status (0xFE1_2) ─────────────── @@ -60,18 +51,15 @@ export interface StrangerStatus { */ export async function getStrangerStatus(bridge: Bridge, uin: number): Promise { try { - const resp = await runOidb<{ data?: { status?: { value?: bigint | number } } }>(bridge, { - cmd: 'OidbSvcTrpcTcp.0xfe1_2', - oidbCmd: 0xFE1, subCmd: 2, - request: { - schema: OidbStrangerStatusReqSchema, - value: { uin, key: [{ key: 27372 }] }, - // Same UIN-form flag fetchUserProfile sets — without it newer - // QQ NT rejects with `[oidb] one of uid/openid is invaild`. - isUid: true, - }, - response: { schema: OidbStrangerStatusRespSchema }, - }); + const env = makeOidbEnvelope( + 0xFE1, 2, + { uin, key: [{ key: 27372 }] } as any, + // Same UIN-form flag fetchUserProfile sets — without it newer + // QQ NT rejects with `[oidb] one of uid/openid is invaild`. + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const raw = resp?.data?.status?.value; if (raw === undefined || raw === null) return null; const extBig = typeof raw === 'bigint' ? raw : BigInt(raw); @@ -110,13 +98,10 @@ export async function fetchAiVoiceList( groupId: number, chatType: AiVoiceChatType, ): Promise { - const resp = await runOidb<{ content?: AiVoiceCategory[] }>(bridge, { - cmd: 'OidbSvcTrpcTcp.0x929d_0', - oidbCmd: 0x929D, subCmd: 0, - request: { schema: OidbAiVoiceListReqSchema, value: { groupUin: groupId, chatType } }, - response: { schema: OidbAiVoiceListRespSchema }, - }); - return resp?.content ?? []; + const env = makeOidbEnvelope(0x929D, 0, { groupUin: groupId, chatType }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; + return (resp?.content as AiVoiceCategory[] | undefined) ?? []; } /** @@ -139,19 +124,13 @@ export async function fetchAiVoice( // Random 32-bit session id — server uses this to deduplicate polls. const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0; for (let i = 0; i < maxRetries; i++) { - const resp = await runOidb<{ - statusCode?: number; - msgInfo?: { msgInfoBody?: Array<{ index?: MediaIndexNode }> }; - }>(bridge, { - cmd: 'OidbSvcTrpcTcp.0x929b_0', - oidbCmd: 0x929B, subCmd: 0, - request: { - schema: OidbAiVoiceReqSchema, - value: { groupUin: groupId, voiceId, text, chatType, session: { sessionId } }, - }, - response: { schema: OidbAiVoiceRespSchema }, - }); - const node = resp?.msgInfo?.msgInfoBody?.[0]?.index; + const env = makeOidbEnvelope( + 0x929B, 0, + { groupUin: groupId, voiceId, text, chatType, session: { sessionId } }, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; + const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined; if (node) return node; } throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`); diff --git a/packages/core/src/bridge/actions/friend.ts b/packages/core/src/bridge/actions/friend.ts index 4670ecf6..c4ff1510 100644 --- a/packages/core/src/bridge/actions/friend.ts +++ b/packages/core/src/bridge/actions/friend.ts @@ -3,50 +3,41 @@ // protocol uses opaque UIDs rather than QQ uin numbers. import type { Bridge } from '../bridge'; -import { runOidb } from '../bridge-oidb'; -import { - OidbDeleteFriendSchema, - OidbFriendRequestActionSchema, - OidbSetFriendRemarkSchema, -} from '../proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv } from '../bridge-oidb'; +import type { + OidbDeleteFriend, + OidbFriendRequestAction, + OidbSetFriendRemark, +} from '../proto/proton/oidb-action'; export async function setFriendAddRequest(bridge: Bridge, uidOrFlag: string, approve: boolean): Promise { let targetUid = uidOrFlag; if (/^\d+$/.test(uidOrFlag)) { targetUid = await bridge.resolveUserUid(parseInt(uidOrFlag, 10)); } - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xb5d_44', - oidbCmd: 0xB5D, subCmd: 44, - request: { schema: OidbFriendRequestActionSchema, value: { accept: approve ? 3 : 5, targetUid } }, - }); + const env = makeOidbEnvelope(0xB5D, 44, { accept: approve ? 3 : 5, targetUid }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xb5d_44', encodeOidbEnv(env)); } export async function deleteFriend(bridge: Bridge, userId: number, block = false): Promise { const targetUid = await bridge.resolveUserUid(userId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x126b_0', - oidbCmd: 0x126B, subCmd: 0, - request: { - schema: OidbDeleteFriendSchema, - value: { - field1: { - targetUid, - field2: { - field1: 130, - field2: 109, - field3: { - field1: 8, - field2: 8, - field3: 50, - }, - }, - block, - field4: false, + const env = makeOidbEnvelope(0x126B, 0, { + field1: { + targetUid, + field2: { + field1: 130, + field2: 109, + field3: { + field1: 8, + field2: 8, + field3: 50, }, }, + block, + field4: false, }, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x126b_0', encodeOidbEnv(env)); // Refresh friend cache after deletion so subsequent reads don't // surface a ghost entry. Best-effort: a transient OIDB hiccup here @@ -56,9 +47,6 @@ export async function deleteFriend(bridge: Bridge, userId: number, block = false export async function setFriendRemark(bridge: Bridge, userId: number, remark: string): Promise { const uid = await bridge.resolveUserUid(userId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xb6e_2', - oidbCmd: 0xB6E, subCmd: 2, - request: { schema: OidbSetFriendRemarkSchema, value: { targetUid: uid, remark } }, - }); + const env = makeOidbEnvelope(0xB6E, 2, { targetUid: uid, remark }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xb6e_2', encodeOidbEnv(env)); } diff --git a/packages/core/src/bridge/actions/group-admin.ts b/packages/core/src/bridge/actions/group-admin.ts index ef59e9a1..25b2eafd 100644 --- a/packages/core/src/bridge/actions/group-admin.ts +++ b/packages/core/src/bridge/actions/group-admin.ts @@ -4,72 +4,56 @@ // so callers can grep across the two layers. import type { Bridge } from '../bridge'; -import { runOidb } from '../bridge-oidb'; -import { - Oidb0x89a_0AddOptionSchema, - Oidb0x89a_0SearchSchema, - Oidb0x8a0ReqSchema, - Oidb0x8a7ReqSchema, - Oidb0x8a7RespSchema, - OidbGroupRequestActionSchema, - OidbKickMemberSchema, - OidbLeaveGroupSchema, - OidbMuteAllSchema, - OidbMuteMemberSchema, - OidbRenameGroupSchema, - OidbRenameMemberSchema, - OidbSetAdminSchema, - OidbSpecialTitleSchema, - Oidb0xf16ReqSchema, -} from '../proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; +import type { + Oidb0x89a_0AddOption, + Oidb0x89a_0Search, + Oidb0x8a0Req, + Oidb0x8a7Req, + Oidb0x8a7Resp, + Oidb0xf16Req, + OidbGroupRequestAction, + OidbKickMember, + OidbLeaveGroup, + OidbMuteAll, + OidbMuteMember, + OidbRenameGroup, + OidbRenameMember, + OidbSetAdmin, + OidbSpecialTitle, +} from '../proto/proton/oidb-action'; // ─────────────── mute / un-mute ─────────────── export async function muteGroupMember(bridge: Bridge, groupId: number, userId: number, duration: number): Promise { const uid = await bridge.resolveUserUid(userId, groupId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x1253_1', - oidbCmd: 0x1253, subCmd: 1, - request: { - schema: OidbMuteMemberSchema, - value: { groupUin: groupId, type: 1, body: { targetUid: uid, duration } }, - }, + const env = makeOidbEnvelope(0x1253, 1, { + groupUin: groupId, type: 1, body: { targetUid: uid, duration }, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x1253_1', encodeOidbEnv(env)); } export async function muteGroupAll(bridge: Bridge, groupId: number, enable: boolean): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x89a_0', - oidbCmd: 0x89A, subCmd: 0, - request: { - schema: OidbMuteAllSchema, - value: { groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 } }, - }, + const env = makeOidbEnvelope(0x89A, 0, { + groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 }, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env)); } // ─────────────── join-policy ─────────────── export async function setGroupAddOption(bridge: Bridge, groupId: number, addType: number): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x89a_0', - oidbCmd: 0x89A, subCmd: 0, - request: { - schema: Oidb0x89a_0AddOptionSchema, - value: { groupUin: BigInt(groupId), settings: { addType }, field12: 0 }, - }, + const env = makeOidbEnvelope(0x89A, 0, { + groupUin: BigInt(groupId), settings: { addType }, field12: 0, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env)); } export async function setGroupSearch(bridge: Bridge, groupId: number): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x89a_0', - oidbCmd: 0x89A, subCmd: 0, - request: { - schema: Oidb0x89a_0SearchSchema, - value: { groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0 }, - }, + const env = makeOidbEnvelope(0x89A, 0, { + groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', encodeOidbEnv(env)); } export async function setGroupAddRequest( @@ -78,92 +62,64 @@ export async function setGroupAddRequest( ): Promise { const subCmd = filtered ? 2 : 1; const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1'; - await runOidb(bridge, { - cmd, - oidbCmd: 0x10C8, subCmd, - request: { - schema: OidbGroupRequestActionSchema, - value: { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } }, - isUid: true, - }, - }); + const env = makeOidbEnvelope( + 0x10C8, subCmd, + { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } }, + true, + ); + await runOidb(bridge, cmd, encodeOidbEnv(env)); } // ─────────────── kick / leave ─────────────── export async function kickGroupMember(bridge: Bridge, groupId: number, userId: number, reject: boolean, reason = ''): Promise { const uid = await bridge.resolveUserUid(userId, groupId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x8a0_1', - oidbCmd: 0x8A0, subCmd: 1, - request: { - schema: OidbKickMemberSchema, - value: { groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason }, - }, + const env = makeOidbEnvelope(0x8A0, 1, { + groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', encodeOidbEnv(env)); } export async function kickGroupMembers(bridge: Bridge, groupId: number, userIds: number[], reject: boolean): Promise { const targetUids = await Promise.all(userIds.map(userId => bridge.resolveUserUid(userId, groupId))); - await runOidb(bridge, { - 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 }, - }, + const env = makeOidbEnvelope(0x8A0, 1, { + groupId: BigInt(groupId), targetUids, rejectAddRequest: reject ? 1 : 0, kickReason: new Uint8Array(0), field12: 0, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', encodeOidbEnv(env)); } export async function leaveGroup(bridge: Bridge, groupId: number): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x1097_1', - oidbCmd: 0x1097, subCmd: 1, - request: { schema: OidbLeaveGroupSchema, value: { groupUin: groupId } }, - }); + const env = makeOidbEnvelope(0x1097, 1, { groupUin: groupId }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x1097_1', encodeOidbEnv(env)); } // ─────────────── role / display name ─────────────── export async function setGroupAdmin(bridge: Bridge, groupId: number, userId: number, enable: boolean): Promise { const uid = await bridge.resolveUserUid(userId, groupId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x1096_1', - oidbCmd: 0x1096, subCmd: 1, - request: { schema: OidbSetAdminSchema, value: { groupUin: groupId, uid, isAdmin: enable } }, - }); + const env = makeOidbEnvelope(0x1096, 1, { groupUin: groupId, uid, isAdmin: enable }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x1096_1', encodeOidbEnv(env)); } export async function setGroupCard(bridge: Bridge, groupId: number, userId: number, card: string): Promise { const uid = await bridge.resolveUserUid(userId, groupId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x8fc_3', - oidbCmd: 0x8FC, subCmd: 3, - request: { - schema: OidbRenameMemberSchema, - value: { groupUin: groupId, body: { targetUid: uid, targetName: card } }, - }, + const env = makeOidbEnvelope(0x8FC, 3, { + groupUin: groupId, body: { targetUid: uid, targetName: card }, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_3', encodeOidbEnv(env)); } export async function setGroupName(bridge: Bridge, groupId: number, name: string): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x89a_15', - oidbCmd: 0x89A, subCmd: 15, - request: { schema: OidbRenameGroupSchema, value: { groupUin: groupId, body: { targetName: name } } }, - }); + const env = makeOidbEnvelope(0x89A, 15, { groupUin: groupId, body: { targetName: name } }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_15', encodeOidbEnv(env)); } export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, userId: number, title: string): Promise { const uid = await bridge.resolveUserUid(userId, groupId); - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x8fc_2', - oidbCmd: 0x8FC, subCmd: 2, - request: { - schema: OidbSpecialTitleSchema, - value: { groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 } }, - }, + const env = makeOidbEnvelope(0x8FC, 2, { + groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 }, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_2', encodeOidbEnv(env)); } // ─────────────── personal-side metadata ─────────────── @@ -172,11 +128,8 @@ export async function setGroupSpecialTitle(bridge: Bridge, groupId: number, user // here rather than in friend.ts because the semantic is "operate on a // group" rather than "operate on a contact list". export async function setGroupRemark(bridge: Bridge, groupId: number, remark: string): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xf16_1', - oidbCmd: 0xF16, subCmd: 1, - request: { schema: Oidb0xf16ReqSchema, value: { inner: { groupId: BigInt(groupId), remark }, field12: 0 } }, - }); + const env = makeOidbEnvelope(0xF16, 1, { inner: { groupId: BigInt(groupId), remark }, field12: 0 }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xf16_1', encodeOidbEnv(env)); } // ─────────────── group-level quota query ─────────────── @@ -194,12 +147,9 @@ export async function getGroupAtAllRemain( type: 0, }; - const result = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x8a7_0', - oidbCmd: 0x8A7, subCmd: 0, - request: { schema: Oidb0x8a7ReqSchema, value: req }, - response: { schema: Oidb0x8a7RespSchema }, - }); + const env = makeOidbEnvelope(0x8A7, 0, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a7_0', encodeOidbEnv(env)); + const result = decodeOidbEnv(respBytes).body; if (!result) { throw new Error('get group at all remain result empty'); @@ -213,4 +163,3 @@ export async function getGroupAtAllRemain( remain_at_all_count_for_uin: Number(result.uinRemain || 0), }; } - diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts index 1db541e4..2408904a 100644 --- a/packages/core/src/bridge/actions/group-file.ts +++ b/packages/core/src/bridge/actions/group-file.ts @@ -7,25 +7,25 @@ import type { Bridge } from '../bridge'; import { protobuf_encode } from '@snowluma/proton'; -import { runOidb } from '../bridge-oidb'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils'; -import { - OidbGroupFileCountViewReqSchema, - OidbGroupFileCountViewRespSchema, - OidbGroupFileFolderReqSchema, - OidbGroupFileFolderRespSchema, - OidbGroupFileReqSchema, - OidbGroupFileRespSchema, - OidbGroupFileViewReqSchema, - OidbGroupFileViewRespSchema, - OidbPrivateFileDownloadReqSchema, - OidbPrivateFileDownloadRespSchema, - OidbPrivateFileUploadReqSchema, - OidbPrivateFileUploadRespSchema, - NTV2RichMediaReqSchema, - NTV2RichMediaRespSchema, -} from '../proto/oidb-action'; +import type { + OidbGroupFileCountViewReq, + OidbGroupFileCountViewResp, + OidbGroupFileFolderReq, + OidbGroupFileFolderResp, + OidbGroupFileReq, + OidbGroupFileResp, + OidbGroupFileViewReq, + OidbGroupFileViewResp, + OidbPrivateFileDownloadReq, + OidbPrivateFileDownloadResp, + OidbPrivateFileUploadReq, + OidbPrivateFileUploadResp, + NTV2RichMediaReq, + NTV2RichMediaResp, +} from '../proto/proton/oidb-action'; import type { FileUploadExt } from '../proto/proton/highway'; import { toHexUpper } from '../../utils/hex'; import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared'; @@ -242,12 +242,9 @@ async function fetchNtv2DownloadUrl( oidbCmd: number, payload: Record, ): Promise { - const resp = await runOidb(bridge, { - cmd: serviceCmd, - oidbCmd, subCmd: 200, - request: { schema: NTV2RichMediaReqSchema, value: payload, isUid: true }, - response: { schema: NTV2RichMediaRespSchema }, - }); + const env = makeOidbEnvelope(oidbCmd, 200, payload as any, true); + const respBytes = await runOidb(bridge, serviceCmd, encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined); const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : ''; @@ -263,15 +260,12 @@ async function fetchNtv2DownloadUrl( // ─────────────── file count ─────────────── export async function fetchGroupFileCount(bridge: Bridge, groupId: number): Promise<{ fileCount: number; maxCount: number }> { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d8_3', - oidbCmd: 0x6D8, subCmd: 3, - request: { - schema: OidbGroupFileCountViewReqSchema, - value: { count: { groupUin: groupId, appId: 7, busId: 0 } }, - }, - response: { schema: OidbGroupFileCountViewRespSchema }, - }); + const env = makeOidbEnvelope( + 0x6D8, 3, + { count: { groupUin: groupId, appId: 7, busId: 0 } }, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_3', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; return { fileCount: toInt(resp?.count?.fileCount ?? 0), maxCount: toInt(resp?.count?.maxCount ?? 10000), @@ -296,31 +290,28 @@ export async function uploadGroupFile( const fileName = normalizeUploadFileName(name, loaded.fileName); const hashes = computeHashes(loaded.bytes); - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d6_0', - oidbCmd: 0x6D6, subCmd: 0, - request: { - schema: OidbGroupFileReqSchema, - value: { - file: { - groupUin: groupId, - appId: 4, - busId: 102, - entrance: 6, - targetDirectory: normalizeDirectory(folderId), - fileName, - localDirectory: `/${fileName}`, - fileSize: BigInt(loaded.bytes.length), - fileSha1: hashes.sha1, - fileSha3: new Uint8Array(0), - fileMd5: hashes.md5, - field15: true, - }, + const env = makeOidbEnvelope( + 0x6D6, 0, + { + file: { + groupUin: groupId, + appId: 4, + busId: 102, + entrance: 6, + targetDirectory: normalizeDirectory(folderId), + fileName, + localDirectory: `/${fileName}`, + fileSize: BigInt(loaded.bytes.length), + fileSha1: hashes.sha1, + fileSha3: new Uint8Array(0), + fileMd5: hashes.md5, + field15: true, }, - isUid: true, }, - response: { schema: OidbGroupFileRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_0', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const upload = resp?.upload; if (!upload) throw new Error('group file upload response missing'); @@ -389,32 +380,26 @@ export async function uploadPrivateFile( const fileName = normalizeUploadFileName(name, loaded.fileName); const hashes = computeHashes(loaded.bytes); - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xe37_1700', - oidbCmd: 0xE37, subCmd: 1700, - request: { - schema: OidbPrivateFileUploadReqSchema, - value: { - command: 1700, - seq: 0, - upload: { - senderUid: selfUid, - receiverUid: targetUid, - fileSize: loaded.bytes.length, - fileName, - md510MCheckSum: md5First10MB(loaded.bytes), - sha1CheckSum: hashes.sha1, - localPath: '/', - md5CheckSum: hashes.md5, - sha3CheckSum: new Uint8Array(0), - }, - businessId: 3, - clientType: 1, - flagSupportMediaPlatform: 1, - }, + const env = makeOidbEnvelope(0xE37, 1700, { + command: 1700, + seq: 0, + upload: { + senderUid: selfUid, + receiverUid: targetUid, + fileSize: loaded.bytes.length, + fileName, + md510MCheckSum: md5First10MB(loaded.bytes), + sha1CheckSum: hashes.sha1, + localPath: '/', + md5CheckSum: hashes.md5, + sha3CheckSum: new Uint8Array(0), }, - response: { schema: OidbPrivateFileUploadRespSchema }, + businessId: 3, + clientType: 1, + flagSupportMediaPlatform: 1, }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1700', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const upload = resp?.upload; if (!upload) throw new Error('private file upload response missing'); @@ -463,27 +448,24 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId const pageSize = 20; let startIndex = 0; for (let page = 0; page < 200; page++) { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d8_1', - oidbCmd: 0x6D8, subCmd: 1, - request: { - schema: OidbGroupFileViewReqSchema, - value: { - list: { - groupUin: groupId, - appId: 7, - targetDirectory, - fileCount: pageSize, - sortBy: 1, - startIndex, - field17: 2, - field18: 0, - }, + const env = makeOidbEnvelope( + 0x6D8, 1, + { + list: { + groupUin: groupId, + appId: 7, + targetDirectory, + fileCount: pageSize, + sortBy: 1, + startIndex, + field17: 2, + field18: 0, }, - isUid: true, }, - response: { schema: OidbGroupFileViewRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_1', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const list = resp?.list; if (!list) break; @@ -538,23 +520,20 @@ export async function fetchGroupFiles(bridge: Bridge, groupId: number, folderId // ─────────────── url fetch (group / private files) ─────────────── export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: string, busId = 102): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d6_2', - oidbCmd: 0x6D6, subCmd: 2, - request: { - schema: OidbGroupFileReqSchema, - value: { - download: { - groupUin: groupId, - appId: 7, - busId, - fileId, - }, + const env = makeOidbEnvelope( + 0x6D6, 2, + { + download: { + groupUin: groupId, + appId: 7, + busId, + fileId, }, - isUid: true, }, - response: { schema: OidbGroupFileRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_2', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const download = resp?.download; if (!download) throw new Error('group file url response missing'); @@ -574,29 +553,23 @@ export async function fetchGroupFileUrl(bridge: Bridge, groupId: number, fileId: export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId: string, fileHash: string): Promise { const uid = await bridge.resolveUserUid(userId); - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xe37_1200', - oidbCmd: 0xE37, subCmd: 1200, - request: { - schema: OidbPrivateFileDownloadReqSchema, - value: { - subCommand: 1200, - field2: 1, - body: { - receiverUid: uid, - fileUuid: fileId, - type: 2, - fileHash, - t2: 0, - }, - field101: 3, - field102: 103, - field200: 1, - field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), - }, + const env = makeOidbEnvelope(0xE37, 1200, { + subCommand: 1200, + field2: 1, + body: { + receiverUid: uid, + fileUuid: fileId, + type: 2, + fileHash, + t2: 0, }, - response: { schema: OidbPrivateFileDownloadRespSchema }, + field101: 3, + field102: 103, + field200: 1, + field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1200', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.body?.result; const server = typeof result?.server === 'string' ? result.server : ''; @@ -611,22 +584,19 @@ export async function fetchPrivateFileUrl(bridge: Bridge, userId: number, fileId // ─────────────── delete / move ─────────────── export async function deleteGroupFile(bridge: Bridge, groupId: number, fileId: string): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d6_3', - oidbCmd: 0x6D6, subCmd: 3, - request: { - schema: OidbGroupFileReqSchema, - value: { - delete: { - groupUin: groupId, - busId: 102, - fileId, - }, + const env = makeOidbEnvelope( + 0x6D6, 3, + { + delete: { + groupUin: groupId, + busId: 102, + fileId, }, - isUid: true, }, - response: { schema: OidbGroupFileRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_3', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.delete; if (!result) throw new Error('group file delete response missing'); @@ -640,25 +610,22 @@ export async function moveGroupFile( parentDirectory: string, targetDirectory: string, ): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d6_5', - oidbCmd: 0x6D6, subCmd: 5, - request: { - schema: OidbGroupFileReqSchema, - value: { - move: { - groupUin: groupId, - appId: 7, - busId: 102, - fileId, - parentDirectory, - targetDirectory, - }, + const env = makeOidbEnvelope( + 0x6D6, 5, + { + move: { + groupUin: groupId, + appId: 7, + busId: 102, + fileId, + parentDirectory, + targetDirectory, }, - isUid: true, }, - response: { schema: OidbGroupFileRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_5', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.move; if (!result) throw new Error('group file move response missing'); @@ -668,22 +635,19 @@ export async function moveGroupFile( // ─────────────── folders ─────────────── export async function createGroupFileFolder(bridge: Bridge, groupId: number, name: string, parentId = '/'): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d7_0', - oidbCmd: 0x6D7, subCmd: 0, - request: { - schema: OidbGroupFileFolderReqSchema, - value: { - create: { - groupUin: groupId, - rootDirectory: normalizeDirectory(parentId), - folderName: name, - }, + const env = makeOidbEnvelope( + 0x6D7, 0, + { + create: { + groupUin: groupId, + rootDirectory: normalizeDirectory(parentId), + folderName: name, }, - isUid: true, }, - response: { schema: OidbGroupFileFolderRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_0', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.create; if (!result) throw new Error('group folder create response missing'); @@ -691,21 +655,18 @@ export async function createGroupFileFolder(bridge: Bridge, groupId: number, nam } export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, folderId: string): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d7_1', - oidbCmd: 0x6D7, subCmd: 1, - request: { - schema: OidbGroupFileFolderReqSchema, - value: { - delete: { - groupUin: groupId, - folderId, - }, + const env = makeOidbEnvelope( + 0x6D7, 1, + { + delete: { + groupUin: groupId, + folderId, }, - isUid: true, }, - response: { schema: OidbGroupFileFolderRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_1', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.delete; if (!result) throw new Error('group folder delete response missing'); @@ -713,22 +674,19 @@ export async function deleteGroupFileFolder(bridge: Bridge, groupId: number, fol } export async function renameGroupFileFolder(bridge: Bridge, groupId: number, folderId: string, newFolderName: string): Promise { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x6d7_2', - oidbCmd: 0x6D7, subCmd: 2, - request: { - schema: OidbGroupFileFolderReqSchema, - value: { - rename: { - groupUin: groupId, - folderId, - newFolderName, - }, + const env = makeOidbEnvelope( + 0x6D7, 2, + { + rename: { + groupUin: groupId, + folderId, + newFolderName, }, - isUid: true, }, - response: { schema: OidbGroupFileFolderRespSchema }, - }); + true, + ); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_2', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const result = resp?.rename; if (!result) throw new Error('group folder rename response missing'); diff --git a/packages/core/src/bridge/actions/group-message.ts b/packages/core/src/bridge/actions/group-message.ts index 7419e244..13da8dc2 100644 --- a/packages/core/src/bridge/actions/group-message.ts +++ b/packages/core/src/bridge/actions/group-message.ts @@ -5,13 +5,13 @@ import type { Bridge } from '../bridge'; import { protoEncode } from '../../protobuf/decode'; -import { runOidb } from '../bridge-oidb'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv } from '../bridge-oidb'; import { C2CRecallRequestSchema, GroupRecallRequestSchema, - OidbEssenceSchema, SsoReadedReportReqSchema, } from '../proto/oidb-action'; +import type { OidbEssence } from '../proto/proton/oidb-action'; export async function recallGroupMessage(bridge: Bridge, groupId: number, sequence: number): Promise { const request = protoEncode({ @@ -96,9 +96,6 @@ export async function markGroupMessageRead( export async function setGroupEssence(bridge: Bridge, groupId: number, sequence: number, random: number, enable: boolean): Promise { const subCmd = enable ? 1 : 2; const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2'; - await runOidb(bridge, { - cmd, - oidbCmd: 0xEAC, subCmd, - request: { schema: OidbEssenceSchema, value: { groupUin: groupId, sequence, random } }, - }); + const env = makeOidbEnvelope(0xEAC, subCmd, { groupUin: groupId, sequence, random }); + await runOidb(bridge, cmd, encodeOidbEnv(env)); } diff --git a/packages/core/src/bridge/actions/interaction.ts b/packages/core/src/bridge/actions/interaction.ts index 5d1faf4a..17279e00 100644 --- a/packages/core/src/bridge/actions/interaction.ts +++ b/packages/core/src/bridge/actions/interaction.ts @@ -3,37 +3,28 @@ // edit message content — they're purely social signals. import type { Bridge } from '../bridge'; -import { runOidb } from '../bridge-oidb'; -import { - Oidb0x9083ReqSchema, - Oidb0x9083RespSchema, - OidbGroupReactionSchema, - OidbLikeSchema, - OidbPokeSchema, -} from '../proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; +import type { + Oidb0x9083Req, + Oidb0x9083Resp, + OidbGroupReaction, + OidbLike, + OidbPoke, +} from '../proto/proton/oidb-action'; export async function sendPoke(bridge: Bridge, isGroup: boolean, peerUin: number, targetUin?: number): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xed3_1', - oidbCmd: 0xED3, subCmd: 1, - request: { - schema: OidbPokeSchema, - value: { - uin: targetUin ?? peerUin, - groupUin: isGroup ? peerUin : 0, - friendUin: isGroup ? 0 : peerUin, - ext: 0, - }, - }, + const env = makeOidbEnvelope(0xED3, 1, { + uin: targetUin ?? peerUin, + groupUin: isGroup ? peerUin : 0, + friendUin: isGroup ? 0 : peerUin, + ext: 0, }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0xed3_1', encodeOidbEnv(env)); } export async function sendLike(bridge: Bridge, userId: number, count: number): Promise { - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x7e5_104', - oidbCmd: 0x7E5, subCmd: 104, - request: { schema: OidbLikeSchema, value: { targetUin: userId, count } }, - }); + const env = makeOidbEnvelope(0x7E5, 104, { targetUin: userId, count }); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x7e5_104', encodeOidbEnv(env)); } export async function setGroupReaction(bridge: Bridge, groupId: number, sequence: number, code: string, isSet: boolean): Promise { @@ -44,14 +35,8 @@ export async function setGroupReaction(bridge: Bridge, groupId: number, sequence // type field to pick the right resolution table; omitting it makes // unicode reactions silently fail. const type = code.length > 3 ? 2 : 1; - await runOidb(bridge, { - cmd, - oidbCmd: 0x9082, subCmd, - request: { - schema: OidbGroupReactionSchema, - value: { groupUin: groupId, sequence, code, type }, - }, - }); + const env = makeOidbEnvelope(0x9082, subCmd, { groupUin: groupId, sequence, code, type }); + await runOidb(bridge, cmd, encodeOidbEnv(env)); } export async function getEmojiLikes( @@ -63,7 +48,7 @@ export async function getEmojiLikes( count: number = 10, cookie: string = '', ): Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }> { - const req = { + const req: any = { groupId: BigInt(groupId), sequence, emojiType, @@ -73,12 +58,9 @@ export async function getEmojiLikes( count, field12: 1, }; - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x9083_1', - oidbCmd: 0x9083, subCmd: 1, - request: { schema: Oidb0x9083ReqSchema, value: req }, - response: { schema: Oidb0x9083RespSchema }, - }); + const env = makeOidbEnvelope(0x9083, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9083_1', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const uin = resp?.inner?.userInfo?.uin; const users = uin ? [{ uin: Number(uin) }] : []; const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : ''; diff --git a/packages/core/src/bridge/actions/misc.ts b/packages/core/src/bridge/actions/misc.ts index 3e0e98dd..b3b06f98 100644 --- a/packages/core/src/bridge/actions/misc.ts +++ b/packages/core/src/bridge/actions/misc.ts @@ -4,17 +4,19 @@ import type { Bridge } from '../bridge'; import { protoDecode, protoEncode } from '../../protobuf/decode'; -import { runOidb } from '../bridge-oidb'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; import { MiniAppShareReqSchema, MiniAppShareRespSchema, - Oidb0x112eReqSchema, - Oidb0x112eRespSchema, - Oidb0x990ReqSchema, - Oidb0x990RespSchema, - Oidb0xeb7ReqSchema, - Oidb0xeb7RespSchema, } from '../proto/oidb-action'; +import type { + Oidb0x112eReq, + Oidb0x112eResp, + Oidb0x990Req, + Oidb0x990Resp, + Oidb0xeb7Req, + Oidb0xeb7Resp, +} from '../proto/proton/oidb-action'; export async function translateEn2Zh( bridge: Bridge, @@ -30,12 +32,9 @@ export async function translateEn2Zh( tag12: 1, }; - const result = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x990_2', - oidbCmd: 0x990, subCmd: 2, - request: { schema: Oidb0x990ReqSchema, value: req }, - response: { schema: Oidb0x990RespSchema }, - }); + const env = makeOidbEnvelope(0x990, 2, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x990_2', encodeOidbEnv(env)); + const result = decodeOidbEnv(respBytes).body; const resp = result?.translateResp; if (!resp) { @@ -122,12 +121,9 @@ export async function clickInlineKeyboardButton( unknown9: 1, }; - const result = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x112e_1', - oidbCmd: 0x112E, subCmd: 1, - request: { schema: Oidb0x112eReqSchema, value: req }, - response: { schema: Oidb0x112eRespSchema }, - }); + const env = makeOidbEnvelope(0x112E, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112e_1', encodeOidbEnv(env)); + const result = decodeOidbEnv(respBytes).body; if (!result) { throw new Error('click inline keyboard button result empty'); @@ -155,10 +151,8 @@ export async function sendGroupSign( }, }; - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xEB7_1', - oidbCmd: 0xEB7, subCmd: 1, - request: { schema: Oidb0xeb7ReqSchema, value: req }, - response: { schema: Oidb0xeb7RespSchema }, - }); + const env = makeOidbEnvelope(0xEB7, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xEB7_1', encodeOidbEnv(env)); + // Decode just to maintain the original behaviour of "consume the response". + decodeOidbEnv(respBytes); } diff --git a/packages/core/src/bridge/actions/profile.ts b/packages/core/src/bridge/actions/profile.ts index 849e6fb6..b0284428 100644 --- a/packages/core/src/bridge/actions/profile.ts +++ b/packages/core/src/bridge/actions/profile.ts @@ -4,25 +4,27 @@ import type { Bridge } from '../bridge'; import { protoDecode, protoEncode } from '../../protobuf/decode'; -import { runOidb } from '../bridge-oidb'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; import { computeHashes, loadBinarySource } from '../highway/utils'; import { FaceroamOpReqSchema, FaceroamOpRespSchema, GroupAvatarExtraSchema, - Oidb0x112aReqSchema, - Oidb0x112aRespSchema, - Oidb0x7edReqSchema, - Oidb0x7edRespSchema, - Oidb0xcd4ReqSchema, - Oidb0xcd4RespSchema, - Oidb0xe17ReqSchema, - Oidb0xe17RespSchema, - OidbSetProfileSchema, SetStatusReqSchema, SetStatusRespSchema, } from '../proto/oidb-action'; +import type { + Oidb0x112aReq, + Oidb0x112aResp, + Oidb0x7edReq, + Oidb0x7edResp, + Oidb0xcd4Req, + Oidb0xcd4Resp, + Oidb0xe17Req, + Oidb0xe17Resp, + OidbSetProfile, +} from '../proto/proton/oidb-action'; import { resolveSelfUid } from './shared'; // ─────────────── status / profile setters ─────────────── @@ -110,11 +112,8 @@ export async function setProfile( stringProfiles, }; - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x112a_2', - oidbCmd: 0x112A, subCmd: 2, - request: { schema: OidbSetProfileSchema, value: req }, - }); + const env = makeOidbEnvelope(0x112A, 2, req); + await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', encodeOidbEnv(env)); } export async function setSelfLongNick( @@ -129,12 +128,10 @@ export async function setSelfLongNick( }, }; - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x112a_2', - oidbCmd: 0x112A, subCmd: 2, - request: { schema: Oidb0x112aReqSchema, value: req }, - response: { schema: Oidb0x112aRespSchema }, - }); + const env = makeOidbEnvelope(0x112A, 2, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', encodeOidbEnv(env)); + // Decode just to maintain the original behaviour of "consume the response". + decodeOidbEnv(respBytes); } export async function setInputStatus( @@ -156,12 +153,10 @@ export async function setInputStatus( }, }; - await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xcd4_1', - oidbCmd: 0xCD4, subCmd: 1, - request: { schema: Oidb0xcd4ReqSchema, value: req }, - response: { schema: Oidb0xcd4RespSchema }, - }); + const env = makeOidbEnvelope(0xCD4, 1, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xcd4_1', encodeOidbEnv(env)); + // Decode just to maintain the original behaviour of "consume the response". + decodeOidbEnv(respBytes); } export async function setAvatar( @@ -232,12 +227,9 @@ export async function getProfileLike( limit: limit, }; - const result = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x7ed_12', - oidbCmd: 0x7ED, subCmd: 12, - request: { schema: Oidb0x7edReqSchema, value: req }, - response: { schema: Oidb0x7edRespSchema }, - }); + const env = makeOidbEnvelope(0x7ED, 12, req); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x7ed_12', encodeOidbEnv(env)); + const result = decodeOidbEnv(respBytes).body; const data = result?.userLikeInfos?.[0]; if (!data) { @@ -277,12 +269,9 @@ export async function getUnidirectionalFriendList( jsonBody: JSON.stringify(reqObj), }; - const result = await runOidb(bridge, { - cmd: 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', - oidbCmd: 0xE17, subCmd: 0, - request: { schema: Oidb0xe17ReqSchema, value: req }, - response: { schema: Oidb0xe17RespSchema }, - }); + const env = makeOidbEnvelope(0xE17, 0, req); + const respBytes = await runOidb(bridge, 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', encodeOidbEnv(env)); + const result = decodeOidbEnv(respBytes).body; if (!result || !result.jsonBody) { throw new Error('get unidirectional friend list empty'); diff --git a/packages/core/src/bridge/bridge-contacts.ts b/packages/core/src/bridge/bridge-contacts.ts index 9e0fa6dc..54173dcf 100644 --- a/packages/core/src/bridge/bridge-contacts.ts +++ b/packages/core/src/bridge/bridge-contacts.ts @@ -4,24 +4,24 @@ import type { Bridge } from './bridge'; import type { DownloadRKeyInfo } from './bridge'; import type { FriendInfo, QQGroupInfo, GroupMemberInfo, UserProfileInfo, GroupRequestInfo } from './qq-info'; import { protoDecode } from '../protobuf/decode'; -import { runOidb } from './bridge-oidb'; -import { - OidbSvcTrpcTcp0xFD4_1ResponseSchema, - OidbSvcTrpcTcp0xFE5_2ResponseSchema, - OidbSvcTrpcTcp0xFE7_3ResponseSchema, - OidbSvcTrpcTcp0x10C0ResponseSchema, -} from './proto/oidb'; -import { - OidbFriendListRequestSchema, - OidbGroupListRequestSchema, - OidbGroupMemberListRequestSchema, - OidbUserInfoRequestSchema, - OidbUserInfoResponseSchema, - AvatarInfoSchema, - OidbGroupRequestListSchema, - NTV2RichMediaReqSchema, - NTV2RichMediaRespSchema, -} from './proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from './bridge-oidb'; +import { AvatarInfoSchema } from './proto/oidb-action'; +import type { + OidbSvcTrpcTcp0xFD4_1Response, + OidbSvcTrpcTcp0xFE5_2Response, + OidbSvcTrpcTcp0xFE7_3Response, + OidbSvcTrpcTcp0x10C0Response, +} from './proto/proton/oidb'; +import type { + OidbFriendListRequest, + OidbGroupListRequest, + OidbGroupMemberListRequest, + OidbUserInfoRequest, + OidbUserInfoResponse, + OidbGroupRequestList, + NTV2RichMediaReq, + NTV2RichMediaResp, +} from './proto/proton/oidb-action'; // --------------------------------------------------------------------------- // Helpers @@ -71,12 +71,9 @@ export async function fetchFriendList(bridge: Bridge): Promise { body.nextUin = { uin: nextUin }; } - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xfd4_1', - oidbCmd: 0xFD4, subCmd: 1, - request: { schema: OidbFriendListRequestSchema, value: body }, - response: { schema: OidbSvcTrpcTcp0xFD4_1ResponseSchema }, - }); + const env = makeOidbEnvelope(0xFD4, 1, body); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfd4_1', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; if (resp?.friends) { for (const raw of resp.friends) { @@ -137,12 +134,9 @@ export async function fetchGroupList(bridge: Bridge): Promise { }, }; - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xfe5_2', - oidbCmd: 0xFE5, subCmd: 2, - request: { schema: OidbGroupListRequestSchema, value: body, isUid: true }, - response: { schema: OidbSvcTrpcTcp0xFE5_2ResponseSchema }, - }); + const env = makeOidbEnvelope(0xFE5, 2, body, true); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe5_2', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const groups: QQGroupInfo[] = []; if (resp?.groups) { @@ -184,12 +178,9 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro }; if (token) body.token = token; - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0xfe7_3', - oidbCmd: 0xFE7, subCmd: 3, - request: { schema: OidbGroupMemberListRequestSchema, value: body }, - response: { schema: OidbSvcTrpcTcp0xFE7_3ResponseSchema }, - }); + const env = makeOidbEnvelope(0xFE7, 3, body); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe7_3', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; if (resp?.members) { for (const raw of resp.members) { @@ -234,12 +225,9 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise(bridge, { - cmd: 'OidbSvcTrpcTcp.0xfe1_2', - oidbCmd: 0xFE1, subCmd: 2, - request: { schema: OidbUserInfoRequestSchema, value: body, isUid: true }, - response: { schema: OidbUserInfoResponseSchema }, - }); + const env = makeOidbEnvelope(0xFE1, 2, body, true); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; if (!resp?.body) throw new Error('user info response body missing'); @@ -291,12 +279,9 @@ export async function fetchUserProfile(bridge: Bridge, uin: number): Promise { const subCmd = filtered ? 2 : 1; const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1'; - const resp = await runOidb(bridge, { - cmd, - oidbCmd: 0x10C0, subCmd, - request: { schema: OidbGroupRequestListSchema, value: { count: 20, field2: 0 } }, - response: { schema: OidbSvcTrpcTcp0x10C0ResponseSchema }, - }); + const env = makeOidbEnvelope(0x10C0, subCmd, { count: 20, field2: 0 }); + const respBytes = await runOidb(bridge, cmd, encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const requests: GroupRequestInfo[] = []; for (const raw of resp?.requests ?? []) { @@ -343,12 +328,9 @@ export async function fetchDownloadRKeys(bridge: Bridge): Promise(bridge, { - cmd: 'OidbSvcTrpcTcp.0x9067_202', - oidbCmd: 0x9067, subCmd: 202, - request: { schema: NTV2RichMediaReqSchema, value: body, isUid: true }, - response: { schema: NTV2RichMediaRespSchema }, - }); + const env = makeOidbEnvelope(0x9067, 202, body, true); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9067_202', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) { throw new Error(resp.respHead.message ?? 'fetch download rkey failed'); diff --git a/packages/core/src/bridge/bridge-oidb.ts b/packages/core/src/bridge/bridge-oidb.ts index 23e71579..cdd5c76e 100644 --- a/packages/core/src/bridge/bridge-oidb.ts +++ b/packages/core/src/bridge/bridge-oidb.ts @@ -1,96 +1,101 @@ -// 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. +// One deep entry point for a single OIDB round-trip: dispatch a +// pre-encoded envelope via Bridge.sendRawPacket, validate the envelope +// retCode, and return the raw response bytes. +// +// History note. The legacy implementation used a runtime +// `makeOidbBaseSchema(InnerSchema)` factory and ran a runtime +// schema-walking encoder. Proton is compile-time, so the envelope is +// the generic interface `OidbBase` (proto/proton/oidb.ts). Proton's +// wrapper-binding requires *pass-through* wrappers (the wrapper's first +// arg must be forwarded unchanged to the inner codec — see +// proton/src/transform/replacer.ts), so this file exposes thin +// pass-through helpers (`encodeOidbEnv` / `decodeOidbEnv`) that +// proton monomorphizes at every call site. `runOidb` itself is +// non-generic — it just sends pre-encoded bytes and peeks at the +// envelope retCode via the non-generic `OidbBaseMeta` view. import type { Bridge } from './bridge'; -import type { ProtoSchema } from '../protobuf/decode'; -import { protoEncode, protoDecode } from '../protobuf/decode'; -import { makeOidbBaseSchema } from './proto/oidb'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; +import type { OidbBase, OidbBaseMeta } from './proto/proton/oidb'; -export interface OidbCall { - /** 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; - /** - * Sets the OIDB envelope `reserved` field to 1 when true. - * - * The name is historical and misleading: empirically (see Lagrange - * FetchStrangerByUin vs FetchStrangerByUid, fetchGroupList, our own - * highway uploads) the `reserved = 1` flag indicates the UIN-form - * variant of an OIDB call — it tells newer QQ NT to translate the - * UIN in the body to an internal UID rather than running the - * UID-form validator that expects a uid/openid string in the body. - * - * Omit (default false) for genuinely UID-keyed calls. - */ - isUid?: boolean; - }; - /** Omit to skip decoding the response body (fire-and-check). */ - response?: { - schema: ProtoSchema; +/** + * Build the OidbBase-shaped TS value. Pure helper, no protobuf + * encoding happens here — pair with `encodeOidbEnv` to produce the + * wire bytes. + * + * The `isUid` flag sets the envelope `reserved` field to 1; despite the + * name (kept for back-compat with the legacy API), `reserved = 1` + * empirically signals the UIN-form variant of an OIDB call. Omit + * (default false) for genuinely UID-keyed calls. + */ +export function makeOidbEnvelope( + oidbCmd: number, + subCmd: number, + body: T, + isUid: boolean = false, +): OidbBase { + return { + command: oidbCmd, + subCommand: subCmd, + errorCode: 0, + body, + errorMsg: '', + reserved: isUid ? 1 : 0, }; } /** - * 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. + * Pass-through encoder for the OIDB envelope. Single type param, body + * literally forwards its arg to `protobuf_encode>` — proton + * wrapper-binds this and replaces every `encodeOidbEnv(env)` call + * site with `protobuf_encode_OidbBase__MyReq(env)` at build time. */ -export function runOidb(bridge: Bridge, call: OidbCall & { response?: undefined }): Promise; -export function runOidb(bridge: Bridge, call: OidbCall & { response: { schema: ProtoSchema } }): Promise; -export async function runOidb(bridge: Bridge, call: OidbCall): Promise { - const envelope = encodeOidbEnvelope(call); - const result = await bridge.sendRawPacket(call.cmd, envelope); +export function encodeOidbEnv(env: OidbBase): Uint8Array { + return protobuf_encode>(env); +} + +/** + * Pass-through decoder for the OIDB envelope. Mirror of `encodeOidbEnv` + * — proton monomorphizes `OidbBase` per call site. + * + * Returns the full envelope; the caller usually wants `.body`. + */ +export function decodeOidbEnv(bytes: Uint8Array): OidbBase { + return protobuf_decode>(bytes); +} + +/** + * Issue one OIDB request and return the raw response bytes. + * + * Typical usage: + * const env = makeOidbEnvelope(0x1253, 1, value); + * const buf = await runOidb(bridge, cmd, encodeOidbEnv(env)); + * const resp = decodeOidbEnv(buf).body; + * + * Fire-and-check (no body decode): + * await runOidb(bridge, cmd, encodeOidbEnv(env)); + * + * Always peeks at the envelope errorCode via the non-generic + * `OidbBaseMeta` view so a server-side rejection cannot slip past + * silently. Returns the raw response bytes (empty `Uint8Array` if the + * packet carried no payload). + */ +export async function runOidb( + bridge: Bridge, + cmd: string, + envelopeBytes: Uint8Array, +): Promise { + const result = await bridge.sendRawPacket(cmd, envelopeBytes); 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.responseData && result.responseData.length > 0) { - const emptyBase = makeOidbBaseSchema({ _dummy: { field: 99, type: 'uint32' as const } }); - const resp = protoDecode(result.responseData, emptyBase); - if (resp) throwIfOidbError(resp); - } -} -function encodeOidbEnvelope(call: OidbCall): Uint8Array { - const baseSchema = makeOidbBaseSchema(call.request.schema); - return protoEncode({ - command: call.oidbCmd, - subCommand: call.subCmd, - errorCode: 0, - body: call.request.value, - errorMsg: '', - reserved: call.request.isUid ? 1 : 0, - }, baseSchema); -} - -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 ?? ''}`); + const bytes = result.responseData ?? new Uint8Array(0); + if (bytes.length > 0) { + const meta = protobuf_decode(bytes); + const code = meta?.errorCode; + if (code && code !== 0) { + throw new Error(`OIDB error ${code}: ${meta?.errorMsg ?? ''}`); + } } + return bytes; } diff --git a/packages/core/src/bridge/highway/pipeline.ts b/packages/core/src/bridge/highway/pipeline.ts index b04b6b32..86b0be53 100644 --- a/packages/core/src/bridge/highway/pipeline.ts +++ b/packages/core/src/bridge/highway/pipeline.ts @@ -17,13 +17,13 @@ import crypto from 'crypto'; import type { Bridge } from '../bridge'; -import { protoDecode, protoEncode } from '../../protobuf/decode'; -import { makeOidbBaseSchema } from '../proto/oidb'; -import { - EncodableMediaMsgInfoSchema, - NTV2UploadRichMediaReqSchema, - NTV2UploadRichMediaRespSchema, -} from '../proto/highway'; +import { protobuf_encode } from '@snowluma/proton'; +import { makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; +import type { + EncodableMediaMsgInfo, + NTV2UploadRichMediaReq, + NTV2UploadRichMediaResp, +} from '../proto/proton/highway'; import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client'; import { createLogger } from '../../utils/logger'; @@ -159,24 +159,21 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise { }, }; - const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaReqSchema); - const request = protoEncode({ - command: oidbCmd, subCommand: 100, errorCode: 0, body, errorMsg: '', reserved: 1, - }, baseSchema); + const env = makeOidbEnvelope(oidbCmd, 100, body, true); + const requestBytes = encodeOidbEnv(env); - const result = await bridge.sendRawPacket(serviceCmd, request); + const result = await bridge.sendRawPacket(serviceCmd, requestBytes); if (!result.success || !result.gotResponse || !result.responseData) { throw new Error(result.errorMessage || `${label} upload request failed`); } - const respBaseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema); - const resp: any = protoDecode(result.responseData, respBaseSchema); + const resp = decodeOidbEnv(result.responseData); if (!resp) throw new Error(`failed to decode ${label} upload response`); if (resp.errorCode && resp.errorCode !== 0) { throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`); } - const uploadBody = resp.body; + const uploadBody: any = resp.body; if (!uploadBody) throw new Error(`${label} upload response body missing`); if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) { throw new Error(uploadBody.respHead.message ?? `${label} upload failed`); @@ -262,5 +259,5 @@ export function finalizeMediaMsgInfo( extBizInfo.busiType = upload.msgInfo.extBizInfo.busiType; } - return protoEncode({ msgInfoBody, extBizInfo }, EncodableMediaMsgInfoSchema); + return protobuf_encode({ msgInfoBody, extBizInfo }); } diff --git a/packages/core/src/bridge/web-actions/cookies.ts b/packages/core/src/bridge/web-actions/cookies.ts index 65bc37cf..fb398d79 100644 --- a/packages/core/src/bridge/web-actions/cookies.ts +++ b/packages/core/src/bridge/web-actions/cookies.ts @@ -4,22 +4,19 @@ // thread the cookies into a qun.qq.com REST endpoint. import type { Bridge } from '../bridge'; -import { runOidb } from '../bridge-oidb'; -import { - OidbClientKeyRespSchema, - OidbClientKeyReqSchema, - OidbGetPskeyReqSchema, - OidbGetPskeyRespSchema, -} from '../proto/oidb-action'; +import { runOidb, makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../bridge-oidb'; +import type { + OidbClientKeyReq, + OidbClientKeyResp, + OidbGetPskeyReq, + OidbGetPskeyResp, +} from '../proto/proton/oidb-action'; import { RequestUtil } from '../web/request-util'; export async function forceFetchClientKey(bridge: Bridge) { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x102a_1', - oidbCmd: 0x102A, subCmd: 1, - request: { schema: OidbClientKeyReqSchema, value: {} }, - response: { schema: OidbClientKeyRespSchema }, - }); + const env = makeOidbEnvelope(0x102A, 1, {}); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_1', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const clientKey = resp?.clientKey || ''; // keyIndex falls back to "19" — origin unknown but the value is what @@ -34,12 +31,9 @@ export async function forceFetchClientKey(bridge: Bridge) { } export async function getPSkey(bridge: Bridge, domainList: string[]) { - const resp = await runOidb(bridge, { - cmd: 'OidbSvcTrpcTcp.0x102a_0', - oidbCmd: 0x102A, subCmd: 0, - request: { schema: OidbGetPskeyReqSchema, value: { domainList } }, - response: { schema: OidbGetPskeyRespSchema }, - }); + const env = makeOidbEnvelope(0x102A, 0, { domainList }); + const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_0', encodeOidbEnv(env)); + const resp = decodeOidbEnv(respBytes).body; const domainPskeyMap = new Map(); diff --git a/packages/core/tests/actions/extras.test.ts b/packages/core/tests/actions/extras.test.ts index eca813a8..0278be45 100644 --- a/packages/core/tests/actions/extras.test.ts +++ b/packages/core/tests/actions/extras.test.ts @@ -1,19 +1,38 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { + OidbStrangerStatusResp, + OidbAiVoiceListResp, + OidbAiVoiceResp, +} from '../../src/bridge/proto/proton/oidb-action'; -// Same stub-the-oidb-runner pattern as actions/group-admin.test.ts — -// we don't care about wire bytes, just that each function targets the -// right cmd / subCmd / schema. -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// that the plugin substitutes at the call site with the inlined codec, so +// mocking them on the module object is a no-op. The only mockable point +// is `runOidb` (non-generic, untouched by proton) returning real bytes +// that the production-side codec then decodes. `makeOidbEnvelope` is a +// pure TS helper, so its mock works for introspection. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); import * as oidb from '../../src/bridge/bridge-oidb'; import * as extras from '../../src/bridge/actions/extras'; -import * as schemas from '../../src/bridge/proto/oidb-action'; import { mockBridge } from './_helpers'; describe('actions/extras / group todo (0xF90)', () => { - beforeEach(() => vi.mocked(oidb.runOidb).mockClear()); + beforeEach(() => { + vi.mocked(oidb.runOidb).mockClear(); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); + }); it.each([ ['setGroupTodo', extras.setGroupTodo, 'OidbSvcTrpcTcp.0xf90_1', 1], @@ -22,32 +41,41 @@ describe('actions/extras / group todo (0xF90)', () => { ] as const)('%s dispatches the right subCmd with shared body', async (_name, fn, cmd, subCmd) => { const bridge = mockBridge(); await fn(bridge as any, 12345, 9876543210n); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe(cmd); - expect(call.oidbCmd).toBe(0xF90); - expect(call.subCmd).toBe(subCmd); - expect(call.request.schema).toBe(schemas.OidbGroupTodoSchema); - expect(call.request.value).toEqual({ groupUin: 12345, msgSeq: 9876543210n }); + const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(runCmd).toBe(cmd); + const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!; + expect(oidbCmd).toBe(0xF90); + expect(sub).toBe(subCmd); + expect(body).toEqual({ groupUin: 12345, msgSeq: 9876543210n }); }); }); describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { - beforeEach(() => vi.mocked(oidb.runOidb).mockClear()); + beforeEach(() => { + vi.mocked(oidb.runOidb).mockReset(); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); + }); it('issues the FE1_2 query with key=27372', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 5n } } } as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { data: { status: { value: 5n } } } }), + ); await extras.getStrangerStatus(bridge as any, 100200); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0xfe1_2'); - expect(call.oidbCmd).toBe(0xFE1); - expect(call.subCmd).toBe(2); - expect(call.request.value).toMatchObject({ uin: 100200, key: [{ key: 27372 }] }); + const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(runCmd).toBe('OidbSvcTrpcTcp.0xfe1_2'); + const [oidbCmd, sub, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!; + expect(oidbCmd).toBe(0xFE1); + expect(sub).toBe(2); + expect(body).toMatchObject({ uin: 100200, key: [{ key: 27372 }] }); }); it('low-band values (≤10) map to status*10 with ext_status=0', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 7n } } } as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { data: { status: { value: 7n } } } }), + ); expect(await extras.getStrangerStatus(bridge as any, 1)).toEqual({ status: 70, ext_status: 0 }); }); @@ -56,7 +84,9 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { // value 0x42F100: bits 8-15 (the 0xff00 mask) = 0xF100; // bits 16-23 (>>16 & 0xff) = 0x42. // ext_status = 0xF100 + 0x42 = 0xF142. - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ data: { status: { value: 0x42F100n } } } as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { data: { status: { value: 0x42F100n } } } }), + ); const status = await extras.getStrangerStatus(bridge as any, 1); expect(status).toEqual({ status: 10, ext_status: 0xF142 }); }); @@ -69,58 +99,74 @@ describe('actions/extras / getStrangerStatus (0xFE1_2)', () => { it('returns null when the server omits the status field', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({} as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); expect(await extras.getStrangerStatus(bridge as any, 1)).toBeNull(); }); }); describe('actions/extras / AI voice (0x929D / 0x929B)', () => { - beforeEach(() => vi.mocked(oidb.runOidb).mockClear()); + beforeEach(() => { + vi.mocked(oidb.runOidb).mockReset(); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); + }); it('fetchAiVoiceList sends 0x929D_0 and returns server content verbatim', async () => { const bridge = mockBridge(); const fake = [ { category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] }, ]; - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ content: fake } as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { content: fake } } as any), + ); const out = await extras.fetchAiVoiceList(bridge as any, 4242, extras.AiVoiceChatType.Sound); expect(out).toEqual(fake); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x929d_0'); - expect(call.request.value).toEqual({ groupUin: 4242, chatType: 1 }); + const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(runCmd).toBe('OidbSvcTrpcTcp.0x929d_0'); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toEqual({ groupUin: 4242, chatType: 1 }); }); it('fetchAiVoiceList returns [] when server replies with no content', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({} as any); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); const out = await extras.fetchAiVoiceList(bridge as any, 1, 1 as any); expect(out).toEqual([]); }); it('fetchAiVoice retries while msgInfo is empty, returns the first IndexNode it sees', async () => { const bridge = mockBridge(); - const node = { fileUuid: 'uuid-1', subType: 0 }; + // subType is non-zero so proto3 doesn't omit it from the wire (the + // re-decoded object must include the field for the matcher to spot it). + const node = { fileUuid: 'uuid-1', subType: 1 }; vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ statusCode: 2 } as any) - .mockResolvedValueOnce({ msgInfo: { msgInfoBody: [] } } as any) - .mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any); + .mockResolvedValueOnce(protobuf_encode>({ body: { statusCode: 2 } })) + .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [] } } as any })) + .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })); const out = await extras.fetchAiVoice(bridge as any, 100, 'voice-id', 'hi', extras.AiVoiceChatType.Sound); - expect(out).toBe(node); + expect(out).toMatchObject(node); expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x929b_0'); - expect(call.request.value).toMatchObject({ + const [, runCmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(runCmd).toBe('OidbSvcTrpcTcp.0x929b_0'); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2] as any; + expect(body).toMatchObject({ groupUin: 100, voiceId: 'voice-id', text: 'hi', chatType: 1, }); // sessionId is randomized but must be a uint32. - expect((call.request.value as any).session.sessionId).toBeTypeOf('number'); - expect((call.request.value as any).session.sessionId).toBeGreaterThanOrEqual(0); - expect((call.request.value as any).session.sessionId).toBeLessThanOrEqual(0xFFFFFFFF); + expect(body.session.sessionId).toBeTypeOf('number'); + expect(body.session.sessionId).toBeGreaterThanOrEqual(0); + expect(body.session.sessionId).toBeLessThanOrEqual(0xFFFFFFFF); }); it('fetchAiVoice throws after exhausting the retry budget', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValue({ statusCode: 1 } as any); + vi.mocked(oidb.runOidb).mockResolvedValue( + protobuf_encode>({ body: { statusCode: 1 } }), + ); await expect(extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any, 3)).rejects.toThrow( /AI voice synthesis did not complete/, ); @@ -131,11 +177,11 @@ describe('actions/extras / AI voice (0x929D / 0x929B)', () => { const bridge = mockBridge(); const node = { fileUuid: 'uuid', subType: 0 }; vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({} as any) - .mockResolvedValueOnce({ msgInfo: { msgInfoBody: [{ index: node }] } } as any); + .mockResolvedValueOnce(protobuf_encode>({ body: {} })) + .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })); await extras.fetchAiVoice(bridge as any, 1, 'v', 't', 1 as any); - const first = (vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value as any).session.sessionId; - const second = (vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value as any).session.sessionId; + const first = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2] as any).session.sessionId; + const second = (vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2] as any).session.sessionId; expect(first).toBe(second); }); }); diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index 72f82931..2e63e515 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -1,7 +1,10 @@ import { describe, it, expect, vi } from 'vitest'; vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + encodeOidbEnv: vi.fn(() => new Uint8Array()), + decodeOidbEnv: vi.fn(() => ({ body: {} })), })); // element-builder reaches into protoEncode with element-specific schemas diff --git a/packages/core/tests/actions/friend.test.ts b/packages/core/tests/actions/friend.test.ts index a190096c..919cd5ae 100644 --- a/packages/core/tests/actions/friend.test.ts +++ b/packages/core/tests/actions/friend.test.ts @@ -1,7 +1,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + encodeOidbEnv: vi.fn(() => new Uint8Array()), + decodeOidbEnv: vi.fn(() => ({ body: {} })), })); import * as oidb from '../../src/bridge/bridge-oidb'; @@ -11,31 +14,35 @@ import { mockBridge } from './_helpers'; describe('actions/friend', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockClear(); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); + vi.mocked(oidb.encodeOidbEnv).mockClear(); + vi.mocked(oidb.decodeOidbEnv).mockClear(); }); it('setFriendAddRequest: numeric input is treated as UIN and resolved', async () => { const bridge = mockBridge(); await friend.setFriendAddRequest(bridge as any, '10001', true); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.request.value).toMatchObject({ accept: 3, targetUid: 'resolved-uid' }); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ accept: 3, targetUid: 'resolved-uid' }); }); it('setFriendAddRequest: non-numeric flag is forwarded as-is', async () => { const bridge = mockBridge(); await friend.setFriendAddRequest(bridge as any, 'flag-abc', false); expect(bridge.resolveUserUid).not.toHaveBeenCalled(); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.request.value).toMatchObject({ accept: 5, targetUid: 'flag-abc' }); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ accept: 5, targetUid: 'flag-abc' }); }); it('deleteFriend resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => { const bridge = mockBridge(); await friend.deleteFriend(bridge as any, 10001, true); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x126b_0'); - expect((call.request.value as any).field1.block).toBe(true); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x126b_0'); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect((body as any).field1.block).toBe(true); expect(bridge.fetchFriendList).toHaveBeenCalled(); }); @@ -50,8 +57,9 @@ describe('actions/friend', () => { it('setFriendRemark resolves UID and sends 0xb6e_2', async () => { const bridge = mockBridge(); await friend.setFriendRemark(bridge as any, 10001, 'best-friend'); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0xb6e_2'); - expect(call.request.value).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' }); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0xb6e_2'); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' }); }); }); diff --git a/packages/core/tests/actions/group-admin.test.ts b/packages/core/tests/actions/group-admin.test.ts index cc2f0cb2..a7e0c5c7 100644 --- a/packages/core/tests/actions/group-admin.test.ts +++ b/packages/core/tests/actions/group-admin.test.ts @@ -1,10 +1,24 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { Oidb0x8a7Resp } from '../../src/bridge/proto/proton/oidb-action'; -// Stub the OIDB shim so we can assert WHICH command + payload each -// action constructs without booting a real Bridge / native pipe. -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// that the plugin substitutes at the call site with the inlined codec, so +// mocking them on the module object is a no-op. The only mockable point +// is `runOidb` (non-generic, untouched by proton) returning real bytes +// that the production-side codec then decodes. `makeOidbEnvelope` is a +// pure TS helper, so its mock works for introspection. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); import * as oidb from '../../src/bridge/bridge-oidb'; import * as admin from '../../src/bridge/actions/group-admin'; @@ -12,7 +26,9 @@ import { mockBridge } from './_helpers'; describe('actions/group-admin', () => { beforeEach(() => { - vi.mocked(oidb.runOidb).mockClear(); + vi.mocked(oidb.runOidb).mockReset(); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); }); it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => { @@ -20,11 +36,12 @@ describe('actions/group-admin', () => { await admin.muteGroupMember(bridge as any, 12345, 67890, 600); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345); expect(oidb.runOidb).toHaveBeenCalledOnce(); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1253_1'); - expect(call.oidbCmd).toBe(0x1253); - expect(call.subCmd).toBe(1); - expect(call.request.value).toMatchObject({ + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x1253_1'); + const [oidbCmd, subCmd, body] = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]!; + expect(oidbCmd).toBe(0x1253); + expect(subCmd).toBe(1); + expect(body).toMatchObject({ groupUin: 12345, type: 1, body: { targetUid: 'resolved-uid', duration: 600 }, @@ -34,13 +51,13 @@ describe('actions/group-admin', () => { it('muteGroupAll flips the muteState flag based on enable', async () => { const bridge = mockBridge(); await admin.muteGroupAll(bridge as any, 12345, true); - expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({ + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345, muteState: { state: 0xFFFFFFFF }, }); await admin.muteGroupAll(bridge as any, 12345, false); - expect(vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value).toMatchObject({ + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2]).toMatchObject({ muteState: { state: 0 }, }); }); @@ -49,7 +66,7 @@ describe('actions/group-admin', () => { const bridge = mockBridge(); await admin.kickGroupMember(bridge as any, 12345, 67890, true, 'bad behaviour'); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345); - expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({ + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345, targetUid: 'resolved-uid', rejectAddRequest: true, @@ -65,7 +82,7 @@ describe('actions/group-admin', () => { await admin.kickGroupMembers(bridge as any, 12345, [11, 22], false); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); - const payload: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value; + const payload: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect(payload.targetUids).toEqual(['uid-a', 'uid-b']); expect(payload.rejectAddRequest).toBe(0); }); @@ -73,15 +90,15 @@ describe('actions/group-admin', () => { it('leaveGroup sends 0x1097_1 with the groupUin', async () => { const bridge = mockBridge(); await admin.leaveGroup(bridge as any, 12345); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x1097_1'); - expect(call.request.value).toMatchObject({ groupUin: 12345 }); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x1097_1'); + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345 }); }); it('setGroupAdmin resolves UID and sends 0x1096_1', async () => { const bridge = mockBridge(); await admin.setGroupAdmin(bridge as any, 12345, 67890, true); - expect(vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value).toMatchObject({ + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345, uid: 'resolved-uid', isAdmin: true, }); }); @@ -95,7 +112,7 @@ describe('actions/group-admin', () => { await admin.setGroupAddOption(bridge as any, 1, 2); await admin.setGroupSearch(bridge as any, 1); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd); + const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]); expect(cmds).toEqual([ 'OidbSvcTrpcTcp.0x8fc_3', 'OidbSvcTrpcTcp.0x89a_15', @@ -111,27 +128,27 @@ 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, false, 'no', true); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1].cmd); + const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]); expect(cmds).toEqual([ 'OidbSvcTrpcTcp.0x10c8_1', 'OidbSvcTrpcTcp.0x10c8_2', ]); - const firstBody: any = vi.mocked(oidb.runOidb).mock.calls[0]![1].request.value; + const firstBody: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; expect(firstBody.accept).toBe(1); expect(firstBody.body.message).toBe('ok'); - const secondBody: any = vi.mocked(oidb.runOidb).mock.calls[1]![1].request.value; + const secondBody: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2]; expect(secondBody.accept).toBe(2); }); it('getGroupAtAllRemain decodes the response and converts BigInts', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - canAtAll: 1, - groupRemain: 12n, - uinRemain: 5n, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { canAtAll: true, groupRemain: 12, uinRemain: 5 } as any, + }), + ); const out = await admin.getGroupAtAllRemain(bridge as any, 12345); expect(out).toEqual({ can_at_all: true, @@ -142,7 +159,11 @@ describe('actions/group-admin', () => { it('getGroupAtAllRemain throws when the response is empty', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce(null); + // An empty OidbBase envelope (no body) — production code sees `body` + // undefined and throws the "empty" error. + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({}), + ); await expect(admin.getGroupAtAllRemain(bridge as any, 12345)).rejects.toThrow(/empty/); }); }); diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 2f71bc76..2a10edd9 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -1,8 +1,30 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { + OidbGroupFileCountViewResp, + OidbGroupFileResp, + OidbGroupFileViewResp, + OidbPrivateFileUploadResp, + OidbGroupFileFolderResp, + NTV2RichMediaResp, +} from '../../src/bridge/proto/proton/oidb-action'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// (substituted at the call site with the inlined codec). Mocking them on +// the module object is a no-op — proton has already inlined the call. +// We mock `runOidb` (non-generic, proton leaves it alone) to return real +// proton-encoded bytes, which the production-side codec then decodes. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); vi.mock('../../src/bridge/highway/highway-client', () => ({ fetchHighwaySession: vi.fn(async () => ({})), @@ -27,36 +49,45 @@ import { mockBridge } from './_helpers'; describe('actions/group-file', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue({}); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); vi.mocked(highwayClient.fetchHighwaySession).mockClear(); vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); }); it('fetchGroupFileCount returns { fileCount, maxCount } from the OIDB response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - count: { fileCount: 42, maxCount: 1000 }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { count: { fileCount: 42, maxCount: 1000 } }, + }), + ); const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); expect(out).toEqual({ fileCount: 42, maxCount: 1000 }); }); it('fetchGroupFileCount falls back to defaults on partial response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ count: {} }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { count: {} } }), + ); const out = await groupFile.fetchGroupFileCount(bridge as any, 12345); expect(out).toEqual({ fileCount: 0, maxCount: 10000 }); }); it('uploadGroupFile skips highway when boolFileExist is true', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - upload: { - retCode: 0, - fileId: 'fid-xyz', - boolFileExist: true, - }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + upload: { + // retCode 0 omitted by proto3 — production only checks against nonzero + fileId: 'fid-xyz', + boolFileExist: true, + }, + } as any, + }), + ); const out = await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); expect(out).toEqual({ fileId: 'fid-xyz' }); expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled(); @@ -65,17 +96,21 @@ describe('actions/group-file', () => { it('uploadGroupFile runs highway PUT when boolFileExist is false', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - upload: { - retCode: 0, - fileId: 'fid-xyz', - boolFileExist: false, - uploadIp: '1.2.3.4', - uploadPort: 8080, - fileKey: new Uint8Array([9]), - checkKey: new Uint8Array([8]), - }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + upload: { + fileId: 'fid-xyz', + // boolFileExist is the proto3 default (false) — omit, production + // sees undefined which the helper treats as "must upload via highway". + uploadIp: '1.2.3.4', + uploadPort: 8080, + fileKey: new Uint8Array([9]), + checkKey: new Uint8Array([8]), + }, + } as any, + }), + ); await groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin'); expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce(); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); @@ -83,16 +118,20 @@ describe('actions/group-file', () => { it('uploadGroupFile throws on missing upload response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({}); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) .rejects.toThrow(/response missing/); }); it('uploadGroupFile bubbles up OIDB retCode errors', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - upload: { retCode: 999, retMsg: 'quota exceeded' }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { retCode: 999, retMsg: 'quota exceeded' } as any }, + }), + ); await expect(groupFile.uploadGroupFile(bridge as any, 12345, '/path/file.bin')) .rejects.toThrow(/code=999/); }); @@ -111,9 +150,11 @@ describe('actions/group-file', () => { vi.mocked(bridge.resolveUserUid) .mockResolvedValueOnce('target-uid') // target user .mockResolvedValueOnce('self-uid-resolved'); // self fallback - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - upload: { retCode: 0, uuid: 'fid', fileAddon: 'hash', boolFileExist: true }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { upload: { uuid: 'fid', fileAddon: 'hash', boolFileExist: true } as any }, + }), + ); const out = await groupFile.uploadPrivateFile(bridge as any, 67890, '/path/file'); expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' }); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); @@ -121,16 +162,19 @@ describe('actions/group-file', () => { it('fetchGroupFiles paginates files + folders out of OIDB items', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - list: { - retCode: 0, - isEnd: true, - items: [ - { type: 1, fileInfo: { fileId: 'f1', fileName: 'a.txt', uploaderUin: 1, uploaderName: 'alice' } }, - { type: 2, folderInfo: { folderId: 'd1', folderName: 'dir', creatorUin: 2, creatorName: 'bob' } }, - ], - }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + list: { + isEnd: true, + items: [ + { type: 1, fileInfo: { fileId: 'f1', fileName: 'a.txt', uploaderUin: 1, uploaderName: 'alice' } }, + { type: 2, folderInfo: { folderId: 'd1', folderName: 'dir', creatorUin: 2, creatorName: 'bob' } }, + ], + } as any, + }, + }), + ); const out = await groupFile.fetchGroupFiles(bridge as any, 12345); expect(out.files).toHaveLength(1); expect(out.files[0]).toMatchObject({ fileId: 'f1', fileName: 'a.txt', uploader: 1, uploaderName: 'alice' }); @@ -140,22 +184,27 @@ describe('actions/group-file', () => { it('fetchGroupFileUrl builds the https URL from downloadDns + hex-encoded path', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - download: { - retCode: 0, - downloadDns: 'cdn.example.com', - downloadUrl: new Uint8Array([0x01, 0x02]), - }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + download: { + downloadDns: 'cdn.example.com', + downloadUrl: new Uint8Array([0x01, 0x02]), + } as any, + }, + }), + ); const url = await groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz'); expect(url).toBe('https://cdn.example.com/ftn_handler/0102/?fname=fid-xyz'); }); it('fetchGroupFileUrl throws when response is missing dns or url', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - download: { retCode: 0 }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { download: {} as any }, + }), + ); await expect(groupFile.fetchGroupFileUrl(bridge as any, 12345, 'fid-xyz')) .rejects.toThrow(/invalid/); }); @@ -163,34 +212,38 @@ describe('actions/group-file', () => { it('deleteGroupFile / moveGroupFile dispatch the right sub-commands', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ delete: { retCode: 0 } }) - .mockResolvedValueOnce({ move: { retCode: 0 } }); + .mockResolvedValueOnce(protobuf_encode>({ body: { delete: {} as any } })) + .mockResolvedValueOnce(protobuf_encode>({ body: { move: {} as any } })); await groupFile.deleteGroupFile(bridge as any, 12345, 'fid'); await groupFile.moveGroupFile(bridge as any, 12345, 'fid', '/a', '/b'); - expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].subCmd)).toEqual([3, 5]); + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[1])).toEqual([3, 5]); }); it('createGroupFileFolder / deleteGroupFileFolder / renameGroupFileFolder dispatch 0x6d7 family', async () => { const bridge = mockBridge(); vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ create: { retcode: 0 } }) - .mockResolvedValueOnce({ delete: { retcode: 0 } }) - .mockResolvedValueOnce({ rename: { retcode: 0 } }); + .mockResolvedValueOnce(protobuf_encode>({ body: { create: {} as any } })) + .mockResolvedValueOnce(protobuf_encode>({ body: { delete: {} as any } })) + .mockResolvedValueOnce(protobuf_encode>({ body: { rename: {} as any } })); await groupFile.createGroupFileFolder(bridge as any, 1, 'folder'); await groupFile.deleteGroupFileFolder(bridge as any, 1, 'fid'); await groupFile.renameGroupFileFolder(bridge as any, 1, 'fid', 'newname'); - expect(vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].oidbCmd)).toEqual([0x6D7, 0x6D7, 0x6D7]); + expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[0])).toEqual([0x6D7, 0x6D7, 0x6D7]); }); it('fetch*UrlByNode builds https://domain/path?rkey from the NTV2 response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValue({ - respHead: { retCode: 0 }, - download: { - info: { domain: 'media.example.com', urlPath: '/path/x' }, - rKeyParam: '?rkey=abc', - }, - }); + vi.mocked(oidb.runOidb).mockResolvedValue( + protobuf_encode>({ + body: { + respHead: {}, + download: { + info: { domain: 'media.example.com', urlPath: '/path/x' }, + rKeyParam: '?rkey=abc', + } as any, + } as any, + }), + ); const url = await groupFile.fetchGroupVideoUrlByNode(bridge as any, 12345, { fileUuid: 'uuid' }); expect(url).toBe('https://media.example.com/path/x?rkey=abc'); }); diff --git a/packages/core/tests/actions/group-message.test.ts b/packages/core/tests/actions/group-message.test.ts index 5c50b90c..95281197 100644 --- a/packages/core/tests/actions/group-message.test.ts +++ b/packages/core/tests/actions/group-message.test.ts @@ -1,7 +1,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + encodeOidbEnv: vi.fn(() => new Uint8Array()), + decodeOidbEnv: vi.fn(() => ({ body: {} })), })); import * as oidb from '../../src/bridge/bridge-oidb'; @@ -11,6 +14,9 @@ import { mockBridge } from './_helpers'; describe('actions/group-message', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockClear(); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); + vi.mocked(oidb.encodeOidbEnv).mockClear(); + vi.mocked(oidb.decodeOidbEnv).mockClear(); }); it('recallGroupMessage sends to SsoGroupRecallMsg with the group sequence', async () => { @@ -59,7 +65,7 @@ describe('actions/group-message', () => { const bridge = mockBridge(); await msg.setGroupEssence(bridge as any, 12345, 5, 7, true); await msg.setGroupEssence(bridge as any, 12345, 5, 7, false); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd); + const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]); expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']); }); }); diff --git a/packages/core/tests/actions/interaction.test.ts b/packages/core/tests/actions/interaction.test.ts index b12a89c5..feace71a 100644 --- a/packages/core/tests/actions/interaction.test.ts +++ b/packages/core/tests/actions/interaction.test.ts @@ -1,8 +1,25 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { Oidb0x9083Resp } from '../../src/bridge/proto/proton/oidb-action'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// that the plugin substitutes at the call site for the inlined codec. +// That means production calls to them NEVER hit the imported function — +// mocking them on the module object is a no-op. The only mockable point +// is `runOidb` (non-generic, untouched by proton) returning real bytes +// that the production-side codec actually decodes. `makeOidbEnvelope` is +// a pure TS helper, so its mock works for introspection. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); import * as oidb from '../../src/bridge/bridge-oidb'; import * as inter from '../../src/bridge/actions/interaction'; @@ -11,45 +28,51 @@ import { mockBridge } from './_helpers'; describe('actions/interaction', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue({}); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); }); it('sendPoke group: groupUin set, friendUin=0', async () => { const bridge = mockBridge(); await inter.sendPoke(bridge as any, true, 12345, 67890); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 }); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 }); }); it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => { const bridge = mockBridge(); await inter.sendPoke(bridge as any, false, 67890); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.request.value).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 }); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 }); }); it('sendLike forwards target + count to 0x7e5_104', async () => { const bridge = mockBridge(); await inter.sendLike(bridge as any, 10001, 3); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0x7e5_104'); - expect(call.request.value).toMatchObject({ targetUin: 10001, count: 3 }); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x7e5_104'); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect(body).toMatchObject({ targetUin: 10001, count: 3 }); }); it('setGroupReaction picks _1 for set and _2 for unset', async () => { const bridge = mockBridge(); await inter.setGroupReaction(bridge as any, 12345, 99, '128516', true); await inter.setGroupReaction(bridge as any, 12345, 99, '128516', false); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1].cmd); + const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]); expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']); }); it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - inner: { userInfo: { uin: 10001 } }, - cookie: new Uint8Array([0xCA, 0xFE]), - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + inner: { userInfo: { uin: 10001n } }, + cookie: new Uint8Array([0xCA, 0xFE]), + } as any, + }), + ); const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516'); expect(out.users).toEqual([{ uin: 10001 }]); expect(out.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64')); @@ -58,7 +81,9 @@ describe('actions/interaction', () => { it('getEmojiLikes reports isLast=true when no cookie comes back', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({}); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); const out = await inter.getEmojiLikes(bridge as any, 12345, 99, '128516'); expect(out.users).toEqual([]); expect(out.isLast).toBe(true); diff --git a/packages/core/tests/actions/misc.test.ts b/packages/core/tests/actions/misc.test.ts index 05a30962..09efd6e2 100644 --- a/packages/core/tests/actions/misc.test.ts +++ b/packages/core/tests/actions/misc.test.ts @@ -1,8 +1,26 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { + Oidb0x990Resp, + Oidb0x112eResp, +} from '../../src/bridge/proto/proton/oidb-action'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// — the plugin substitutes them at the call site with the inlined codec, +// so mocking them on the module object is a no-op. We mock `runOidb` +// (non-generic, untouched by proton) to return real proton-encoded bytes +// that the production-side codec then actually decodes. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); import * as oidb from '../../src/bridge/bridge-oidb'; import * as misc from '../../src/bridge/actions/misc'; @@ -11,21 +29,26 @@ import { mockBridge } from './_helpers'; describe('actions/misc', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue({}); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); }); it('translateEn2Zh returns dstWords when present', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - translateResp: { dstWords: ['你好', '世界'] }, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { translateResp: { dstWords: ['你好', '世界'] } } as any, + }), + ); const out = await misc.translateEn2Zh(bridge as any, ['hello', 'world']); expect(out).toEqual(['你好', '世界']); }); it('translateEn2Zh throws on empty response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({}); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); await expect(misc.translateEn2Zh(bridge as any, ['hello'])) .rejects.toThrow(/empty/); }); @@ -60,9 +83,11 @@ describe('actions/misc', () => { it('clickInlineKeyboardButton returns shaped result', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - result: 1, errMsg: 'ok', promptText: 'hi', - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { result: 1, errMsg: 'ok', promptText: 'hi' } as any, + }), + ); const out = await misc.clickInlineKeyboardButton(bridge as any, 1, 2, 'btn', 'data', 100); expect(out).toMatchObject({ result: 1, errMsg: 'ok', promptText: 'hi', status: 0 }); }); @@ -70,7 +95,7 @@ describe('actions/misc', () => { it('sendGroupSign dispatches to 0xEB7_1', async () => { const bridge = mockBridge(); await misc.sendGroupSign(bridge as any, 12345); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0xEB7_1'); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0xEB7_1'); }); }); diff --git a/packages/core/tests/actions/profile.test.ts b/packages/core/tests/actions/profile.test.ts index 52feb3f2..6ec45f46 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -1,8 +1,26 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { + Oidb0x7edResp, + Oidb0xe17Resp, +} from '../../src/bridge/proto/proton/oidb-action'; -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// (substituted at the call site with the inlined codec). Mocking them on +// the module object is a no-op — proton has already inlined the call. +// We mock `runOidb` (non-generic) to return real proton-encoded bytes +// that the production-side codec actually decodes. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); vi.mock('../../src/bridge/highway/highway-client', () => ({ fetchHighwaySession: vi.fn(async () => ({})), @@ -23,7 +41,8 @@ import { mockBridge } from './_helpers'; describe('actions/profile', () => { beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue({}); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); vi.mocked(highwayClient.fetchHighwaySession).mockClear(); vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); }); @@ -93,23 +112,23 @@ describe('actions/profile', () => { const bridge = mockBridge(); await profile.setProfile(bridge as any, 'New Nick'); expect(oidb.runOidb).toHaveBeenCalledOnce(); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect((call.request.value as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect((body as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]); }); it('setSelfLongNick wraps the long nick in profile tag 102', async () => { const bridge = mockBridge(); await profile.setSelfLongNick(bridge as any, 'hello world'); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect((call.request.value as any).profile).toEqual({ tag: 102, value: 'hello world' }); + const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; + expect((body as any).profile).toEqual({ tag: 102, value: 'hello world' }); }); it('setInputStatus resolves UID first and sends 0xcd4_1', async () => { const bridge = mockBridge(); await profile.setInputStatus(bridge as any, 10001, 1); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); - const call = vi.mocked(oidb.runOidb).mock.calls[0]![1]; - expect(call.cmd).toBe('OidbSvcTrpcTcp.0xcd4_1'); + const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0xcd4_1'); }); it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => { @@ -155,14 +174,18 @@ describe('actions/profile', () => { it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - userLikeInfos: [{ - uid: 'u', - time: 1700000000n, - favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 }, - voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n }, - }], - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + userLikeInfos: [{ + uid: 'u', + time: 1700000000n, + favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 }, + voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n }, + }], + } as any, + }), + ); const out = await profile.getProfileLike(bridge as any); expect(out.favoriteInfo.total_count).toBe(5); expect(out.voteInfo.total_count).toBe(7); @@ -170,15 +193,19 @@ describe('actions/profile', () => { it('getProfileLike throws on empty result', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ userLikeInfos: [] }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { userLikeInfos: [] } as any }), + ); await expect(profile.getProfileLike(bridge as any)).rejects.toThrow(/empty/); }); it('getUnidirectionalFriendList parses the embedded JSON body', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }), - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }) } as any, + }), + ); const out = await profile.getUnidirectionalFriendList(bridge as any); expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]); }); diff --git a/packages/core/tests/proton-parity.test.ts b/packages/core/tests/proton-parity.test.ts index 85e966c2..a613d739 100644 --- a/packages/core/tests/proton-parity.test.ts +++ b/packages/core/tests/proton-parity.test.ts @@ -51,6 +51,7 @@ import { FileUploadExtSchema, } from '../src/bridge/proto/highway'; import { makeOidbBaseSchema, OidbSvcTrpcTcp0xFE5_2ResponseSchema } from '../src/bridge/proto/oidb'; +import { makeOidbEnvelope, encodeOidbEnv, decodeOidbEnv } from '../src/bridge/bridge-oidb'; import type { SendLongMsgResp, @@ -618,6 +619,24 @@ describe('proton ↔ legacy parity (longmsg subset)', () => { expect(hex(proton)).toBe(hex(legacy)); }); + it('encodeOidbEnv pass-through wrapper byte-equivalent to direct codec', () => { + // The bridge-oidb.ts module exposes encodeOidbEnv / decodeOidbEnv + // as pure pass-through wrappers around protobuf_encode/decode>. + // Proton wrapper-binds them and substitutes each call site with the + // monomorphized codec, so byte-output must match a direct call. + const body: OidbSvcTrpcTcp0xFE5_2Response = { + groups: [{ groupUin: 100, info: { groupName: 'G' } }], + }; + const env = makeOidbEnvelope(0xFE5, 2, body, false); + const viaWrapper = encodeOidbEnv(env); + const viaDirect = protobuf_encode>(env); + expect(hex(viaWrapper)).toBe(hex(viaDirect)); + + const back = decodeOidbEnv(viaWrapper); + expect(back.body?.groups?.[0]?.groupUin).toBe(100); + expect(back.body?.groups?.[0]?.info?.groupName).toBe('G'); + }); + it('round-trips OidbBase with non-trivial nested body', () => { const body: OidbSvcTrpcTcp0xFE5_2Response = { groups: [{ groupUin: 100, info: { groupName: 'G' } }], diff --git a/packages/core/tests/web-actions/cookies.test.ts b/packages/core/tests/web-actions/cookies.test.ts index e0ec6b56..fdf54624 100644 --- a/packages/core/tests/web-actions/cookies.test.ts +++ b/packages/core/tests/web-actions/cookies.test.ts @@ -1,10 +1,26 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '../../src/bridge/proto/proton/oidb'; +import type { + OidbClientKeyResp, + OidbGetPskeyResp, +} from '../../src/bridge/proto/proton/oidb-action'; -// Mock the OIDB shim so we can control what `forceFetchClientKey` and -// `getPSkey` see without standing up a Bridge. -vi.mock('../../src/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => ({})), -})); +// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers +// — the plugin substitutes them at the call site with the inlined codec, +// so mocking them on the module object is a no-op. We mock `runOidb` +// (non-generic, untouched by proton) to return real proton-encoded bytes +// that the production-side codec then decodes. +vi.mock('../../src/bridge/bridge-oidb', async () => { + const actual = await vi.importActual( + '../../src/bridge/bridge-oidb', + ); + return { + ...actual, + runOidb: vi.fn(async () => new Uint8Array()), + makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), + }; +}); // Mock the actual HTTP cookie fetch. vi.mock('../../src/bridge/web/request-util', () => ({ @@ -28,35 +44,54 @@ import { const bridge = { identity: { uin: '10001' } } as any; +function resetOidbMocks() { + vi.mocked(oidb.runOidb).mockReset(); + vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); + vi.mocked(oidb.makeOidbEnvelope).mockClear(); +} + +// Bake the encoded OidbBase bytes a test wants `runOidb` to return. +// Keeping these inline as `protobuf_encode>({body: ...})` +// — proton substitutes them with the inlined codec at this file's +// transform time, just like for production code. + describe('cookies — forceFetchClientKey', () => { - beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); }); + beforeEach(() => { resetOidbMocks(); }); it('returns clientKey + keyIndex + expireTime from the OIDB response', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600, - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600 } as any, + }), + ); const out = await forceFetchClientKey(bridge); expect(out).toEqual({ clientKey: 'ck-xyz', keyIndex: '42', expireTime: '3600' }); }); it('falls back to default keyIndex/expireTime when the response omits them', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck' }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck' } as any }), + ); const out = await forceFetchClientKey(bridge); expect(out).toEqual({ clientKey: 'ck', keyIndex: '19', expireTime: '1800' }); }); }); describe('cookies — getPSkey', () => { - beforeEach(() => { vi.mocked(oidb.runOidb).mockReset(); }); + beforeEach(() => { resetOidbMocks(); }); it('folds pskeyItems into a domain → pskey Map', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ - pskeyItems: [ - { domain: 'qun.qq.com', pskey: 'psk-a' }, - { domain: 'qzone.qq.com', pskey: 'psk-b' }, - { domain: 'corrupt', pskey: '' }, - ], - }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { + pskeyItems: [ + { domain: 'qun.qq.com', pskey: 'psk-a' }, + { domain: 'qzone.qq.com', pskey: 'psk-b' }, + { domain: 'corrupt', pskey: '' }, + ], + } as any, + }), + ); const { domainPskeyMap } = await getPSkey(bridge, ['qun.qq.com', 'qzone.qq.com']); expect(domainPskeyMap.get('qun.qq.com')).toBe('psk-a'); expect(domainPskeyMap.get('qzone.qq.com')).toBe('psk-b'); @@ -66,12 +101,16 @@ describe('cookies — getPSkey', () => { describe('cookies — getCookies', () => { beforeEach(() => { - vi.mocked(oidb.runOidb).mockReset(); + resetOidbMocks(); vi.mocked(RequestUtil.HttpsGetCookies).mockReset(); }); it('builds the ptlogin2 jump URL with the right query params', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ + body: { clientKey: 'ck', keyIndex: 19 } as any, + }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'psk', skey: 'sk', @@ -89,10 +128,14 @@ describe('cookies — getCookies', () => { it('falls back to getPSkey when p_skey is missing in the cookie response', async () => { vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) // forceFetchClientKey - .mockResolvedValueOnce({ // getPSkey - pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }], - }); + .mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ) + .mockResolvedValueOnce( + protobuf_encode>({ + body: { pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }] } as any, + }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); const out = await getCookies(bridge, 'qun.qq.com'); @@ -101,7 +144,9 @@ describe('cookies — getCookies', () => { it('returns whatever cookies it got if getPSkey fallback throws', async () => { vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) + .mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ) .mockRejectedValueOnce(new Error('pskey unavailable')); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'sk' }); @@ -112,29 +157,38 @@ describe('cookies — getCookies', () => { describe('cookies — getSKey', () => { beforeEach(() => { - vi.mocked(oidb.runOidb).mockReset(); + resetOidbMocks(); vi.mocked(RequestUtil.HttpsGetCookies).mockReset(); }); it('returns skey from the qzone-targeted ptlogin2 jump', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'the-skey' }); expect(await getSKey(bridge)).toBe('the-skey'); }); it('throws when clientKey comes back empty', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: '' }); + // Empty clientKey is the proto3 default; omit so it decodes back to ''. + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: {} }), + ); await expect(getSKey(bridge)).rejects.toThrow(/clientKey is empty/); }); it('throws when the jump response omits skey', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); await expect(getSKey(bridge)).rejects.toThrow(/SKey is Empty/); }); }); describe('cookies — pure helpers', () => { + beforeEach(() => { resetOidbMocks(); }); + it('getBknFromSKey: deterministic djb2 truncated to 31 bits', () => { // Two calls on the same input → same number; different input → different. const a = getBknFromSKey('hello'); @@ -147,21 +201,27 @@ describe('cookies — pure helpers', () => { }); it('getCookiesStr: joins cookies with "; "', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' }); const out = await getCookiesStr(bridge, 'qun.qq.com'); expect(out).toBe('p_skey=p; skey=s'); }); it('getCsrfToken: combines getSKey + getBknFromSKey', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'abc' }); const csrf = await getCsrfToken(bridge); expect(csrf).toBe(getBknFromSKey('abc')); }); it('getCredentials: returns { cookies, token, csrf_token } with bkn(p_skey)', async () => { - vi.mocked(oidb.runOidb).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }); + vi.mocked(oidb.runOidb).mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' }); const out = await getCredentials(bridge, 'qun.qq.com'); @@ -172,7 +232,9 @@ describe('cookies — pure helpers', () => { it('getCredentials: token is 0 when no skey/p_skey available', async () => { vi.mocked(oidb.runOidb) - .mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) + .mockResolvedValueOnce( + protobuf_encode>({ body: { clientKey: 'ck', keyIndex: 19 } as any }), + ) .mockRejectedValueOnce(new Error('no pskey')); vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({}); diff --git a/packages/proton/src/ast/analyzer.ts b/packages/proton/src/ast/analyzer.ts index c7c1c61e..4041b0a7 100644 --- a/packages/proton/src/ast/analyzer.ts +++ b/packages/proton/src/ast/analyzer.ts @@ -107,58 +107,108 @@ export function analyze(code: string, filePath: string, imported?: ImportedDefin for (const [k, v] of imported.templates) templates.set(k, v); } + // Stack of generic-function type-param scopes. When visiting a + // `protobuf_encode/decode` call whose type arg references one of + // these (e.g. `protobuf_encode>(env)` inside + // `function encodeOidbEnv(...)`), we MUST skip monomorphization — + // the type arg only resolves once the wrapper itself is instantiated + // at a downstream call site, and that case is handled separately by + // the wrapper-binding path in `matchForwardedProtobufFn`. Without + // this skip, the analyzer would happily mint a literal `OidbBase__T` + // registry entry with a `body.typeName = 'T'` field, which the + // wire-type guard then trips on. + const enclosingTypeParamStack: Set[] = []; + function typeArgReferencesEnclosingParam(typeArg: ts.TypeNode): boolean { + if (enclosingTypeParamStack.length === 0) return false; + let found = false; + function check(n: ts.Node): void { + if (found) return; + if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) { + const name = n.typeName.text; + for (const scope of enclosingTypeParamStack) { + if (scope.has(name)) { found = true; return; } + } + } + ts.forEachChild(n, check); + } + check(typeArg); + return found; + } + function nodeIntroducesTypeParams(n: ts.Node): readonly ts.TypeParameterDeclaration[] | undefined { + if (ts.isFunctionDeclaration(n)) return n.typeParameters; + if (ts.isFunctionExpression(n)) return n.typeParameters; + if (ts.isArrowFunction(n)) return n.typeParameters; + if (ts.isMethodDeclaration(n)) return n.typeParameters; + return undefined; + } + // ── single walk ───────────────────────────────────────────────────── ts.forEachChild(sf, function visit(node) { - if (ts.isInterfaceDeclaration(node)) { - if (node.typeParameters?.length) { - const tpl = collectGenericInterface(node, sf, resolveImportedTypeName); - if (tpl) templates.set(tpl.name, tpl); - } else { - const msg = collectInterface(node, sf, resolveImportedTypeName); - if (msg) concrete.push(msg); - // Queue any generic-instantiated type-args appearing as field types - // (e.g. `wrapped: pb<5, Wrapper>`) for monomorphization. - // The call-site queue only sees the outer concrete type, so without - // this the nested instantiation would never reach the registry. - for (const ta of collectConcreteFieldGenericTypeArgs(node, resolveImportedTypeName)) { - deferredTypeArgs.push(ta); - } - } + const introduced = nodeIntroducesTypeParams(node); + const pushedScope = !!(introduced && introduced.length); + if (pushedScope) { + enclosingTypeParamStack.push(new Set(introduced!.map(p => p.name.text))); } - if (ts.isCallExpression(node)) { - const cs = matchProtobufCallSite(node, sf, importBindings, { - allowLegacyUnboundCanonical: true, - }); - if (cs) { - deferredTypeArgs.push(cs.firstTypeArg); - callSites.push(cs); - } else if ( - node.typeArguments?.length && - getCallableName(node.expression) && - wrapperBindings.has(getCallableName(node.expression)!) - ) { - const binding = wrapperBindings.get(getCallableName(node.expression)!)!; - const firstTypeArg = instantiateWrapperTypePattern(binding, node.typeArguments, sf); - if (!firstTypeArg) { - ts.forEachChild(node, visit); - return; + try { + if (ts.isInterfaceDeclaration(node)) { + if (node.typeParameters?.length) { + const tpl = collectGenericInterface(node, sf, resolveImportedTypeName); + if (tpl) templates.set(tpl.name, tpl); + } else { + const msg = collectInterface(node, sf, resolveImportedTypeName); + if (msg) concrete.push(msg); + // Queue any generic-instantiated type-args appearing as field types + // (e.g. `wrapped: pb<5, Wrapper>`) for monomorphization. + // The call-site queue only sees the outer concrete type, so without + // this the nested instantiation would never reach the registry. + for (const ta of collectConcreteFieldGenericTypeArgs(node, resolveImportedTypeName)) { + deferredTypeArgs.push(ta); + } } - const exprStart = node.expression.getStart(sf); - const lc = sf.getLineAndCharacterOfPosition(exprStart); - deferredTypeArgs.push(firstTypeArg); - callSites.push({ - fnName: binding.fnName, - exprStart, - typeArgsEnd: node.typeArguments.end + 1, - firstTypeArg, - line: lc.line + 1, - column: lc.character + 1, + } + + if (ts.isCallExpression(node)) { + const cs = matchProtobufCallSite(node, sf, importBindings, { + allowLegacyUnboundCanonical: true, }); + if (cs) { + if (!typeArgReferencesEnclosingParam(cs.firstTypeArg)) { + deferredTypeArgs.push(cs.firstTypeArg); + callSites.push(cs); + } + // else: this call sits inside a generic wrapper definition; the + // wrapper-binding path will materialise concrete codecs at each + // downstream call site instead. + } else if ( + node.typeArguments?.length && + getCallableName(node.expression) && + wrapperBindings.has(getCallableName(node.expression)!) + ) { + const binding = wrapperBindings.get(getCallableName(node.expression)!)!; + const firstTypeArg = instantiateWrapperTypePattern(binding, node.typeArguments, sf); + if (!firstTypeArg) { + ts.forEachChild(node, visit); + return; + } + const exprStart = node.expression.getStart(sf); + const lc = sf.getLineAndCharacterOfPosition(exprStart); + deferredTypeArgs.push(firstTypeArg); + callSites.push({ + fnName: binding.fnName, + exprStart, + typeArgsEnd: node.typeArguments.end + 1, + firstTypeArg, + line: lc.line + 1, + column: lc.character + 1, + }); + } } - } - ts.forEachChild(node, visit); + ts.forEachChild(node, visit); + } finally { + if (pushedScope) enclosingTypeParamStack.pop(); + } }); // ── post-walk: monomorphize deferred type args ────────────────────── diff --git a/packages/proton/src/ast/collector.ts b/packages/proton/src/ast/collector.ts index 7bdc321c..f05deda6 100644 --- a/packages/proton/src/ast/collector.ts +++ b/packages/proton/src/ast/collector.ts @@ -46,7 +46,15 @@ export function collectInterface( const f = extractField(m, sf, resolveImportedTypeName); if (f) fields.push(f); } - return fields.length ? { name: node.name.text, fields } : null; + // Register interfaces that are EXPLICITLY empty (`interface X {}`) as + // zero-field proto messages — proto3 wire format allows them and + // downstream code routinely uses them for "this OIDB call has no + // meaningful response body" placeholders. Interfaces that have + // members but no pb-marked fields are NOT proto messages — they + // belong to regular TS types and must stay unregistered to avoid + // polluting the registry. + if (fields.length === 0 && node.members.length > 0) return null; + return { name: node.name.text, fields }; } /** Collect a generic interface template. */