diff --git a/eslint.config.ts b/eslint.config.ts index 3318e517..eefbee28 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -1,9 +1,9 @@ import js from '@eslint/js'; -import globals from 'globals'; import reactHooks from 'eslint-plugin-react-hooks'; import reactRefresh from 'eslint-plugin-react-refresh'; -import tseslint from 'typescript-eslint'; import { defineConfig, globalIgnores } from 'eslint/config'; +import globals from 'globals'; +import tseslint from 'typescript-eslint'; const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1'); @@ -48,7 +48,7 @@ export default defineConfig([ rules: { 'indent': ['error', 2, { SwitchCase: 1 }], 'prefer-const': 'off', - '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-explicit-any': 'error', '@typescript-eslint/no-empty-object-type': 'off', '@typescript-eslint/no-this-alias': 'off', '@typescript-eslint/no-unused-vars': [ @@ -61,6 +61,31 @@ export default defineConfig([ ], }, }, + { + files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'], + rules: { + '@typescript-eslint/no-explicit-any': 'off', + }, + }, + { + files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'], + rules: { + '@typescript-eslint/no-explicit-any': 'off', + }, + }, + { + // OIDB service layer is namespace-per-cmd by design — the + // structural-typing contract (namespace IS the OidbCallSpec) and + // the file:cmd 1:1 mapping are the whole point. Disable the + // module-syntax preference here only. + files: [ + 'packages/protocol/src/oidb-services/**/*.ts', + 'packages/protocol/tests/oidb-services/**/*.ts', + ], + rules: { + '@typescript-eslint/no-namespace': 'off', + }, + }, { files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'], extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite], @@ -77,4 +102,4 @@ export default defineConfig([ 'react-hooks/set-state-in-effect': 'off', }, }, -]); \ No newline at end of file +]); diff --git a/package.json b/package.json index b53a6379..62c62bc7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snowluma-monorepo", - "version": "1.9.1", + "version": "1.9.2", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", @@ -23,6 +23,8 @@ }, "devDependencies": { "@eslint/js": "^10.0.1", + "@vitest/coverage-istanbul": "4.1.4", + "@vitest/coverage-v8": "^4.1.4", "cross-env": "^10.1.0", "eslint": "^10.2.0", "eslint-plugin-react-hooks": "^7.0.1", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index 6c3ac96b..df0e8a04 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,9 +1,9 @@ { "name": "@snowluma/bridge", - "version": "1.9.1", + "version": "1.9.2", "private": true, "type": "module", - "description": "SnowLuma bridge — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/'` collapses to `import { … } from '@snowluma/bridge/'`.", + "description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).", "main": "./src/index.ts", "types": "./src/index.ts", "exports": { @@ -11,116 +11,45 @@ "types": "./src/index.ts", "default": "./src/index.ts" }, - "./events": { - "types": "./src/events.ts", - "default": "./src/events.ts" + "./hook-manager": { + "types": "./src/hook-manager.ts", + "default": "./src/hook-manager.ts" }, - "./event-bus": { - "types": "./src/event-bus.ts", - "default": "./src/event-bus.ts" + "./hook-session": { + "types": "./src/hook-session.ts", + "default": "./src/hook-session.ts" }, - "./identity-service": { - "types": "./src/identity-service.ts", - "default": "./src/identity-service.ts" + "./hook-packet-client": { + "types": "./src/hook-packet-client.ts", + "default": "./src/hook-packet-client.ts" }, - "./packet-pipeline": { - "types": "./src/packet-pipeline.ts", - "default": "./src/packet-pipeline.ts" + "./injector": { + "types": "./src/injector.ts", + "default": "./src/injector.ts" }, - "./element-builder": { - "types": "./src/element-builder.ts", - "default": "./src/element-builder.ts" + "./pipe-watcher": { + "types": "./src/pipe-watcher.ts", + "default": "./src/pipe-watcher.ts" }, - "./bridge-oidb": { - "types": "./src/bridge-oidb.ts", - "default": "./src/bridge-oidb.ts" + "./qq-hook-client": { + "types": "./src/qq-hook-client.ts", + "default": "./src/qq-hook-client.ts" }, - "./bridge-context": { - "types": "./src/bridge-context.ts", - "default": "./src/bridge-context.ts" + "./qq-port-probe": { + "types": "./src/qq-port-probe.ts", + "default": "./src/qq-port-probe.ts" }, - "./qq-info": { - "types": "./src/qq-info.ts", - "default": "./src/qq-info.ts" - }, - "./format": { - "types": "./src/format.ts", - "default": "./src/format.ts" - }, - "./msg-push": { - "types": "./src/msg-push/index.ts", - "default": "./src/msg-push/index.ts" - }, - "./msg-push/registry": { - "types": "./src/msg-push/registry.ts", - "default": "./src/msg-push/registry.ts" - }, - "./msg-push/context": { - "types": "./src/msg-push/context.ts", - "default": "./src/msg-push/context.ts" - }, - "./msg-push/decoders/event-0x2dc": { - "types": "./src/msg-push/decoders/event-0x2dc.ts", - "default": "./src/msg-push/decoders/event-0x2dc.ts" - }, - "./highway": { - "types": "./src/highway/highway-client.ts", - "default": "./src/highway/highway-client.ts" - }, - "./highway/utils": { - "types": "./src/highway/utils.ts", - "default": "./src/highway/utils.ts" - }, - "./highway/pipeline": { - "types": "./src/highway/pipeline.ts", - "default": "./src/highway/pipeline.ts" - }, - "./highway/image-upload": { - "types": "./src/highway/image-upload.ts", - "default": "./src/highway/image-upload.ts" - }, - "./highway/ptt-upload": { - "types": "./src/highway/ptt-upload.ts", - "default": "./src/highway/ptt-upload.ts" - }, - "./highway/video-upload": { - "types": "./src/highway/video-upload.ts", - "default": "./src/highway/video-upload.ts" - }, - "./highway/ffmpeg-addon": { - "types": "./src/highway/ffmpeg-addon.ts", - "default": "./src/highway/ffmpeg-addon.ts" - }, - "./web/group-album": { - "types": "./src/web/group-album.ts", - "default": "./src/web/group-album.ts" - }, - "./web/group-essence": { - "types": "./src/web/group-essence.ts", - "default": "./src/web/group-essence.ts" - }, - "./web/group-honor": { - "types": "./src/web/group-honor.ts", - "default": "./src/web/group-honor.ts" - }, - "./web/group-notice": { - "types": "./src/web/group-notice.ts", - "default": "./src/web/group-notice.ts" - }, - "./web/request-util": { - "types": "./src/web/request-util.ts", - "default": "./src/web/request-util.ts" + "./types": { + "types": "./src/types.ts", + "default": "./src/types.ts" } }, "scripts": { - "bench": "vitest bench --run", + "test": "vitest run", "typecheck": "tsc --noEmit" }, "dependencies": { - "@snowluma/common": "workspace:*", - "@snowluma/proto-defs": "workspace:*", - "@snowluma/proton": "workspace:*", - "@snowluma/sqlite": "workspace:*" + "@snowluma/common": "workspace:*" }, "devDependencies": { "@types/node": "^24.12.2", diff --git a/packages/core/src/hook/hook-manager.ts b/packages/bridge/src/hook-manager.ts similarity index 92% rename from packages/core/src/hook/hook-manager.ts rename to packages/bridge/src/hook-manager.ts index f5feed33..40a309dc 100644 --- a/packages/core/src/hook/hook-manager.ts +++ b/packages/bridge/src/hook-manager.ts @@ -1,25 +1,36 @@ -import fs from 'fs'; -import type { BridgeManager } from '../bridge/manager'; -import type { PacketSink } from '@snowluma/common/protocol-types'; import { createLogger, type Logger } from '@snowluma/common/logger'; +import type { PacketSender } from '@snowluma/common/packet-sender'; +import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types'; +import fs from 'fs'; +import { HookSession, type HookSessionDeps } from './hook-session'; import { injectHookProcess, listHookProcesses, unloadHookProcess, type HookProcessBaseInfo, } from './injector'; -import { HookSession, type HookSessionDeps } from './hook-session'; import { PipeWatcher } from './pipe-watcher'; import { QqHookClient } from './qq-hook-client'; -import type { HookProcessInfo } from './types'; import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe'; +import type { HookProcessInfo } from './types'; -export type { HookProcessInfo, HookProcessStatus } from './types'; -export type { HookProcessBaseInfo } from './injector'; -export type { QqPortLoginInfo } from './qq-port-probe'; + + +/** + * Sink that the hook layer calls back into when it observes a new login, + * a parsed packet, or a PID disconnect. The concrete implementation lives + * in @snowluma/core (`BridgeManager`), which is wired in by the top-level + * app entry. Declaring it here keeps @snowluma/bridge free of any + * dependency on @snowluma/core — the hook package is self-contained. + */ +export interface BridgeManagerSink { + onHookLogin(pid: number, uin: string, packetClient: PacketSender): void; + onPacket(pkt: PacketInfo): void; + onPidDisconnected(pid: number): void; +} export type HookManagerDeps = { - bridgeManager: BridgeManager; + bridgeManager: BridgeManagerSink; /** Sink for parsed packets from any live HookSession. Defaults to * `bridgeManager.onPacket` — every packet flows straight into the * per-UIN bridge dispatcher with no intermediate event emitter. */ @@ -57,7 +68,7 @@ export type HookManagerDeps = { * real QQ.exe or a native addon. */ export class HookManager { - private readonly bridgeManager: BridgeManager; + private readonly bridgeManager: BridgeManagerSink; private readonly onPacket: PacketSink; private readonly injector: HookSessionDeps['injector']; private readonly makeClient: HookSessionDeps['makeClient']; @@ -216,7 +227,7 @@ export class HookManager { if (this.disposed) return; for (const session of this.sessions.values()) { if ((session.status === 'connecting' || session.status === 'disconnected') - && this.pipeWatcher.isPipeLive(session.pid)) { + && this.pipeWatcher.isPipeLive(session.pid)) { session.onPipeUp(); } } @@ -298,3 +309,6 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean { } return true; } +export type { HookProcessBaseInfo } from './injector'; +export type { QqPortLoginInfo } from './qq-port-probe'; +export type { HookProcessInfo, HookProcessStatus } from './types'; diff --git a/packages/core/src/hook/hook-packet-client.ts b/packages/bridge/src/hook-packet-client.ts similarity index 95% rename from packages/core/src/hook/hook-packet-client.ts rename to packages/bridge/src/hook-packet-client.ts index f2633737..e8935d2d 100644 --- a/packages/core/src/hook/hook-packet-client.ts +++ b/packages/bridge/src/hook-packet-client.ts @@ -2,7 +2,7 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sen import { QqHookClient, type QqHookSendReply } from './qq-hook-client'; export class HookPacketClient implements PacketSender { - constructor(private readonly client: QqHookClient) {} + constructor(private readonly client: QqHookClient) { } async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise { if (!this.client.isLoggedIn) { diff --git a/packages/core/src/hook/hook-session.ts b/packages/bridge/src/hook-session.ts similarity index 100% rename from packages/core/src/hook/hook-session.ts rename to packages/bridge/src/hook-session.ts index 42f5645a..2da5a150 100644 --- a/packages/core/src/hook/hook-session.ts +++ b/packages/bridge/src/hook-session.ts @@ -1,6 +1,6 @@ -import { EventEmitter } from 'events'; -import type { PacketSink } from '@snowluma/common/protocol-types'; import { createLogger, type Logger } from '@snowluma/common/logger'; +import type { PacketSink } from '@snowluma/common/protocol-types'; +import { EventEmitter } from 'events'; import { HookPacketClient } from './hook-packet-client'; import type { HookInjectResult } from './injector'; import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client'; diff --git a/packages/bridge/src/index.ts b/packages/bridge/src/index.ts new file mode 100644 index 00000000..4f7a4378 --- /dev/null +++ b/packages/bridge/src/index.ts @@ -0,0 +1,5 @@ +export { + HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo, + type HookProcessStatus, type QqPortLoginInfo +} from './hook-manager'; + diff --git a/packages/core/src/hook/injector.ts b/packages/bridge/src/injector.ts similarity index 92% rename from packages/core/src/hook/injector.ts rename to packages/bridge/src/injector.ts index 8332164b..70f01e64 100644 --- a/packages/core/src/hook/injector.ts +++ b/packages/bridge/src/injector.ts @@ -55,12 +55,13 @@ function defaultProcessName(): string { function nativeSearchDirs(): string[] { // Several layouts must be supported: // 1. Released zip (flattened dist/): __dirname=/, native at /native - // 2. Repo bundled build (dist/index.mjs): __dirname=/dist, native at /dist/native - // 3. Dev via tsx (packages/core/src/hook/injector.ts): __dirname=/packages/core/src/hook + // 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=/packages/bridge/src // → walk up to /packages and append runtime/native + // Same offset works for `packages/bridge/dist/index.mjs` after build. + // 3. cwd-based fallback when neither __dirname-relative path resolves. return [ path.resolve(__dirname, 'native'), - path.resolve(__dirname, '..', '..', '..', 'runtime', 'native'), + path.resolve(__dirname, '..', '..', 'runtime', 'native'), path.resolve(process.cwd(), 'dist', 'native'), path.resolve(process.cwd(), 'packages', 'runtime', 'native'), ]; diff --git a/packages/core/src/hook/pipe-watcher.ts b/packages/bridge/src/pipe-watcher.ts similarity index 100% rename from packages/core/src/hook/pipe-watcher.ts rename to packages/bridge/src/pipe-watcher.ts index 59b87632..c0d7cc82 100644 --- a/packages/core/src/hook/pipe-watcher.ts +++ b/packages/bridge/src/pipe-watcher.ts @@ -1,5 +1,5 @@ -import { EventEmitter } from 'events'; import { createLogger, type Logger } from '@snowluma/common/logger'; +import { EventEmitter } from 'events'; import type { HookProcessBaseInfo } from './injector'; const DEFAULT_INTERVAL_MS = 1500; diff --git a/packages/core/src/hook/qq-hook-client.ts b/packages/bridge/src/qq-hook-client.ts similarity index 99% rename from packages/core/src/hook/qq-hook-client.ts rename to packages/bridge/src/qq-hook-client.ts index 4b195f39..49b6420d 100644 --- a/packages/core/src/hook/qq-hook-client.ts +++ b/packages/bridge/src/qq-hook-client.ts @@ -1,8 +1,8 @@ +import { EventEmitter } from 'events'; +import { promises as fs } from 'fs'; import net from 'net'; import os from 'os'; import path from 'path'; -import { promises as fs } from 'fs'; -import { EventEmitter } from 'events'; export const PIPE_MAGIC = 0x31504851; export const PIPE_VERSION = 1; @@ -235,7 +235,7 @@ function encodeFrame({ class FrameReader { private buffer = Buffer.alloc(0); - constructor(private readonly onFrame: (frame: PipeFrame) => void) {} + constructor(private readonly onFrame: (frame: PipeFrame) => void) { } push(chunk: Buffer): void { this.buffer = Buffer.concat([this.buffer, chunk]); @@ -513,7 +513,7 @@ export class QqHookClient extends EventEmitter { const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1)); const worker = async () => { - for (;;) { + for (; ;) { const index = nextIndex; nextIndex += 1; if (index >= items.length) return; @@ -624,7 +624,7 @@ export class QqHookClient extends EventEmitter { else resolve(); }); })); - this.controlWriteChain = writePromise.catch(() => {}); + this.controlWriteChain = writePromise.catch(() => { }); return writePromise; } diff --git a/packages/core/src/hook/qq-port-probe.ts b/packages/bridge/src/qq-port-probe.ts similarity index 100% rename from packages/core/src/hook/qq-port-probe.ts rename to packages/bridge/src/qq-port-probe.ts index b9bde522..5767ebaa 100644 --- a/packages/core/src/hook/qq-port-probe.ts +++ b/packages/bridge/src/qq-port-probe.ts @@ -1,5 +1,5 @@ -import net from 'net'; import { exec } from 'child_process'; +import net from 'net'; import { promisify } from 'util'; const execAsync = promisify(exec); diff --git a/packages/core/src/hook/types.ts b/packages/bridge/src/types.ts similarity index 100% rename from packages/core/src/hook/types.ts rename to packages/bridge/src/types.ts diff --git a/packages/core/tests/hook-manager.test.ts b/packages/bridge/tests/hook-manager.test.ts similarity index 95% rename from packages/core/tests/hook-manager.test.ts rename to packages/bridge/tests/hook-manager.test.ts index de1aaf13..7274b05a 100644 --- a/packages/core/tests/hook-manager.test.ts +++ b/packages/bridge/tests/hook-manager.test.ts @@ -3,11 +3,11 @@ import { EventEmitter } from 'events'; import fs from 'fs'; import os from 'os'; import path from 'path'; -import { HookManager, shouldAutoLoadPid } from '../src/hook/hook-manager'; -import { PipeWatcher } from '../src/hook/pipe-watcher'; -import type { ManualMapHandle } from '../src/hook/injector'; -import type { BridgeManager } from '../src/bridge/manager'; -import type { QqHookClient } from '../src/hook/qq-hook-client'; +import { HookManager, shouldAutoLoadPid } from '../src/hook-manager'; +import { PipeWatcher } from '../src/pipe-watcher'; +import type { ManualMapHandle } from '../src/injector'; +import type { BridgeManagerSink } from '../src/hook-manager'; +import type { QqHookClient } from '../src/qq-hook-client'; import { createLogger } from '@snowluma/common/logger'; const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; @@ -41,7 +41,7 @@ function makeManager(opts: { onPacket: vi.fn(), onHookLogin: vi.fn(), onPidDisconnected: vi.fn(), - } as unknown as BridgeManager; + } as unknown as BridgeManagerSink; const manager = new HookManager({ bridgeManager, pipeWatcher, diff --git a/packages/core/tests/hook-reconnect-no-login-e2e.test.ts b/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts similarity index 90% rename from packages/core/tests/hook-reconnect-no-login-e2e.test.ts rename to packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts index 4c0a61f9..61ef7d08 100644 --- a/packages/core/tests/hook-reconnect-no-login-e2e.test.ts +++ b/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts @@ -6,11 +6,11 @@ import { describe, it, expect, vi } from 'vitest'; import { EventEmitter } from 'events'; -import { HookManager } from '../src/hook/hook-manager'; -import { PipeWatcher } from '../src/hook/pipe-watcher'; -import type { ManualMapHandle } from '../src/hook/injector'; -import type { BridgeManager } from '../src/bridge/manager'; -import type { QqHookClient } from '../src/hook/qq-hook-client'; +import { HookManager } from '../src/hook-manager'; +import { PipeWatcher } from '../src/pipe-watcher'; +import type { ManualMapHandle } from '../src/injector'; +import type { BridgeManagerSink } from '../src/hook-manager'; +import type { QqHookClient } from '../src/qq-hook-client'; const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; const flush = () => new Promise(r => setImmediate(r)); @@ -45,7 +45,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => { onPacket: vi.fn(), onHookLogin: vi.fn(), onPidDisconnected: vi.fn(), - } as unknown as BridgeManager; + } as unknown as BridgeManagerSink; const manager = new HookManager({ bridgeManager, diff --git a/packages/core/tests/hook-reconnect-no-login.test.ts b/packages/bridge/tests/hook-reconnect-no-login.test.ts similarity index 95% rename from packages/core/tests/hook-reconnect-no-login.test.ts rename to packages/bridge/tests/hook-reconnect-no-login.test.ts index a6ab3a90..fc2f6d7d 100644 --- a/packages/core/tests/hook-reconnect-no-login.test.ts +++ b/packages/bridge/tests/hook-reconnect-no-login.test.ts @@ -17,9 +17,9 @@ import { describe, it, expect, vi } from 'vitest'; import { EventEmitter } from 'events'; -import { HookSession } from '../src/hook/hook-session'; -import type { ManualMapHandle } from '../src/hook/injector'; -import type { QqHookClient } from '../src/hook/qq-hook-client'; +import { HookSession } from '../src/hook-session'; +import type { ManualMapHandle } from '../src/injector'; +import type { QqHookClient } from '../src/qq-hook-client'; const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; diff --git a/packages/core/tests/hook-session.test.ts b/packages/bridge/tests/hook-session.test.ts similarity index 98% rename from packages/core/tests/hook-session.test.ts rename to packages/bridge/tests/hook-session.test.ts index 8a14f335..f44cdbbf 100644 --- a/packages/core/tests/hook-session.test.ts +++ b/packages/bridge/tests/hook-session.test.ts @@ -1,8 +1,8 @@ import { describe, it, expect, vi } from 'vitest'; import { EventEmitter } from 'events'; -import { HookSession } from '../src/hook/hook-session'; -import type { ManualMapHandle } from '../src/hook/injector'; -import type { QqHookClient, QqHookPacket } from '../src/hook/qq-hook-client'; +import { HookSession } from '../src/hook-session'; +import type { ManualMapHandle } from '../src/injector'; +import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client'; import type { PacketSink } from '@snowluma/common/protocol-types'; const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; diff --git a/packages/core/tests/pipe-watcher.test.ts b/packages/bridge/tests/pipe-watcher.test.ts similarity index 97% rename from packages/core/tests/pipe-watcher.test.ts rename to packages/bridge/tests/pipe-watcher.test.ts index 048a3e3d..1623c8f8 100644 --- a/packages/core/tests/pipe-watcher.test.ts +++ b/packages/bridge/tests/pipe-watcher.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; -import { PipeWatcher } from '../src/hook/pipe-watcher'; -import type { HookProcessBaseInfo } from '../src/hook/injector'; +import { PipeWatcher } from '../src/pipe-watcher'; +import type { HookProcessBaseInfo } from '../src/injector'; function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set }) { let processes = initial.processes; diff --git a/packages/core/tests/qq-hook-client.test.ts b/packages/bridge/tests/qq-hook-client.test.ts similarity index 95% rename from packages/core/tests/qq-hook-client.test.ts rename to packages/bridge/tests/qq-hook-client.test.ts index 3034e522..b84ae67e 100644 --- a/packages/core/tests/qq-hook-client.test.ts +++ b/packages/bridge/tests/qq-hook-client.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, rm, writeFile } from 'fs/promises'; import os from 'os'; import path from 'path'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { listLiveLinuxPipePids } from '../src/hook/qq-hook-client'; +import { listLiveLinuxPipePids } from '../src/qq-hook-client'; let tmpDir: string | null = null; diff --git a/packages/bridge/vitest.config.ts b/packages/bridge/vitest.config.ts index 57df30aa..b0e95a5a 100644 --- a/packages/bridge/vitest.config.ts +++ b/packages/bridge/vitest.config.ts @@ -1,21 +1,8 @@ -// Vitest config — only used by `pnpm bench` to drive the perf -// micro-benchmarks under `bench/`. There are no `*.test.ts` files in -// this package (bridge tests live in @snowluma/core's test suite by -// historical accident); if/when they migrate over, point -// `test.include` at them here. -import protobufVitePlugin from '@snowluma/proton/vite'; import { defineConfig } from 'vitest/config'; export default defineConfig({ - // proton's vite plugin inlines `protobuf_encode` / `protobuf_decode` - // call sites at build time. Required for tinybench-driven benches to - // hit the production code path rather than proton's runtime-fallback - // (which throws unless a runtime-map JSON is loaded). - plugins: [protobufVitePlugin()], test: { - benchmark: { - include: ['bench/**/*.bench.ts'], - }, + include: ['tests/**/*.test.ts'], environment: 'node', }, }); diff --git a/packages/common/package.json b/packages/common/package.json index 4e378c72..0c8471dc 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,9 +1,9 @@ { "name": "@snowluma/common", - "version": "1.9.1", + "version": "1.9.2", "private": true, "type": "module", - "description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/bridge, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).", + "description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).", "main": "./src/index.ts", "types": "./src/index.ts", "exports": { diff --git a/packages/common/src/json.ts b/packages/common/src/json.ts index 1097fa01..5d8dd735 100644 --- a/packages/common/src/json.ts +++ b/packages/common/src/json.ts @@ -1,13 +1,3 @@ -// Plain JSON value types — defined here (not in @snowluma/onebot/types -// where they used to live) so @snowluma/bridge can talk about JSON-shaped -// payloads without importing OneBot. The OneBot types module keeps the -// names exported via re-export, so existing call sites that say -// `import type { JsonValue } from '<…>/onebot/types'` continue to work -// unchanged after Phase 3. -// -// Anything actually OneBot-specific (ApiResponse, OneBotRequest, …) -// stays in @snowluma/onebot — only the plain JSON quartet moves here. - export type JsonPrimitive = string | number | boolean | null; export type JsonValue = JsonPrimitive | JsonObject | JsonArray; export interface JsonObject { diff --git a/packages/core/package.json b/packages/core/package.json index 0a2b6dd1..4eaece12 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/core", - "version": "1.9.1", + "version": "1.9.2", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", @@ -43,6 +43,7 @@ "@snowluma/bridge": "workspace:*", "@snowluma/common": "workspace:*", "@snowluma/onebot": "workspace:*", + "@snowluma/protocol": "workspace:*", "@snowluma/proto-defs": "workspace:*", "@snowluma/proton": "workspace:*", "@snowluma/sqlite": "workspace:*", diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts index 6f1ad964..6ae4f411 100644 --- a/packages/core/src/bridge/apis/contacts.ts +++ b/packages/core/src/bridge/apis/contacts.ts @@ -1,51 +1,35 @@ -// ContactsApi — friend / group / member roster + user-profile + -// group-request-list + download-rkey OIDB calls. -// -// All implementations inlined from the previous `bridge-contacts.ts` -// (which gets removed alongside the rest of the actions/* facade -// shim in commit 13). The single non-trivial piece carried over is -// the per-group inflight + TTL cache for `fetchGroupMemberList`: -// without it a busy OneBot client (e.g. MaiBot calling -// `get_group_member_info` once per inbound message) would trigger -// one OIDB 0xfe7_3 per chat message, sustained >1k/h, which trips -// Tencent risk-control and gets the account banned for 7 days. - -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { - OidbBase, - OidbSvcTrpcTcp0x10C0Response, - OidbSvcTrpcTcp0xFD4_1Response, - OidbSvcTrpcTcp0xFE5_2Response, - OidbSvcTrpcTcp0xFE7_3Response, -} from '@snowluma/proto-defs/oidb'; -import type { - AvatarInfo, - OidbFriendListRequest, - OidbGroupListRequest, - OidbGroupMemberListRequest, - OidbGroupRequestList, - OidbUserInfoRequest, - OidbUserInfoResponse, -} from '@snowluma/proto-defs/oidb-actions/base'; -import type { - NTV2RichMediaReq, - NTV2RichMediaResp, -} from '@snowluma/proto-defs/oidb-actions/media'; -import type { BridgeContext } from '../bridge-context'; -import type { DownloadRKeyInfo } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; -import type { Bridge } from '../bridge'; +import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys'; +import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page'; +import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list'; +import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page'; +import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests'; +import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile'; +import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid'; import type { FriendInfo, GroupMemberInfo, GroupRequestInfo, QQGroupInfo, UserProfileInfo, -} from '@snowluma/bridge/qq-info'; +} from '@snowluma/protocol/qq-info'; +import type { DownloadRKeyInfo } from '../bridge'; +import type { BridgeContext } from '../bridge-context'; // ─── Helpers (previously in bridge-contacts.ts) ─────────────────── -export function buildFriendProperties(raw: any): Map { +type FriendPropertySource = { + additional?: Array<{ + type?: number; + layer1?: { + properties?: Array<{ + code?: number; + value?: string; + }>; + }; + }>; +}; + +export function buildFriendProperties(raw: FriendPropertySource): Map { const props = new Map(); for (const additional of raw.additional ?? []) { if ((additional.type ?? 0) !== 1 || !additional.layer1) continue; @@ -64,68 +48,38 @@ export function permissionToRole(permission: number): string { } } -// `runOidb` and the proto-defs helpers take `Bridge` (deep dependency -// inside the highway / sendRawPacket plumbing). At runtime `ctx` IS -// the Bridge that constructed this Api, so narrowing back via -// `ctx as Bridge` is safe — see the same pattern in `MessageApi` -// where buildSendElems also expects a Bridge. -function asBridge(ctx: BridgeContext): Bridge { - return ctx as unknown as Bridge; -} - const MEMBER_LIST_TTL_MS = 60_000; export class ContactsApi { /** * Per-group inflight + last-fetch cache for `fetchGroupMemberList`. - * Keyed by groupId, lives for the lifetime of the Bridge (so the - * cache resets per account, as you'd expect for multi-account - * runtimes — `BridgeManager` builds one Bridge per uin and each - * gets its own ContactsApi). + * Keyed by groupId, lives for the lifetime of the Bridge. + * + * Without this, a busy OneBot client (e.g. MaiBot calling + * `get_group_member_info` once per inbound message) triggers one + * OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips + * Tencent risk-control and gets the account banned for 7 days. */ private memberListInflight = new Map>(); private memberListLastFetch = new Map(); - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } async fetchFriendList(): Promise { - const bridge = asBridge(this.ctx); const friends: FriendInfo[] = []; let nextUin: number | null = null; - do { - const body: any = { - friendCount: 300, - field4: 0, - field6: 1, - field7: 0x7FFFFFFF, - body: [ - { type: 1, number: { numbers: [103, 102, 20002, 27394] } }, - { type: 4, number: { numbers: [100, 101, 102] } }, - ], - field10002: [13578, 13579, 13573, 13572, 13568], - field10003: 4051, - }; - if (nextUin !== null) { - body.nextUin = { uin: nextUin }; + const resp = await FetchFriendListPage.invoke(this.ctx, { nextUin }); + for (const raw of resp.friends ?? []) { + const props = buildFriendProperties(raw); + friends.push({ + uin: raw.uin ?? 0, + uid: raw.uid ?? '', + nickname: props.get(20002) ?? String(raw.uin ?? 0), + remark: props.get(103) ?? '', + }); } - const env = makeOidbEnvelope(0xFD4, 1, body); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfd4_1', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - if (resp?.friends) { - for (const raw of resp.friends) { - const props = buildFriendProperties(raw); - friends.push({ - uin: raw.uin ?? 0, - uid: raw.uid ?? '', - nickname: props.get(20002) ?? String(raw.uin ?? 0), - remark: props.get(103) ?? '', - }); - } - } - - nextUin = resp?.next?.uin ?? null; + nextUin = resp.next?.uin ?? null; if (nextUin === 0) nextUin = null; } while (nextUin !== null); @@ -134,50 +88,17 @@ export class ContactsApi { } async fetchGroupList(): Promise { - const bridge = asBridge(this.ctx); - // The config flags ask QQ which per-group fields to include in - // the response. Asking for everything looks innocent on small - // accounts but on ~200+ groups it makes the QQ NT process write - // a payload large enough to blow the named-pipe write buffer — - // we then read EPIPE and the whole session dies. See issue #42. - // Keep `config1.*` mostly on but turn off the costly groups of - // bools that never map back to a decoded field. - const allTrue = true; - const body = { - config: { - config1: { - groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue, - groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue, - field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue, - field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue, - question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue, - field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue, - field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue, - field32: allTrue, field5001: allTrue, field5002: false, field5003: false, - }, - config2: { - field1: false, field2: false, field3: false, field4: false, - field5: false, field6: false, field7: false, field8: false, - }, - config3: { field5: allTrue, field6: allTrue }, - }, - }; - const env = makeOidbEnvelope(0xFE5, 2, body, true); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe5_2', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - + const resp = await FetchGroupList.invoke(this.ctx); const groups: QQGroupInfo[] = []; - if (resp?.groups) { - for (const raw of resp.groups) { - groups.push({ - groupId: raw.groupUin ?? 0, - groupName: raw.info?.groupName ?? '', - remark: raw.customInfo?.remark ?? '', - memberCount: raw.info?.memberCount ?? 0, - memberMax: raw.info?.memberMax ?? 0, - members: new Map(), - }); - } + for (const raw of resp.groups ?? []) { + groups.push({ + groupId: raw.groupUin ?? 0, + groupName: raw.info?.groupName ?? '', + remark: raw.customInfo?.remark ?? '', + memberCount: raw.info?.memberCount ?? 0, + memberMax: raw.info?.memberMax ?? 0, + members: new Map(), + }); } this.ctx.identity.rememberGroups(groups); return groups; @@ -187,9 +108,6 @@ export class ContactsApi { groupId: number, options: { force?: boolean } = {}, ): Promise { - // Coalesce in-flight calls + serve a 60s-cached result. Without - // this, a busy OneBot client gets the bot 7-day banned within - // hours via Tencent risk-control. const now = Date.now(); const last = this.memberListLastFetch.get(groupId); if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) { @@ -211,45 +129,25 @@ export class ContactsApi { } private async fetchGroupMemberListUncached(groupId: number): Promise { - const bridge = asBridge(this.ctx); const members: GroupMemberInfo[] = []; let token = ''; - do { - const body: any = { - groupUin: groupId, - field2: 5, - field3: 2, - body: { - memberName: true, memberCard: true, level: true, field13: true, - field16: true, specialTitle: true, field18: true, field20: true, - field21: true, joinTimestamp: true, lastMsgTimestamp: true, - shutUpTimestamp: true, field103: true, field104: true, field105: true, - field106: true, permission: true, field200: true, field201: true, - }, - }; - if (token) body.token = token; - const env = makeOidbEnvelope(0xFE7, 3, body); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe7_3', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - if (resp?.members) { - for (const raw of resp.members) { - members.push({ - uin: raw.uin?.uin ?? 0, - uid: raw.uin?.uid ?? '', - nickname: raw.memberName ?? '', - card: raw.memberCard?.memberCard ?? '', - role: permissionToRole(raw.permission ?? 0), - level: raw.level?.level ?? 0, - title: raw.specialTitle ?? '', - joinTime: raw.joinTimestamp ?? 0, - lastSentTime: raw.lastMsgTimestamp ?? 0, - shutUpTime: raw.shutUpTimestamp ?? 0, - }); - } + const resp = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token }); + for (const raw of resp.members ?? []) { + members.push({ + uin: raw.uin?.uin ?? 0, + uid: raw.uin?.uid ?? '', + nickname: raw.memberName ?? '', + card: raw.memberCard?.memberCard ?? '', + role: permissionToRole(raw.permission ?? 0), + level: raw.level?.level ?? 0, + title: raw.specialTitle ?? '', + joinTime: raw.joinTimestamp ?? 0, + lastSentTime: raw.lastMsgTimestamp ?? 0, + shutUpTime: raw.shutUpTimestamp ?? 0, + }); } - token = resp?.token ?? ''; + token = resp.token ?? ''; } while (token); this.ctx.identity.rememberGroupMembers(groupId, members); @@ -257,75 +155,25 @@ export class ContactsApi { } async fetchUserProfile(uin: number): Promise { - const bridge = asBridge(this.ctx); - const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037]; - // Only `uin` and `keys` — see OidbUserInfoRequestSchema for why - // sending field 2 makes the server reject the request. - const body = { - uin, - keys: keys.map(k => ({ key: k })), - }; - // Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the - // name is historical, the wire semantic is "this is the UIN-form - // variant of the call"). Without it newer QQ NT versions take the - // UID-form validation path, find neither uid nor openid in the - // body and bounce the request with - // `[oidb] one of uid/openid is invaild`. Matches Lagrange.Core's - // FetchStrangerByUin (Reserved = 1). - const env = makeOidbEnvelope(0xFE1, 2, body, true); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xfe1_2', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - if (!resp?.body) throw new Error('user info response body missing'); - - const info: UserProfileInfo = { - uin: resp.body.uin ?? uin, - uid: resp.body.uid ?? '', - nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', - }; - - if (resp.body.properties) { - const bytesMap = new Map(); - const numMap = new Map(); - for (const bp of resp.body.properties.bytesProperties ?? []) { - bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0)); - } - for (const np of resp.body.properties.numberProperties ?? []) { - numMap.set(np.number1 ?? 0, np.number2 ?? 0); - } - const getString = (code: number) => { - const b = bytesMap.get(code); - return b ? Buffer.from(b).toString('utf8') : ''; - }; - info.nickname = getString(20002); - info.remark = getString(103); - info.qid = getString(27394); - info.sign = getString(102); - - const avatarBytes = bytesMap.get(101); - if (avatarBytes) { - const av = protobuf_decode(avatarBytes); - if (av?.url) info.avatar = av.url + '640'; - } - const sexNum = numMap.get(20009) ?? 0; - info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown'; - info.age = numMap.get(20037) ?? 0; - } - + const info = await FetchUserProfile.invoke(this.ctx, { uin }); this.ctx.identity.rememberUserProfile(info); return info; } - async fetchGroupRequests(filtered = false): Promise { - const bridge = asBridge(this.ctx); - const subCmd = filtered ? 2 : 1; - const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c0_2' : 'OidbSvcTrpcTcp.0x10c0_1'; - const env = makeOidbEnvelope(0x10C0, subCmd, { count: 20, field2: 0 }); - const respBytes = await runOidb(bridge, cmd, protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; + /** Look up a user profile by UID (string form). Used for strangers + * whose UIN we don't have yet — typically the requester on a + * group join request push. Mirrors Lagrange's `FetchUserInfoEvent + * .Create(targetUid)` path. */ + async fetchUserProfileByUid(uid: string): Promise { + const info = await FetchUserProfileByUid.invoke(this.ctx, { uid }); + if (info.uin > 0) this.ctx.identity.rememberUserProfile(info); + return info; + } + async fetchGroupRequests(filtered = false): Promise { + const resp = await FetchGroupRequests.invoke(this.ctx, { filtered }); const requests: GroupRequestInfo[] = []; - for (const raw of resp?.requests ?? []) { + for (const raw of resp.requests ?? []) { requests.push({ groupId: raw.group?.groupUin ?? 0, groupName: raw.group?.groupName ?? '', @@ -350,31 +198,10 @@ export class ContactsApi { } async fetchDownloadRKeys(): Promise { - const bridge = asBridge(this.ctx); - const PRIVATE_IMAGE = 10; - const GROUP_IMAGE = 20; - const FALLBACK_IMAGE = 2; - - const body = { - reqHead: { - common: { requestId: 1, command: 202 }, - scene: { requestType: 2, businessType: 1, sceneType: 0 }, - client: { agentType: 2 }, - }, - downloadRkey: { - types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE], - }, - }; - const env = makeOidbEnvelope(0x9067, 202, body, true); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9067_202', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - if (resp?.respHead?.retCode && resp.respHead.retCode !== 0) { - throw new Error(resp.respHead.message ?? 'fetch download rkey failed'); - } + const resp = await FetchDownloadRkeys.invoke(this.ctx); const result: DownloadRKeyInfo[] = []; - for (const entry of resp?.downloadRkey?.rkeys ?? []) { + for (const entry of resp.downloadRkey?.rkeys ?? []) { const rkey = entry.rkey ?? ''; const type = entry.type ?? 0; if (rkey && type) { diff --git a/packages/core/src/bridge/apis/extras.ts b/packages/core/src/bridge/apis/extras.ts index 327b733e..cd78f577 100644 --- a/packages/core/src/bridge/apis/extras.ts +++ b/packages/core/src/bridge/apis/extras.ts @@ -1,34 +1,16 @@ -// ExtrasApi — Tier-2 napcat-parity surfaces that don't fit anywhere -// else: group todo CRUD, stranger online/ext status decode, AI voice -// list + synthesis. Inlined from `actions/extras.ts` (deleted alongside -// actions/* in commit 13). - -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { - OidbGroupTodo, - OidbStrangerStatusReq, - OidbStrangerStatusResp, -} from '@snowluma/proto-defs/oidb-actions/base'; -import type { - OidbAiVoiceListReq, - OidbAiVoiceListResp, - OidbAiVoiceReq, - OidbAiVoiceResp, -} from '@snowluma/proto-defs/oidb-actions/media'; -import type { MediaIndexNode } from './shared'; +import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice'; +import { + FetchAiVoiceList, + type AiVoiceCategory as NamespaceAiVoiceCategory, +} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list'; +import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status'; +import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo'; import type { BridgeContext } from '../bridge-context'; -import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; - -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } +import type { MediaIndexNode } from './shared'; // ─────────────── public types (re-exported from bridge.ts as before) ─── -export interface StrangerStatus { - status: number; - ext_status: number; -} +export type StrangerStatus = NamespaceStrangerStatus; export const AiVoiceChatType = { Unknown: 0, @@ -37,71 +19,40 @@ export const AiVoiceChatType = { } as const; export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType]; +export type AiVoiceCategory = NamespaceAiVoiceCategory; export interface AiVoiceItem { voiceId: string; voiceDisplayName: string; voiceExampleUrl: string; } -export interface AiVoiceCategory { - category: string; - voices: AiVoiceItem[]; -} - export class ExtrasApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } // ─────────────── Group todo (0xF90) ─────────────── - async setGroupTodo(groupId: number, msgSeq: bigint): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0xF90, 1, { groupUin: groupId, msgSeq }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_1', protobuf_encode>(env)); + setGroupTodo(groupId: number, msgSeq: bigint): Promise { + return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' }); } - async completeGroupTodo(groupId: number, msgSeq: bigint): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0xF90, 2, { groupUin: groupId, msgSeq }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_2', protobuf_encode>(env)); + completeGroupTodo(groupId: number, msgSeq: bigint): Promise { + return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' }); } - async cancelGroupTodo(groupId: number, msgSeq: bigint): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0xF90, 3, { groupUin: groupId, msgSeq }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xf90_3', protobuf_encode>(env)); + cancelGroupTodo(groupId: number, msgSeq: bigint): Promise { + return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' }); } // ─────────────── Stranger online/ext status (0xFE1_2) ─────────────── /** - * Mirror napcat's GetStrangerStatus: decode the extBigInt status word. - * Values ≤10 fold into a 10×status; everything else is split into the - * high-byte / low-byte ext_status the OneBot dialect uses. - * - * Returns null on transport / decode failure rather than throwing, so - * the OneBot action can produce a clean retcode without try/catch - * gymnastics. + * Returns `null` on transport / decode failure rather than throwing, + * so the OneBot action can produce a clean retcode without try/catch + * gymnastics. Namespace throws on transport failure → swallow here. */ async getStrangerStatus(uin: number): Promise { - const bridge = asBridge(this.ctx); try { - 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', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - const raw = resp?.data?.status?.value; - if (raw === undefined || raw === null) return null; - const extBig = typeof raw === 'bigint' ? raw : BigInt(raw); - if (extBig <= 10n) { - return { status: Number(extBig) * 10, ext_status: 0 }; - } - const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn)); - return { status: 10, ext_status: status }; + return await GetStrangerStatus.invoke(this.ctx, { uin }); } catch { return null; } @@ -109,12 +60,8 @@ export class ExtrasApi { // ─────────────── AI voice (0x929D / 0x929B) ─────────────── - async fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0x929D, 0, { groupUin: groupId, chatType }); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929d_0', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - return (resp?.content as AiVoiceCategory[] | undefined) ?? []; + fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise { + return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType }); } /** @@ -133,18 +80,11 @@ export class ExtrasApi { chatType: AiVoiceChatType | number, maxRetries = 30, ): Promise { - const bridge = asBridge(this.ctx); // 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 env = makeOidbEnvelope( - 0x929B, 0, - { groupUin: groupId, voiceId, text, chatType, session: { sessionId } }, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x929b_0', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - const node = resp?.msgInfo?.msgInfoBody?.[0]?.index as MediaIndexNode | undefined; - if (node) return node; + const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId }); + if (node) return node as MediaIndexNode; } throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`); } diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/bridge/apis/forward.ts index 2ebe8656..86d0b9da 100644 --- a/packages/core/src/bridge/apis/forward.ts +++ b/packages/core/src/bridge/apis/forward.ts @@ -1,17 +1,4 @@ -// ForwardApi — long-message (聊天记录 / forward) upload + retrieval. -// Inlined from `actions/forward.ts` (deleted alongside actions/* in -// commit 13). -// -// The module-scoped `forwardResCache` stays at file scope (not on the -// class instance) because forward res_ids are globally unique, and an -// outbound upload often gets queried back through `fetch` on a -// different Bridge instance (e.g. a different OneBot connection -// hitting the same account). Keeping the cache shared across the -// process matches NapCat's behaviour. - -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import { randomUUID } from 'crypto'; -import { gunzipSync, gzipSync } from 'zlib'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; import type { LongMsgResult, RecvLongMsgReq, @@ -20,12 +7,14 @@ import type { SendLongMsgResp, } from '@snowluma/proto-defs/longmsg'; import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message'; -import type { PacketInfo } from '@snowluma/common/protocol-types'; -import type { BridgeContext } from '../bridge-context'; +import { buildSendElems } from '@snowluma/protocol/element-builder'; +import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events'; +import { parseMsgPush } from '@snowluma/protocol/msg-push'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { randomUUID } from 'crypto'; +import { gunzipSync, gzipSync } from 'zlib'; import type { Bridge } from '../bridge'; -import { buildSendElems } from '@snowluma/bridge/element-builder'; -import type { ForwardNodePayload, MessageElement } from '@snowluma/bridge/events'; -import { parseMsgPush } from '@snowluma/bridge/msg-push'; +import type { BridgeContext } from '../bridge-context'; import { resolveSelfUid, toInt } from './shared'; function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } @@ -214,7 +203,7 @@ function previewFromElements(elements: MessageElement[]): string { } export class ForwardApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise { const { resId } = await this.uploadRecursive(nodes, groupId, userId); @@ -265,6 +254,14 @@ export class ForwardApi { // res_id / uuid before encoding the outer ARK previews). Build // `processedNodes` with elements rewritten for nested layers, // and collect every inner level's piggyback in `myInnerActions`. + // + // CRITICAL: the same uuid (`inner.uuid`) MUST be baked into the + // outer's preview element as `forwardUuid` AND used as the + // `actionCommand` for the outer's piggyback entry. That's the + // alignment the QQ-NT receiver uses to find the inner layer + // inside the outer's LongMsgResult without a second server fetch + // — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round- + // trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`. const myInnerActions: ForwardInnerAction[] = []; const processedNodes: ForwardNodePayload[] = []; const isGroup = groupId !== undefined; @@ -278,13 +275,13 @@ export class ForwardApi { myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody }); myInnerActions.push(...inner.innerActions); // Replace the inner placeholder element with a forward preview - // pointing at the inner res_id. The wire-side element builder - // turns this into the same XML m_resid blob it already produced - // for top-level forwards — see `makeForwardElem` in - // element-builder.ts:153. + // pointing at the inner res_id. `forwardUuid: inner.uuid` + // baked into the LightApp JSON's `meta.detail.uniseq` is what + // closes the loop with our piggyback action above. const previewElement: MessageElement = { type: 'forward', resId: inner.resId, + forwardUuid: inner.uuid, forwardSource: deriveInnerSource(node.innerForward, isGroup), forwardSummary: `查看${node.innerForward.length}条转发消息`, forwardPrompt: '[聊天记录]', @@ -367,6 +364,14 @@ export class ForwardApi { return { resId, msgBody, + // UUID generated here so the OUTER caller can use it as both + // (1) the `actionCommand` for its piggyback entry carrying our + // msgBody, and + // (2) the `forwardUuid` baked into its forward-preview element + // pointing at our resId. + // Receivers walking the outer's LongMsgResult find the inner + // layer by matching `uniseq` from (2) against `actionCommand` + // from (1) — no separate fetch needed. uuid: randomUUID(), innerActions: myInnerActions, }; @@ -417,10 +422,46 @@ export class ForwardApi { const inflate = gunzipSync(Buffer.from(payload)); const longMsg = protobuf_decode(inflate); - const action = longMsg?.action?.find((item) => item?.actionCommand === 'MultiMsg'); - const msgBodyList = Array.isArray(action?.actionData?.msgBody) ? action.actionData.msgBody : []; + const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : []; + const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg'); + const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody) ? mainAction!.actionData!.msgBody : []; - const nodes: ForwardNodePayload[] = []; + // Piggyback index: any non-`MultiMsg` action carries an inner + // layer keyed by the uuid the sender baked into its forward + // preview's `uniseq`. Build a lookup so we can resolve inner + // forwards (via their uniseq → inner msgBody) without a second + // server roundtrip — matches the sender-side piggyback emitted in + // `uploadRecursive` above. + const piggybackByUuid = new Map(); + for (const action of actions) { + const cmd = action?.actionCommand; + if (!cmd || cmd === 'MultiMsg') continue; + const body = Array.isArray(action.actionData?.msgBody) ? action.actionData.msgBody : []; + piggybackByUuid.set(cmd, body); + } + + const nodes = this.decodeMsgBodiesToNodes(msgBodyList); + + // Walk the decoded outer nodes for inner-forward previews + // (`type: 'forward', forwardUuid: `). For each, pull the + // matching piggyback body, decode it into inner nodes, and seed + // the cache by the inner resId so a follow-up `fetch(innerResId)` + // hits the cache instead of the wire. + if (piggybackByUuid.size > 0) { + this.consumePiggybacks(nodes, piggybackByUuid); + } + + if (nodes.length > 0) { + forwardResCache.set(resId, cloneNodes(nodes)); + } + return nodes; + } + + /** Walk a list of PushMsgBody, run each through the regular msg-push + * pipeline, and shape the result into ForwardNodePayloads. Extracted + * so both the outer + piggyback decode paths share one implementation. */ + private decodeMsgBodiesToNodes(msgBodyList: PushMsgBody[]): ForwardNodePayload[] { + const out: ForwardNodePayload[] = []; for (const msgBody of msgBodyList) { const wrapped = protobuf_encode({ message: msgBody }); const pkt: PacketInfo = { @@ -438,7 +479,7 @@ export class ForwardApi { if (!event) continue; if (event.kind === 'group_message') { - nodes.push({ + out.push({ userUin: event.senderUin, nickname: event.senderCard || event.senderNick, elements: event.elements, @@ -450,7 +491,7 @@ export class ForwardApi { messageType: 'group', }); } else if (event.kind === 'friend_message') { - nodes.push({ + out.push({ userUin: event.senderUin, nickname: event.senderNick, elements: event.elements, @@ -460,7 +501,7 @@ export class ForwardApi { messageType: 'private', }); } else { - nodes.push({ + out.push({ userUin: event.senderUin, nickname: event.senderNick, elements: event.elements, @@ -471,20 +512,51 @@ export class ForwardApi { }); } } + return out; + } - if (nodes.length > 0) { - forwardResCache.set(resId, nodes.map(node => ({ - userUin: node.userUin, - nickname: node.nickname, - elements: [...node.elements], - time: node.time, - msgId: node.msgId, - msgSeq: node.msgSeq, - groupId: node.groupId, - senderCard: node.senderCard, - messageType: node.messageType, - }))); - } - return nodes; + /** Recursively resolve forward previews against the piggyback table. + * For every `{type: 'forward', resId, forwardUuid}` element we find, + * look up the uniseq in the piggyback map; if hit, decode the + * inner msgBody and cache it by inner resId, then descend into that + * inner layer to resolve deeper nestings carried in the SAME + * piggyback set (NapCat hoists the entire tree's piggybacks onto + * the outermost action list). */ + private consumePiggybacks( + nodes: ForwardNodePayload[], + piggybackByUuid: Map, + ): void { + const seen = new Set(); + const visit = (chain: ForwardNodePayload[]): void => { + for (const node of chain) { + for (const elem of node.elements) { + if (elem.type !== 'forward') continue; + const uuid = elem.forwardUuid; + const innerResId = elem.resId; + if (!uuid || !innerResId || seen.has(uuid)) continue; + const body = piggybackByUuid.get(uuid); + if (!body) continue; + seen.add(uuid); + const innerNodes = this.decodeMsgBodiesToNodes(body); + forwardResCache.set(innerResId, cloneNodes(innerNodes)); + visit(innerNodes); + } + } + }; + visit(nodes); } } + +function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] { + return nodes.map(node => ({ + userUin: node.userUin, + nickname: node.nickname, + elements: [...node.elements], + time: node.time, + msgId: node.msgId, + msgSeq: node.msgSeq, + groupId: node.groupId, + senderCard: node.senderCard, + messageType: node.messageType, + })); +} diff --git a/packages/core/src/bridge/apis/friend.ts b/packages/core/src/bridge/apis/friend.ts index 639b72a7..98208352 100644 --- a/packages/core/src/bridge/apis/friend.ts +++ b/packages/core/src/bridge/apis/friend.ts @@ -1,59 +1,21 @@ -// FriendApi — friend roster mutations (handle add request / -// delete / set remark). Inlined from `actions/friend.ts` (deleted -// alongside actions/* in commit 13). The READ side of friends -// (fetchFriendList) lives on ContactsApi because friends/groups -// share the same roster pipeline. - -import { protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { - OidbDeleteFriend, - OidbFriendRequestAction, - OidbSetFriendRemark, -} from '@snowluma/proto-defs/oidb-actions/base'; +import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend'; +import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request'; +import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark'; import type { BridgeContext } from '../bridge-context'; -import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; - -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } export class FriendApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } /** * Accept or reject an inbound friend request. `uidOrFlag` is either a * pre-resolved UID string or a numeric uin (then resolved on the fly). */ - async handleRequest(uidOrFlag: string, approve: boolean): Promise { - const bridge = asBridge(this.ctx); - let targetUid = uidOrFlag; - if (/^\d+$/.test(uidOrFlag)) { - targetUid = await this.ctx.resolveUserUid(parseInt(uidOrFlag, 10)); - } - const env = makeOidbEnvelope(0xB5D, 44, { accept: approve ? 3 : 5, targetUid }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xb5d_44', protobuf_encode>(env)); + handleRequest(uidOrFlag: string, approve: boolean): Promise { + return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve }); } async delete(userId: number, block = false): Promise { - const bridge = asBridge(this.ctx); - const targetUid = await this.ctx.resolveUserUid(userId); - 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', protobuf_encode>(env)); + await DeleteFriend.invoke(this.ctx, { userId, block }); // Refresh friend cache after deletion so subsequent reads don't // surface a ghost entry. Best-effort: a transient OIDB hiccup here @@ -61,10 +23,7 @@ export class FriendApi { try { await this.ctx.apis.contacts.fetchFriendList(); } catch { /* ignore */ } } - async setRemark(userId: number, remark: string): Promise { - const bridge = asBridge(this.ctx); - const uid = await this.ctx.resolveUserUid(userId); - const env = makeOidbEnvelope(0xB6E, 2, { targetUid: uid, remark }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xb6e_2', protobuf_encode>(env)); + setRemark(userId: number, remark: string): Promise { + return SetFriendRemark.invoke(this.ctx, { userId, remark }); } } diff --git a/packages/core/src/bridge/apis/group-admin.ts b/packages/core/src/bridge/apis/group-admin.ts index cc2488ef..9951ddec 100644 --- a/packages/core/src/bridge/apis/group-admin.ts +++ b/packages/core/src/bridge/apis/group-admin.ts @@ -1,137 +1,71 @@ -// GroupAdminApi — mute/kick/admin/card/name/title/leave + join-policy -// + add-request handling. Inlined from the previous -// `actions/group-admin.ts` (deleted alongside the rest of the -// actions/* facade in commit 13). - -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { - Oidb0x89a_0AddOption, - Oidb0x89a_0Search, - Oidb0x8a0Req, - Oidb0x8a7Req, - Oidb0x8a7Resp, - Oidb0xf16Req, - OidbGroupRequestAction, - OidbKickMember, - OidbLeaveGroup, - OidbMuteAll, - OidbMuteMember, - OidbRenameGroup, - OidbRenameMember, - OidbSetAdmin, - OidbSpecialTitle, -} from '@snowluma/proto-defs/oidb-actions/base'; +import { GetAtAllRemain } from '@snowluma/protocol/oidb-services/group-admin/get-at-all-remain'; +import { KickMember } from '@snowluma/protocol/oidb-services/group-admin/kick-member'; +import { KickMembers } from '@snowluma/protocol/oidb-services/group-admin/kick-members'; +import { LeaveGroup } from '@snowluma/protocol/oidb-services/group-admin/leave-group'; +import { MuteAll } from '@snowluma/protocol/oidb-services/group-admin/mute-all'; +import { MuteMember } from '@snowluma/protocol/oidb-services/group-admin/mute-member'; +import { SetAddOption } from '@snowluma/protocol/oidb-services/group-admin/set-add-option'; +import { SetAddRequest } from '@snowluma/protocol/oidb-services/group-admin/set-add-request'; +import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin'; +import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name'; +import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark'; +import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card'; +import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search'; +import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title'; import type { BridgeContext } from '../bridge-context'; -import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; - -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } export class GroupAdminApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } - async muteMember(groupId: number, userId: number, duration: number): Promise { - const bridge = asBridge(this.ctx); - const uid = await this.ctx.resolveUserUid(userId, groupId); - const env = makeOidbEnvelope(0x1253, 1, { - groupUin: groupId, type: 1, body: { targetUid: uid, duration }, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x1253_1', protobuf_encode>(env)); + muteMember(groupId: number, userId: number, duration: number): Promise { + return MuteMember.invoke(this.ctx, { groupId, userId, duration }); } - async muteAll(groupId: number, enable: boolean): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0x89A, 0, { - groupUin: groupId, muteState: { state: enable ? 0xFFFFFFFF : 0 }, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode>(env)); + muteAll(groupId: number, enable: boolean): Promise { + return MuteAll.invoke(this.ctx, { groupId, enable }); } - async setAddOption(groupId: number, addType: number): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0x89A, 0, { - groupUin: BigInt(groupId), settings: { addType }, field12: 0, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode>(env)); + setAddOption(groupId: number, addType: number): Promise { + return SetAddOption.invoke(this.ctx, { groupId, addType }); } - async setSearch(groupId: number): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0x89A, 0, { - groupUin: BigInt(groupId), settings: new Uint8Array(0), field12: 0, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_0', protobuf_encode>(env)); + setSearch(groupId: number): Promise { + return SetSearch.invoke(this.ctx, { groupId }); } - async setAddRequest( + setAddRequest( groupId: number, sequence: number, eventType: number, approve: boolean, reason = '', filtered = false, ): Promise { - const bridge = asBridge(this.ctx); - const subCmd = filtered ? 2 : 1; - const cmd = filtered ? 'OidbSvcTrpcTcp.0x10c8_2' : 'OidbSvcTrpcTcp.0x10c8_1'; - const env = makeOidbEnvelope( - 0x10C8, subCmd, - { accept: approve ? 1 : 2, body: { sequence: BigInt(sequence), eventType, groupUin: groupId, message: reason } }, - true, - ); - await runOidb(bridge, cmd, protobuf_encode>(env)); + return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered }); } - async kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise { - const bridge = asBridge(this.ctx); - const uid = await this.ctx.resolveUserUid(userId, groupId); - const env = makeOidbEnvelope(0x8A0, 1, { - groupUin: groupId, targetUid: uid, rejectAddRequest: reject, reason, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a0_1', protobuf_encode>(env)); + kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise { + return KickMember.invoke(this.ctx, { groupId, userId, reject, reason }); } - async kickMembers(groupId: number, userIds: number[], reject: boolean): Promise { - const bridge = asBridge(this.ctx); - const targetUids = await Promise.all(userIds.map(userId => this.ctx.resolveUserUid(userId, groupId))); - 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', protobuf_encode>(env)); + kickMembers(groupId: number, userIds: number[], reject: boolean): Promise { + return KickMembers.invoke(this.ctx, { groupId, userIds, reject }); } - async leave(groupId: number): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0x1097, 1, { groupUin: groupId }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x1097_1', protobuf_encode>(env)); + leave(groupId: number): Promise { + return LeaveGroup.invoke(this.ctx, { groupId }); } - async setAdmin(groupId: number, userId: number, enable: boolean): Promise { - const bridge = asBridge(this.ctx); - const uid = await this.ctx.resolveUserUid(userId, groupId); - const env = makeOidbEnvelope(0x1096, 1, { groupUin: groupId, uid, isAdmin: enable }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x1096_1', protobuf_encode>(env)); + setAdmin(groupId: number, userId: number, enable: boolean): Promise { + return SetAdmin.invoke(this.ctx, { groupId, userId, enable }); } - async setCard(groupId: number, userId: number, card: string): Promise { - const bridge = asBridge(this.ctx); - const uid = await this.ctx.resolveUserUid(userId, groupId); - const env = makeOidbEnvelope(0x8FC, 3, { - groupUin: groupId, body: { targetUid: uid, targetName: card }, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_3', protobuf_encode>(env)); + setCard(groupId: number, userId: number, card: string): Promise { + return SetMemberCard.invoke(this.ctx, { groupId, userId, card }); } - async setName(groupId: number, name: string): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0x89A, 15, { groupUin: groupId, body: { targetName: name } }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x89a_15', protobuf_encode>(env)); + setName(groupId: number, name: string): Promise { + return SetGroupName.invoke(this.ctx, { groupId, name }); } - async setSpecialTitle(groupId: number, userId: number, title: string): Promise { - const bridge = asBridge(this.ctx); - const uid = await this.ctx.resolveUserUid(userId, groupId); - const env = makeOidbEnvelope(0x8FC, 2, { - groupUin: groupId, body: { targetUid: uid, specialTitle: title, expireTime: -1 }, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x8fc_2', protobuf_encode>(env)); + setSpecialTitle(groupId: number, userId: number, title: string): Promise { + return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title }); } /** @@ -139,37 +73,15 @@ export class GroupAdminApi { * `FriendApi` because the semantic is "operate on a group" rather * than "operate on a contact list". */ - async setRemark(groupId: number, remark: string): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0xF16, 1, { inner: { groupId: BigInt(groupId), remark }, field12: 0 }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xf16_1', protobuf_encode>(env)); + setRemark(groupId: number, remark: string): Promise { + return SetGroupRemark.invoke(this.ctx, { groupId, remark }); } - async getAtAllRemain(groupId: number): Promise<{ + getAtAllRemain(groupId: number): Promise<{ can_at_all: boolean; remain_at_all_count_for_group: number; remain_at_all_count_for_uin: number; }> { - const bridge = asBridge(this.ctx); - const req = { - basic1: 1, - basic2: 2, - basic3: 1, - uin: BigInt(this.ctx.identity.uin), - groupId: BigInt(groupId), - type: 0, - }; - const env = makeOidbEnvelope(0x8A7, 0, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x8a7_0', protobuf_encode>(env)); - const result = protobuf_decode>(respBytes).body; - if (!result) throw new Error('get group at all remain result empty'); - - // Cast numbers to plain Number: the OIDB layer may surface uint32 - // as BigInt and the WebUI JSON serializer chokes on those. - return { - can_at_all: !!result.canAtAll, - remain_at_all_count_for_group: Number(result.groupRemain || 0), - remain_at_all_count_for_uin: Number(result.uinRemain || 0), - }; + return GetAtAllRemain.invoke(this.ctx, { groupId }); } } diff --git a/packages/core/src/bridge/apis/group-album.ts b/packages/core/src/bridge/apis/group-album.ts index 7fa80ade..7a8b1205 100644 --- a/packages/core/src/bridge/apis/group-album.ts +++ b/packages/core/src/bridge/apis/group-album.ts @@ -1,10 +1,4 @@ -// GroupAlbumApi — group photo album operations (list/upload/comment/ -// like/delete + media listing). Inlined from `actions/group-album.ts` -// and `web-actions/group-album.ts` (both deleted alongside actions/* -// in commit 13). The pure-HTTP helpers in `web/group-album.ts` stay -// where they are — they're transport-layer code, not Bridge actions. - -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { JsonObject, JsonValue } from '@snowluma/common/json'; import type { DeleteMediasRequest, DeleteMediasResponse, @@ -14,47 +8,33 @@ import type { DoQunLikeResponse, GetMediaListRequest, GetMediaListResponse, + MediaInfo, } from '@snowluma/proto-defs/oidb-actions/group-album'; +import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { BridgeContext } from '../bridge-context'; -import type { Bridge } from '../bridge'; -import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/bridge/web/group-album'; -// `getCookies` is part of WebApi — go through the hub so we don't -// duplicate the cookie acquisition flow. -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } -export interface GroupAlbumMediaResult { - mediaList: any[]; - nextAttachInfo: string; -} - -export interface GroupAlbumCommentResult { - id: string; - user: { uin: string }; - content: Array<{ type: number; content: string }>; - time: string; - clientKey: string; -} - -function convertBigIntToString(obj: any): any { - if (obj === null || obj === undefined) return obj; +function convertBigIntToString(obj: unknown): JsonValue { + if (obj === null || obj === undefined) return null; if (typeof obj === 'bigint') return obj.toString(); if (Array.isArray(obj)) return obj.map(convertBigIntToString); if (typeof obj === 'object') { - const result: any = {}; - for (const key in obj) { - result[key] = convertBigIntToString(obj[key]); + const result: JsonObject = {}; + for (const [key, value] of Object.entries(obj)) { + result[key] = convertBigIntToString(value); } return result; } - return obj; + if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') return obj; + return null; } export class GroupAlbumApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } - /** List a group's albums (HTTP-cookie-based, qzone.qq.com). */ - async list(groupId: number): Promise { + // 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。 + async list(groupId: number): Promise { const groupCode = groupId.toString(); const uin = this.ctx.identity.uin; const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); @@ -62,7 +42,7 @@ export class GroupAlbumApi { return albumData?.album || []; } - /** Upload an image into an existing album (HTTP slice-upload). */ + // 上传图片到现有相册(HTTP 分片上传)。 async upload(groupId: number, albumId: string, albumName: string, filePath: string): Promise { const groupCode = groupId.toString(); const uin = this.ctx.identity.uin; @@ -108,7 +88,7 @@ export class GroupAlbumApi { const mediaList = data.mediaList ?? []; const nextAttachInfo = data.nextAttachInfo ?? ''; - return convertBigIntToString({ mediaList, nextAttachInfo }); + return convertBigIntToString({ mediaList, nextAttachInfo }) as unknown as GroupAlbumMediaResult; } async comment(groupId: number, albumId: string, lloc: string, content: string): Promise { @@ -179,10 +159,10 @@ export class GroupAlbumApi { content: commentData.content ?? [], time: commentData.time ?? '0', clientKey: commentData.clientKey ?? '', - }); + }) as unknown as GroupAlbumCommentResult; } - async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise { + async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise { const uin = this.ctx.identity.uin; const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; @@ -244,7 +224,7 @@ export class GroupAlbumApi { return convertBigIntToString(resp.body?.like ?? {}); } - async delete(groupId: number, albumId: string, lloc: string): Promise { + async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> { const uin = this.ctx.identity.uin; const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; @@ -283,3 +263,17 @@ export class GroupAlbumApi { return { success: true }; } } +export interface GroupAlbumMediaResult { + mediaList: Array>; + nextAttachInfo: string; +} + +export type GroupAlbumList = NonNullable>>['album']; + +export interface GroupAlbumCommentResult { + id: string; + user: { uin: string }; + content: Array<{ type: number; content: string }>; + time: string; + clientKey: string; +} diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts index 2af2e0f9..86920988 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/bridge/apis/group-file.ts @@ -1,44 +1,30 @@ -// GroupFileApi — group file CRUD + private (c2c) file upload + media -// download URL resolvers. Inlined from `actions/group-file.ts` -// (deleted alongside the rest of actions/* in commit 13). -// -// Naming: methods drop the redundant `Group`/`File` suffix where the -// area name already says it. The `Private`/`Group` axis stays -// explicit because some methods only exist for one side -// (`publish` only makes sense for group, `getPrivateUrl` only for -// c2c) — keeping them in one Api lets the few shared private helpers -// (`fetchNtv2DownloadUrl`, the upload-ext builder) live in one file. - -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { toHexUpper } from '@snowluma/common/hex'; import { createLogger } from '@snowluma/common/logger'; -import type { BridgeContext } from '../bridge-context'; -import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; -import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/bridge/highway'; -import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/bridge/highway/utils'; import type { FileUploadExt } from '@snowluma/proto-defs/highway'; -import { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { - OidbGroupFileCountViewReq, - OidbGroupFileCountViewResp, - OidbGroupFileFolderReq, - OidbGroupFileFolderResp, - OidbGroupFileReq, - OidbGroupFileResp, - OidbGroupFileViewReq, - OidbGroupFileViewResp, - OidbGroupSendFileReq, -} from '@snowluma/proto-defs/oidb-actions/group-file'; -import type { - NTV2RichMediaReq, - NTV2RichMediaResp, - OidbPrivateFileDownloadReq, - OidbPrivateFileDownloadResp, - OidbPrivateFileUploadReq, - OidbPrivateFileUploadResp, -} from '@snowluma/proto-defs/oidb-actions/media'; -import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared'; +import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway'; +import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils'; +import { protobuf_encode } from '@snowluma/proton'; +import type { Bridge } from '../bridge'; +import type { BridgeContext } from '../bridge-context'; +import { resolveSelfUid, toInt, type MediaIndexNode } from './shared'; + +import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/create-group-folder'; +import { DeleteGroupFile } from '@snowluma/protocol/oidb-services/group-file/delete-group-file'; +import { DeleteGroupFolder } from '@snowluma/protocol/oidb-services/group-file/delete-group-folder'; +import { GetGroupFileCount } from '@snowluma/protocol/oidb-services/group-file/get-group-file-count'; +import { GetGroupFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-file-url'; +import { GetGroupPttUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-ptt-url'; +import { GetGroupVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-video-url'; +import { GetPrivateFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-file-url'; +import { GetPrivatePttUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-ptt-url'; +import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-video-url'; +import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page'; +import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file'; +import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file'; +import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder'; +import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request'; +import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request'; +import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared'; const log = createLogger('GroupFile'); @@ -230,120 +216,23 @@ function buildPrivateFileUploadExt( }); } -function normalizeMediaNode(node: MediaIndexNode): Record { - const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : ''; - if (!fileUuid) throw new Error('media node fileUuid is required'); - - const info = node.info ?? {}; - const type = info.type ?? {}; - - return { - info: { - fileSize: toInt(info.fileSize), - fileHash: typeof info.fileHash === 'string' ? info.fileHash : '', - fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '', - fileName: typeof info.fileName === 'string' ? info.fileName : '', - type: { - type: toInt(type.type), - picFormat: toInt(type.picFormat), - videoFormat: toInt(type.videoFormat), - voiceFormat: toInt(type.voiceFormat), - }, - width: toInt(info.width), - height: toInt(info.height), - time: toInt(info.time), - original: toInt(info.original), - }, - fileUuid, - storeId: toInt(node.storeId), - uploadTime: toInt(node.uploadTime), - ttl: toInt(node.ttl), - subType: toInt(node.subType), - }; -} - -async function fetchNtv2DownloadUrl( - bridge: Bridge, - serviceCmd: string, - oidbCmd: number, - payload: Record, -): Promise { - const env = makeOidbEnvelope(oidbCmd, 200, payload as any, true); - const respBytes = await runOidb(bridge, serviceCmd, protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - ensureRetCodeZero('ntv2 download', resp?.respHead?.retCode, resp?.respHead?.message, undefined); - const domain = typeof resp?.download?.info?.domain === 'string' ? resp.download.info.domain : ''; - const path = typeof resp?.download?.info?.urlPath === 'string' ? resp.download.info.urlPath : ''; - const rKeyParam = typeof resp?.download?.rKeyParam === 'string' ? resp.download.rKeyParam : ''; - - if (!domain || !path) { - throw new Error('ntv2 download response invalid'); - } - return `https://${domain}${path}${rKeyParam}`; -} - export class GroupFileApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } // ─────────────── publish (group file → chat) ─────────────── - /** - * Publish a previously-uploaded group file as a chat message. - * - * Wire is OIDB `OidbSvcTrpcTcp.0x6d9_4` — NOT `MessageSvc.PbSendMsg`. - * Lagrange.Core V2 splits these two roles: the file UPLOAD path goes - * via 0x6D6_0 + highway PUT, then a SECOND OIDB hop (this one) tells - * the QQ server "now publish that staged blob as a chat message" so - * everyone in the group can see the file bubble. - * - * The old approach — wrap the file as `TransElem(elemType=24)` inside - * `richText.elems[]` and ship it via PbSendMsg — works for INCOMING - * messages (the receive decoder unpacks transElem(24) into a - * FileEntity) but the QQ-NT server REJECTS it on outgoing with - * `result=79` ("invalid element on send-side"). Mirror Lagrange's - * dedicated GroupSendFileService instead. - * - * The unused `field4` slot and the `field3=random` value match - * Lagrange's send-side defaults (`OidbSvcTrpcTcp0x6D9_4.cs` + the - * `Random.Shared.Next()` call in `GroupSendFileService.cs`). Field 5 - * is the `Field5=true` flag the receiver's deserializer expects. - */ - async publish(groupId: number, fileId: string): Promise { + publish(groupId: number, fileId: string): Promise { if (!fileId) throw new Error('publish requires fileId'); - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0x6D9, 4, { - body: { - groupUin: groupId, - type: 2, - info: { - busiType: 102, - fileId, - field3: Math.floor(Math.random() * 0x7fffffff) >>> 0, - field5: true, - }, - }, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d9_4', protobuf_encode>(env)); + return PublishGroupFile.invoke(this.ctx, { groupId, fileId }); } // ─────────────── count ─────────────── - async getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope( - 0x6D8, 3, - { count: { groupUin: groupId, appId: 7, busId: 0 } }, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_3', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - return { - fileCount: toInt(resp?.count?.fileCount ?? 0), - maxCount: toInt(resp?.count?.maxCount ?? 10000), - }; + getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { + return GetGroupFileCount.invoke(this.ctx, { groupId }); } - // ─────────────── upload ─────────────── + // ─────────────── upload (3-stage: OIDB preflight → highway → publish) ─────────────── async upload( groupId: number, @@ -361,31 +250,14 @@ export class GroupFileApi { const fileName = normalizeUploadFileName(name, loaded.fileName); const hashes = computeHashes(loaded.bytes); - 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, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_0', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - const upload = resp?.upload; - if (!upload) throw new Error('group file upload response missing'); + const upload = await UploadGroupFileRequest.invoke(this.ctx, { + groupId, + fileName, + folderId: normalizeDirectory(folderId), + fileSize: loaded.bytes.length, + fileSha1: hashes.sha1, + fileMd5: hashes.md5, + }); ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording); const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null; @@ -470,8 +342,6 @@ export class GroupFileApi { uploadFile = true, ): Promise { const bridge = asBridge(this.ctx); - // Group/private files may legitimately be up to 4 GiB on QQ's wire, - // so override the default 1 GiB cap with the protocol ceiling. const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); if (!loaded.bytes.length) throw new Error('private file is empty'); @@ -491,29 +361,15 @@ export class GroupFileApi { const fileName = normalizeUploadFileName(name, loaded.fileName); const hashes = computeHashes(loaded.bytes); - 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), - }, - businessId: 3, - clientType: 1, - flagSupportMediaPlatform: 1, + const upload = await UploadPrivateFileRequest.invoke(this.ctx, { + senderUid: selfUid, + receiverUid: targetUid, + fileName, + fileSize: loaded.bytes.length, + fileSha1: hashes.sha1, + fileMd5: hashes.md5, + md510MCheckSum: md5First10MB(loaded.bytes), }); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1700', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - const upload = resp?.upload; - if (!upload) throw new Error('private file upload response missing'); ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined); const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null; @@ -583,12 +439,8 @@ export class GroupFileApi { ? toInt(upload.uploadHttpsPort) : toInt(upload.uploadPort); if (!uploadHost || uploadPort <= 0) { - // Surface every host-bearing field we know about so a user - // hitting this can show us exactly which slot the server filled - // (or whether it returned nothing at all — which would point at - // a request mismatch rather than a missing decoder). const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress) - ? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e: any) => ({ + ? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({ outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort, iPType: e.iPType, }))) @@ -647,10 +499,9 @@ export class GroupFileApi { return { fileId, fileHash }; } - // ─────────────── list ─────────────── + // ─────────────── list (paginated loop) ─────────────── async list(groupId: number, folderId = '/'): Promise { - const bridge = asBridge(this.ctx); const targetDirectory = normalizeDirectory(folderId); const files: GroupFileInfo[] = []; const folders: GroupFolderInfo[] = []; @@ -658,26 +509,9 @@ export class GroupFileApi { const pageSize = 20; let startIndex = 0; for (let page = 0; page < 200; page++) { - const env = makeOidbEnvelope( - 0x6D8, 1, - { - list: { - groupUin: groupId, - appId: 7, - targetDirectory, - fileCount: pageSize, - sortBy: 1, - startIndex, - field17: 2, - field18: 0, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d8_1', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - const list = resp?.list; + const list = await ListGroupFilesPage.invoke(this.ctx, { + groupId, targetDirectory, startIndex, pageSize, + }); if (!list) break; ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording); @@ -730,24 +564,7 @@ export class GroupFileApi { // ─────────────── url fetch (group / private files) ─────────────── async getUrl(groupId: number, fileId: string, busId = 102): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope( - 0x6D6, 2, - { - download: { - groupUin: groupId, - appId: 7, - busId, - fileId, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_2', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - const download = resp?.download; - if (!download) throw new Error('group file url response missing'); + const download = await GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId }); ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording); const dns = (typeof download.downloadDns === 'string' && download.downloadDns) @@ -766,25 +583,8 @@ export class GroupFileApi { const bridge = asBridge(this.ctx); const selfUid = await resolveSelfUid(bridge); void userId; - const env = makeOidbEnvelope(0xE37, 1200, { - subCommand: 1200, - field2: 1, - body: { - receiverUid: selfUid, - fileUuid: fileId, - type: 2, - fileHash, - t2: 0, - }, - field101: 3, - field102: 103, - field200: 1, - field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), - }); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xe37_1200', protobuf_encode>(env), 5000); - const resp = protobuf_decode>(respBytes).body; + const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash }); - const result = resp?.body?.result; const server = typeof result?.server === 'string' ? result.server : ''; const port = toInt(result?.port); const url = typeof result?.url === 'string' ? result.url : ''; @@ -796,211 +596,49 @@ export class GroupFileApi { // ─────────────── delete / move ─────────────── - async delete(groupId: number, fileId: string): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope( - 0x6D6, 3, - { - delete: { - groupUin: groupId, - busId: 102, - fileId, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_3', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - const result = resp?.delete; - if (!result) throw new Error('group file delete response missing'); - ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording); + delete(groupId: number, fileId: string): Promise { + return DeleteGroupFile.invoke(this.ctx, { groupId, fileId }); } - async move( - groupId: number, - fileId: string, - parentDirectory: string, - targetDirectory: string, - ): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope( - 0x6D6, 5, - { - move: { - groupUin: groupId, - appId: 7, - busId: 102, - fileId, - parentDirectory, - targetDirectory, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d6_5', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - const result = resp?.move; - if (!result) throw new Error('group file move response missing'); - ensureRetCodeZero('group file move', result.retCode, result.retMsg, result.clientWording); + move(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise { + return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory }); } // ─────────────── folders ─────────────── - async createFolder(groupId: number, name: string, parentId = '/'): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope( - 0x6D7, 0, - { - create: { - groupUin: groupId, - rootDirectory: normalizeDirectory(parentId), - folderName: name, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_0', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - const result = resp?.create; - if (!result) throw new Error('group folder create response missing'); - ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording); + createFolder(groupId: number, name: string, parentId = '/'): Promise { + return CreateGroupFolder.invoke(this.ctx, { + groupId, parentId: normalizeDirectory(parentId), folderName: name, + }); } - async deleteFolder(groupId: number, folderId: string): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope( - 0x6D7, 1, - { - delete: { - groupUin: groupId, - folderId, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_1', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - const result = resp?.delete; - if (!result) throw new Error('group folder delete response missing'); - ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording); + deleteFolder(groupId: number, folderId: string): Promise { + return DeleteGroupFolder.invoke(this.ctx, { groupId, folderId }); } - async renameFolder(groupId: number, folderId: string, newFolderName: string): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope( - 0x6D7, 2, - { - rename: { - groupUin: groupId, - folderId, - newFolderName, - }, - }, - true, - ); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x6d7_2', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - const result = resp?.rename; - if (!result) throw new Error('group folder rename response missing'); - ensureRetCodeZero('group folder rename', result.retcode, result.retMsg, result.clientWording); + renameFolder(groupId: number, folderId: string, newFolderName: string): Promise { + return RenameGroupFolder.invoke(this.ctx, { groupId, folderId, newFolderName }); } // ─────────────── rich-media URL by node ─────────────── - async getPttUrl(groupId: number, node: MediaIndexNode): Promise { - const bridge = asBridge(this.ctx); - const normalizedNode = normalizeMediaNode(node); - return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126e_200', 0x126E, { - reqHead: { - common: { requestId: 4, command: 200 }, - scene: { - requestType: 1, - businessType: 3, - sceneType: 2, - group: { groupUin: groupId }, - }, - client: { agentType: 2 }, - }, - download: { - node: normalizedNode, - download: { video: { busiType: 0, sceneType: 0 } }, - }, - }); + getPttUrl(groupId: number, node: MediaIndexNode): Promise { + return GetGroupPttUrl.invoke(this.ctx, { groupId, node }); } async getPrivatePttUrl(node: MediaIndexNode): Promise { const bridge = asBridge(this.ctx); const selfUid = await resolveSelfUid(bridge); - const normalizedNode = normalizeMediaNode(node); - return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x126d_200', 0x126D, { - reqHead: { - common: { requestId: 1, command: 200 }, - scene: { - requestType: 1, - businessType: 3, - sceneType: 1, - c2c: { - accountType: 2, - targetUid: selfUid, - }, - }, - client: { agentType: 2 }, - }, - download: { - node: normalizedNode, - download: { video: { busiType: 0, sceneType: 0 } }, - }, - }); + return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node }); } - async getVideoUrl(groupId: number, node: MediaIndexNode): Promise { - const bridge = asBridge(this.ctx); - const normalizedNode = normalizeMediaNode(node); - return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11ea_200', 0x11EA, { - reqHead: { - common: { requestId: 1, command: 200 }, - scene: { - requestType: 2, - businessType: 2, - sceneType: 2, - group: { groupUin: groupId }, - }, - client: { agentType: 2 }, - }, - download: { - node: normalizedNode, - download: { video: { busiType: 0, sceneType: 0 } }, - }, - }); + getVideoUrl(groupId: number, node: MediaIndexNode): Promise { + return GetGroupVideoUrl.invoke(this.ctx, { groupId, node }); } async getPrivateVideoUrl(node: MediaIndexNode): Promise { const bridge = asBridge(this.ctx); const selfUid = await resolveSelfUid(bridge); - const normalizedNode = normalizeMediaNode(node); - return fetchNtv2DownloadUrl(bridge, 'OidbSvcTrpcTcp.0x11e9_200', 0x11E9, { - reqHead: { - common: { requestId: 1, command: 200 }, - scene: { - requestType: 2, - businessType: 2, - sceneType: 1, - c2c: { - accountType: 2, - targetUid: selfUid, - }, - }, - client: { agentType: 2 }, - }, - download: { - node: normalizedNode, - download: { video: { busiType: 0, sceneType: 0 } }, - }, - }); + return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node }); } } diff --git a/packages/core/src/bridge/apis/index.ts b/packages/core/src/bridge/apis/index.ts index 4407a927..831b223b 100644 --- a/packages/core/src/bridge/apis/index.ts +++ b/packages/core/src/bridge/apis/index.ts @@ -1,23 +1,3 @@ -// ApiHub — the per-instance bag of typed Api classes hanging off -// `bridge.apis`. Mirrors NapCat's `NapCatCore.apis = { MsgApi, …}` -// pattern but uses camelCase keys (`apis.message.sendGroup`) to match -// the rest of the SnowLuma TypeScript style. -// -// Each Api class is constructed once when the parent `Bridge` is -// constructed (eager — every account that connects gets its own -// `apis.*` set immediately). Api classes receive a `BridgeContext` -// reference, NOT the concrete `Bridge`, so they remain easy to mock -// without standing up a full Bridge instance. -// -// Adding a new Api: -// 1. Create `bridge/apis/.ts` exporting a `class XxxApi`. -// 2. Add a property here. -// 3. Construct it inside `buildApiHub(ctx)` below. -// 4. Move the relevant methods OFF Bridge and onto the new Api. -// -// All 12 Api hubs are now live (#6 commits 1-12). The interface lists -// every typed area an OneBot caller can reach via `bridge.apis.*`. - import type { BridgeContext } from '../bridge-context'; import { ContactsApi } from './contacts'; import { ExtrasApi } from './extras'; @@ -99,3 +79,4 @@ export { MessageApi } from './message'; export { MiscApi } from './misc'; export { ProfileApi } from './profile'; export { WebApi } from './web'; + diff --git a/packages/core/src/bridge/apis/interaction.ts b/packages/core/src/bridge/apis/interaction.ts index a77a6086..4ace0f61 100644 --- a/packages/core/src/bridge/apis/interaction.ts +++ b/packages/core/src/bridge/apis/interaction.ts @@ -1,70 +1,43 @@ -// InteractionApi — interactive engagement primitives (poke / like / -// reaction / essence / emoji-like-list). Inlined from -// `actions/interaction.ts` + the lone-survivor `setGroupEssence` from -// `actions/group-message.ts` (both deleted alongside actions/* in -// commit 13). The recall+markRead halves of `group-message.ts` were -// already absorbed into `MessageApi` back in commit 1. +// InteractionApi — facade over interactive-engagement OIDB cmds +// (poke / like / reaction / essence / emoji-like-list). Every method +// is a one-line forwarder to a self-contained namespace under +// @snowluma/protocol/oidb-services. The facade exists purely to keep +// the `bridge.apis.interaction.X(...)` ergonomic call style; all wire +// work (envelope build / encode / send / decode) lives in the +// namespace files. -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { - Oidb0x9083Req, - Oidb0x9083Resp, - OidbEssence, - OidbGroupReaction, - OidbLike, - OidbPoke, -} from '@snowluma/proto-defs/oidb-actions/base'; +import { SendLike } from '@snowluma/protocol/oidb-services/interaction/send-like'; +import { SendPoke } from '@snowluma/protocol/oidb-services/interaction/send-poke'; +import { SetEssence } from '@snowluma/protocol/oidb-services/interaction/set-essence'; +import { FetchReactionSummary } from '@snowluma/protocol/oidb-services/reaction/fetch-reaction-summary'; +import { GetEmojiLikes } from '@snowluma/protocol/oidb-services/reaction/get-emoji-likes'; +import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-reaction'; import type { BridgeContext } from '../bridge-context'; -import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; - -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } export class InteractionApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } - async sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0xED3, 1, { - uin: targetUin ?? peerUin, - groupUin: isGroup ? peerUin : 0, - friendUin: isGroup ? 0 : peerUin, - ext: 0, - }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0xed3_1', protobuf_encode>(env)); + sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise { + return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin }); } - async sendLike(userId: number, count: number): Promise { - const bridge = asBridge(this.ctx); - const env = makeOidbEnvelope(0x7E5, 104, { targetUin: userId, count }); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x7e5_104', protobuf_encode>(env)); + sendLike(userId: number, count: number): Promise { + return SendLike.invoke(this.ctx, { userId, count }); } - async setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise { - const bridge = asBridge(this.ctx); - const subCmd = isSet ? 1 : 2; - const cmd = isSet ? 'OidbSvcTrpcTcp.0x9082_1' : 'OidbSvcTrpcTcp.0x9082_2'; - // Same heuristic Lagrange.Core V2 uses (`GroupAddReactionEvent.IsEmoji`): - // QQ face ids are 1–3 digits ("76") → type=1, unicode codepoints are - // longer ("128516") → type=2. Server reads the type at field 5; sending - // it at the wrong field number triggers - // "invalid ReqBody.EmojiType: value must be greater than 0". - const type = code.length > 3 ? 2 : 1; - const env = makeOidbEnvelope(0x9082, subCmd, { - groupUin: groupId, sequence, code, type, field6: false, field7: false, - }); - await runOidb(bridge, cmd, protobuf_encode>(env)); + setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise { + return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet }); } - async setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise { - const bridge = asBridge(this.ctx); - const subCmd = enable ? 1 : 2; - const cmd = enable ? 'OidbSvcTrpcTcp.0xeac_1' : 'OidbSvcTrpcTcp.0xeac_2'; - const env = makeOidbEnvelope(0xEAC, subCmd, { groupUin: groupId, sequence, random }); - await runOidb(bridge, cmd, protobuf_encode>(env)); + setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise { + return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable }); } + /** + * Legacy stub: see `GetEmojiLikes` namespace comment for why this + * SSO path can never surface the user list. Real data lives in + * ReactionStore on the OneBot side. + */ async getEmojiLikes( groupId: number, sequence: number, @@ -73,23 +46,23 @@ export class InteractionApi { count = 10, cookie = '', ): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> { - const bridge = asBridge(this.ctx); - const req: any = { - groupId: BigInt(groupId), - sequence, - emojiType, - emojiId, - cookie: cookie ? Buffer.from(cookie, 'base64') : new Uint8Array(0), - field7: 0, - count, - field12: 1, - }; - const env = makeOidbEnvelope(0x9083, 1, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x9083_1', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - const uin = resp?.inner?.userInfo?.uin; - const users = uin ? [{ uin: Number(uin) }] : []; - const respCookie = resp?.cookie ? Buffer.from(resp.cookie).toString('base64') : ''; - return { users, cookie: respCookie, isLast: !respCookie }; + try { + return await GetEmojiLikes.invoke(this.ctx, { groupId, sequence, emojiId, emojiType, count, cookie }); + } catch { + return { users: [], cookie: '', isLast: true }; + } + } + + /** + * Fetch the per-emoji reaction summary on a group message via + * 0x9084_1 — emoji_id + reactor count + last-reaction timestamp. + * Cross-checked against the local ReactionStore cache for callers + * that need to detect cache gaps. + */ + fetchReactionSummary( + groupId: number, + sequence: number, + ): Promise> { + return FetchReactionSummary.invoke(this.ctx, { groupId, sequence }); } } diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/bridge/apis/message.ts index 0e2aea0a..7b7cbc9b 100644 --- a/packages/core/src/bridge/apis/message.ts +++ b/packages/core/src/bridge/apis/message.ts @@ -1,17 +1,3 @@ -// MessageApi — send / recall / mark-read operations. -// -// Folds together the previous shapes: -// - `Bridge.sendGroupMessage` / `sendPrivateMessage` / `sendC2cFileMessage` -// (formerly inline on the Bridge class). -// - `actions/group-message.ts` (recallGroup / recallPrivate / -// markGroupRead / markPrivateRead). -// -// All implementations are inlined here — the previous indirection -// through `actions/group-message.ts` exported functions was just -// `(bridge, args) → method body`; once methods live on a typed Api -// class the wrapper layer doesn't earn its keep. - -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { SendMessageRequest, SendMessageResponse, @@ -22,8 +8,9 @@ import type { GroupRecallRequest, SsoReadedReportReq, } from '@snowluma/proto-defs/oidb-actions/base'; -import type { MessageElement } from '@snowluma/bridge/events'; -import { buildSendElems } from '@snowluma/bridge/element-builder'; +import { buildSendElems } from '@snowluma/protocol/element-builder'; +import type { MessageElement } from '@snowluma/protocol/events'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { BridgeContext } from '../bridge-context'; // `Bridge` is imported as a type only so we can narrow `ctx` back to // the concrete Bridge instance when passing it to `buildSendElems` @@ -38,7 +25,7 @@ import type { Bridge, SendMessageReceipt } from '../bridge'; const SEND_MSG_CMD = 'MessageSvc.PbSendMsg'; export class MessageApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } /** * Send a message to a QQ group. @@ -68,7 +55,7 @@ export class MessageApi { richText: { elems: protoElems, }, - } as any, + }, clientSequence: 0, random, syncCookie: new Uint8Array(0), @@ -130,7 +117,7 @@ export class MessageApi { richText: { elems: protoElems, }, - } as any, + }, clientSequence: clientSeq, random, syncCookie: new Uint8Array(0), diff --git a/packages/core/src/bridge/apis/misc.ts b/packages/core/src/bridge/apis/misc.ts index fe05bac2..0e78432e 100644 --- a/packages/core/src/bridge/apis/misc.ts +++ b/packages/core/src/bridge/apis/misc.ts @@ -1,54 +1,23 @@ -// MiscApi — odds & ends that don't fit the other Apis: translation, -// mini-app ARK build, inline-keyboard button click, group sign-in. -// Inlined from `actions/misc.ts` (deleted alongside actions/* in -// commit 13). - -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { JsonObject, JsonValue } from '@snowluma/common/json'; import type { MiniAppShareReq, MiniAppShareResp, - Oidb0x112eReq, - Oidb0x112eResp, - Oidb0x990Req, - Oidb0x990Resp, - Oidb0xeb7Req, - Oidb0xeb7Resp, } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { BridgeContext } from '../bridge-context'; -import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; - -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } +// Migrated OIDB cmds — facade methods are one-line forwarders. +import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button'; +import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign'; +import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh'; export class MiscApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } - async translateEn2Zh(words: string[]): Promise { - const bridge = asBridge(this.ctx); - const req = { - translateReq: { - srcLang: 'en', - dstLang: 'zh', - words, - }, - tag10: 1, - tag12: 1, - }; - - const env = makeOidbEnvelope(0x990, 2, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x990_2', protobuf_encode>(env)); - const result = protobuf_decode>(respBytes).body; - - const resp = result?.translateResp; - if (!resp) { - throw new Error('translate response empty'); - } - - return resp.dstWords || []; + translateEn2Zh(words: string[]): Promise { + return TranslateEnToZh.invoke(this.ctx, { words }); } - async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise { + async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise { let appid = '1109937557'; // default: bilibili let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg'; @@ -77,7 +46,7 @@ export class MiscApi { throw new Error('mini app share json empty'); } - const parsed = JSON.parse(jsonStr); + const parsed = JSON.parse(jsonStr) as Record; return { data: { @@ -93,54 +62,17 @@ export class MiscApi { }; } - async clickInlineKeyboardButton( + clickInlineKeyboardButton( groupId: number, botAppid: number, buttonId: string, callbackData: string, msgSeq: number, - ): Promise { - const bridge = asBridge(this.ctx); - const req = { - botAppid: BigInt(botAppid), - msgSeq: BigInt(msgSeq), - buttonId: String(buttonId), - callbackData: String(callbackData || ''), - unknown7: 0, - groupId: BigInt(groupId), - unknown9: 1, - }; - - const env = makeOidbEnvelope(0x112E, 1, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112e_1', protobuf_encode>(env)); - const result = protobuf_decode>(respBytes).body; - - if (!result) { - throw new Error('click inline keyboard button result empty'); - } - - return { - result: Number(result.result || 0), - errMsg: result.errMsg || '', - status: 0, - promptText: result.promptText || '', - promptType: 0, - promptIcon: 0, - }; + ): Promise { + return ClickInlineKeyboardButton.invoke(this.ctx, { groupId, botAppid, buttonId, callbackData, msgSeq }); } - async sendGroupSign(groupId: number): Promise { - const bridge = asBridge(this.ctx); - const req = { - signInInfo: { - uin: String(this.ctx.identity.uin), - groupId: String(groupId), - version: '9.0.90', - }, - }; - - const env = makeOidbEnvelope(0xEB7, 1, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xEB7_1', protobuf_encode>(env)); - protobuf_decode>(respBytes); + sendGroupSign(groupId: number): Promise { + return SendGroupSign.invoke(this.ctx, { groupId }); } } diff --git a/packages/core/src/bridge/apis/profile.ts b/packages/core/src/bridge/apis/profile.ts index d92ac399..309b717e 100644 --- a/packages/core/src/bridge/apis/profile.ts +++ b/packages/core/src/bridge/apis/profile.ts @@ -1,36 +1,25 @@ -// ProfileApi — personal profile + status + avatar + likes + custom -// faces + unidirectional friend list. Inlined from -// `actions/profile.ts` (deleted alongside actions/* in commit 13). - -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { FaceroamOpReq, FaceroamOpResp, GroupAvatarExtra, - Oidb0x112aReq, - Oidb0x112aResp, - Oidb0x7edReq, - Oidb0x7edResp, - Oidb0xcd4Req, - Oidb0xcd4Resp, - Oidb0xe17Req, - Oidb0xe17Resp, - OidbSetProfile, SetStatusReq, SetStatusResp, } from '@snowluma/proto-defs/oidb-actions/base'; -import type { BridgeContext } from '../bridge-context'; +import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway'; +import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils'; +import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like'; +import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list'; +import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status'; +import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile'; +import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; -import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/bridge/highway'; -import { computeHashes, loadBinarySource } from '@snowluma/bridge/highway/utils'; -import { resolveSelfUid } from './shared'; +import type { BridgeContext } from '../bridge-context'; function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } export class ProfileApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } // ─────────────── status / profile setters ─────────────── @@ -80,64 +69,16 @@ export class ProfileApi { } } - async setProfile(nickname?: string, personalNote?: string): Promise { - const bridge = asBridge(this.ctx); - const uin = BigInt(this.ctx.identity.uin); - const stringProfiles: any[] = []; - const intProfiles: any[] = []; - - if (nickname !== undefined) { - stringProfiles.push({ fieldId: 20002, value: nickname }); - } - - if (personalNote !== undefined) { - stringProfiles.push({ fieldId: 102, value: personalNote }); - } - - if (stringProfiles.length === 0 && intProfiles.length === 0) { - return; - } - - const req = { uin, stringProfiles }; - const env = makeOidbEnvelope(0x112A, 2, req); - await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode>(env)); + setProfile(nickname?: string, personalNote?: string): Promise { + return SetProfile.invoke(this.ctx, { nickname, personalNote }); } - async setSelfLongNick(longNick: string): Promise { - const bridge = asBridge(this.ctx); - const req = { - uin: BigInt(this.ctx.identity.uin), - profile: { - tag: 102, - value: String(longNick), - }, - }; - - const env = makeOidbEnvelope(0x112A, 2, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x112a_2', protobuf_encode>(env)); - // Decode just to maintain the original behaviour of "consume the response". - protobuf_decode>(respBytes); + setSelfLongNick(longNick: string): Promise { + return SetSelfLongNick.invoke(this.ctx, { longNick }); } - async setInputStatus(userId: number, eventType: number): Promise { - const bridge = asBridge(this.ctx); - const targetUid = await this.ctx.resolveUserUid(userId); - - if (!targetUid) { - throw new Error('target uid not found'); - } - - const req = { - reqBody: { - uid: targetUid, - chatType: 0, - eventType, - }, - }; - - const env = makeOidbEnvelope(0xCD4, 1, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0xcd4_1', protobuf_encode>(env)); - protobuf_decode>(respBytes); + setInputStatus(userId: number, eventType: number): Promise { + return SetInputStatus.invoke(this.ctx, { userId, eventType }); } async setAvatar(source: string): Promise { @@ -179,74 +120,12 @@ export class ProfileApi { // ─────────────── queries on me / my contacts ─────────────── - async getLike(userId?: number, start = 0, limit = 10): Promise { - const bridge = asBridge(this.ctx); - const isSelf = !userId; - const targetUid = isSelf - ? await resolveSelfUid(bridge) - : await this.ctx.resolveUserUid(userId); - - if (!targetUid) { - throw new Error('target uid not found'); - } - - const req = { - targetUid, - basic: 1, - vote: 1, - favorite: 1, - start, - limit, - }; - - const env = makeOidbEnvelope(0x7ED, 12, req); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x7ed_12', protobuf_encode>(env)); - const result = protobuf_decode>(respBytes).body; - - const data = result?.userLikeInfos?.[0]; - if (!data) { - throw new Error('get profile like info empty'); - } - - return { - uid: data.uid, - time: Number(data.time), - favoriteInfo: { - total_count: data.favoriteInfo?.totalCount || 0, - last_time: Number(data.favoriteInfo?.lastTime || 0), - today_count: data.favoriteInfo?.newCount || 0, - userInfos: [], - }, - voteInfo: { - total_count: data.voteInfo?.totalCount || 0, - new_count: data.voteInfo?.newCount || 0, - new_nearby_count: 0, - last_visit_time: Number(data.voteInfo?.lastTime || 0), - userInfos: [], - }, - }; + getLike(userId?: number, start = 0, limit = 10): Promise { + return GetLike.invoke(this.ctx, { userId, start, limit }); } - async getUnidirectionalFriendList(): Promise { - const bridge = asBridge(this.ctx); - const reqObj = { - uint64_uin: String(this.ctx.identity.uin), - uint64_top: 0, - uint32_req_num: 99, - bytes_cookies: '', - }; - - const req = { jsonBody: JSON.stringify(reqObj) }; - const env = makeOidbEnvelope(0xE17, 0, req); - const respBytes = await runOidb(bridge, 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', protobuf_encode>(env)); - const result = protobuf_decode>(respBytes).body; - - if (!result || !result.jsonBody) { - throw new Error('get unidirectional friend list empty'); - } - - const parsed = JSON.parse(result.jsonBody); - return parsed.rpt_block_list || []; + getUnidirectionalFriendList(): Promise { + return GetUnidirectionalFriendList.invoke(this.ctx); } async fetchCustomFace(count = 10): Promise { @@ -262,10 +141,10 @@ export class ProfileApi { throw new Error(result.errorMessage || 'fetch custom face failed'); } const resp = protobuf_decode(result.responseData); - if (!resp || (resp as any).retCode !== 0) { - throw new Error(`fetch custom face error: ${(resp as any)?.message || 'unknown'}`); + if (!resp || resp.retCode !== 0) { + throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`); } - const faceIds = (resp as any).item?.faceIds || []; + const faceIds = resp.item?.faceIds || []; return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`); } } diff --git a/packages/core/src/bridge/apis/shared.ts b/packages/core/src/bridge/apis/shared.ts index e3c4e091..09ff7b8d 100644 --- a/packages/core/src/bridge/apis/shared.ts +++ b/packages/core/src/bridge/apis/shared.ts @@ -1,10 +1,5 @@ import type { Bridge } from '../bridge'; -/** - * Coerce numbers, strings, and bigints to a plain integer. - * Returns 0 for anything we can't interpret — every action that - * threads this through OIDB has an explicit `<=0` validation later. - */ export function toInt(value: unknown): number { if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); if (typeof value === 'bigint') { diff --git a/packages/core/src/bridge/apis/web.ts b/packages/core/src/bridge/apis/web.ts index 9e40fb75..6198f924 100644 --- a/packages/core/src/bridge/apis/web.ts +++ b/packages/core/src/bridge/apis/web.ts @@ -1,72 +1,55 @@ -// WebApi — cookie-backed HTTP wrappers (group essence / honor / notice / -// client-key / pskey / csrf-token / credentials). Inlined from the -// per-feature files in `web-actions/` (all deleted in commit 13). -// The pure HTTP transport stays in `web/*.ts` and stays unchanged — -// only the Bridge-binding helpers move here. - -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { - OidbClientKeyReq, - OidbClientKeyResp, - OidbGetPskeyReq, - OidbGetPskeyResp, -} from '@snowluma/proto-defs/oidb-actions/base'; -import type { BridgeContext } from '../bridge-context'; -import type { Bridge } from '../bridge'; -import { makeOidbEnvelope, runOidb } from '@snowluma/bridge/bridge-oidb'; -import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '@snowluma/bridge/web/group-essence'; -import { getHonorListWebAPI, WebHonorType } from '@snowluma/bridge/web/group-honor'; +import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key'; +import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey'; +import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence'; +import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor'; import { deleteGroupNotice as deleteGroupNoticeHttp, getGroupNoticeWebAPI, setGroupNoticeWebAPI, uploadGroupNoticeImage, -} from '@snowluma/bridge/web/group-notice'; -import { RequestUtil } from '@snowluma/bridge/web/request-util'; + type SetNoticeRetSuccess, +} from '@snowluma/protocol/web/group-notice'; +import { RequestUtil } from '@snowluma/protocol/web/request-util'; +import type { Bridge } from '../bridge'; +import type { BridgeContext } from '../bridge-context'; function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } -export interface ClientKeyInfo { - clientKey: string; - keyIndex: string; - expireTime: string; +export type ClientKeyInfo = NamespaceClientKeyInfo; + +export interface WebHonorInfo { + [key: string]: import('@snowluma/common/json').JsonValue; + group_id: number; + current_talkative: WebHonorItem | null; + talkative_list: WebHonorItem[]; + performer_list: WebHonorItem[]; + legend_list: WebHonorItem[]; + emotion_list: WebHonorItem[]; + strong_newbie_list: WebHonorItem[]; +} + +export interface WebNoticeInfo { + [key: string]: import('@snowluma/common/json').JsonValue; + notice_id: string; + sender_id: number; + publish_time: number; + message: { + text: string; + image: Array<{ id: string; height: number; width: number }>; + images: Array<{ id: string; height: number; width: number }>; + }; + settings: import('@snowluma/common/json').JsonValue; + read_num: number; } // ─────────────── private helpers (cookie acquisition) ─────────────── -async function forceFetchClientKeyInner(bridge: Bridge): Promise { - const env = makeOidbEnvelope(0x102A, 1, {}); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_1', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - const clientKey = resp?.clientKey || ''; - // keyIndex falls back to "19" — origin unknown but the value is what - // every NapCat-derived implementation uses when the server omits it. - const keyIndex = String(resp?.keyIndex || '19'); - - return { - clientKey, - keyIndex, - expireTime: String(resp?.expireTime || '1800'), - }; +function forceFetchClientKeyInner(bridge: Bridge): Promise { + return ForceFetchClientKey.invoke(bridge); } -async function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map }> { - const env = makeOidbEnvelope(0x102A, 0, { domainList }); - const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_0', protobuf_encode>(env)); - const resp = protobuf_decode>(respBytes).body; - - const domainPskeyMap = new Map(); - if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) { - for (const item of resp.pskeyItems) { - if (item.domain && item.pskey) { - domainPskeyMap.set(item.domain, item.pskey); - } - } - } - - return { domainPskeyMap }; +function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map }> { + return GetPskey.invoke(bridge, { domainList }); } async function getCookies(bridge: Bridge, domain: string): Promise> { @@ -136,7 +119,7 @@ function getBknFromSKey(skey: string): number { } export class WebApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) { } // ─────────────── cookie / token primitives ─────────────── @@ -187,7 +170,7 @@ export class WebApi { // ─────────────── group essence ─────────────── /** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */ - async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise { + async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise { const bridge = asBridge(this.ctx); const groupCode = groupId.toString(); const cookieObject = await getCookies(bridge, 'qun.qq.com'); @@ -196,7 +179,7 @@ export class WebApi { } /** Walks every page and returns the concatenated result. */ - async getEssenceAll(groupId: number): Promise { + async getEssenceAll(groupId: number): Promise { const bridge = asBridge(this.ctx); const groupCode = groupId.toString(); const cookieObject = await getCookies(bridge, 'qun.qq.com'); @@ -205,12 +188,12 @@ export class WebApi { // ─────────────── group honor ─────────────── - async getHonorInfo(groupId: number, type: WebHonorType | string): Promise { + async getHonorInfo(groupId: number, type: WebHonorType | string): Promise { const bridge = asBridge(this.ctx); const groupCode = groupId.toString(); const cookieObject = await getCookies(bridge, 'qun.qq.com'); - const honorInfo: any = { + const honorInfo: WebHonorInfo = { group_id: groupId, current_talkative: null, talkative_list: [], @@ -254,7 +237,7 @@ export class WebApi { type?: number; confirm_required?: number; }, - ): Promise { + ): Promise { const bridge = asBridge(this.ctx); const groupCode = groupId.toString(); const cookieObject = await getCookies(bridge, 'qun.qq.com'); @@ -304,7 +287,7 @@ export class WebApi { return ret; } - async getNotice(groupId: number): Promise { + async getNotice(groupId: number): Promise { const bridge = asBridge(this.ctx); const groupCode = groupId.toString(); const cookieObject = await getCookies(bridge, 'qun.qq.com'); @@ -314,7 +297,7 @@ export class WebApi { throw new Error('获取公告失败'); } - const retNotices: any[] = []; + const retNotices: WebNoticeInfo[] = []; if (ret.feeds) { for (const key in ret.feeds) { diff --git a/packages/core/src/bridge/bridge-context.ts b/packages/core/src/bridge/bridge-context.ts index a2ca9296..ef146e85 100644 --- a/packages/core/src/bridge/bridge-context.ts +++ b/packages/core/src/bridge/bridge-context.ts @@ -1,27 +1,8 @@ -// Api-layer extension of @snowluma/bridge's slim BridgeContext. -// -// The slim interface in @snowluma/bridge has the protocol-layer -// surface (identity / events / sendRawPacket / resolveUserUid / next* -// sequence helpers / upload-metadata cache). This file extends it -// with `apis: ApiHub` — the typed bag of Api classes that lives ONLY -// in @snowluma/core, so the bridge package never sees it (avoiding -// a bridge → core cycle). -// -// The 13 Api classes (apis/.ts) import `BridgeContext` from -// here, which gives them `this.ctx.apis.message.sendGroup(...)` type- -// safety alongside the protocol-layer fields. Highway uploaders, -// element-builder, msg-push parsers (all in @snowluma/bridge) import -// the slim version directly from `@snowluma/bridge/bridge-context`. - -import type { BridgeContext as BaseBridgeContext } from '@snowluma/bridge/bridge-context'; +import type { BridgeContext as BaseBridgeContext } from '@snowluma/protocol/bridge-context'; import type { ApiHub } from './apis'; export interface BridgeContext extends BaseBridgeContext { readonly apis: ApiHub; } +export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context'; -// Re-export `UploadedFileMeta` from the slim package so existing -// `import type { UploadedFileMeta } from '<…>/bridge-context'` (or -// from bridge.ts via re-export) keeps working without callers having -// to learn the new package path. -export type { UploadedFileMeta } from '@snowluma/bridge/bridge-context'; diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index b476fcfd..8e455a39 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -1,22 +1,5 @@ -// BridgeInterface — the public Bridge surface for OneBot-side -// consumers. Slimmed down to BridgeContext + the few extra fields -// OneBot reaches into directly (most notably `activePid`). -// -// Most OneBot code paths reach business methods through -// `bridge.apis..method()` — those types come from `ApiHub` -// inside `bridge-context.ts`. The remaining members below are the -// non-Api state that doesn't fit into a typed Api hub. -// -// Internal Api implementations should depend on `BridgeContext` -// instead (the narrower contract). `BridgeInterface` is for callers -// that need the activePid hook or for backwards compatibility with -// pre-#6 code that imported `BridgeInterface` as the bridge type. - import type { BridgeContext } from './bridge-context'; export interface BridgeInterface extends BridgeContext { - /** Last-active process id — used by `OneBotManager` to thread - * per-process state into the right instance. `null` when no - * process has bound yet. */ readonly activePid: number | null; } diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 98cec6ba..f4e560a8 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -1,45 +1,145 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; import type { PacketInfo } from '@snowluma/common/protocol-types'; -import type { BridgeInterface } from './bridge-interface'; -import { IdentityService } from '@snowluma/bridge/identity-service'; -import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/bridge/msg-push'; -import { IncomingPacketPipeline, type CmdParser } from '@snowluma/bridge/packet-pipeline'; -// qq-info types are no longer used directly in this file — they live -// inside the Api classes that own those fetches (apis/contacts.ts). -import { type ApiHub, buildApiHub } from './apis'; - -// Delegated modules -// Group-todo / stranger-status / AI-voice moved to apis/extras.ts. -// Public types stay re-exported through this file for backwards -// compatibility — the OneBot side imports them via `@snowluma/core`. +import { BridgeEventBus } from '@snowluma/protocol/event-bus'; +import { IdentityService } from '@snowluma/protocol/identity-service'; +import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push'; +import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline'; +import { buildApiHub, type ApiHub } from './apis'; import { AiVoiceChatType, type AiVoiceCategory, type StrangerStatus, } from './apis/extras'; -// actions/forward.ts removed — moved to apis/forward.ts::ForwardApi. -// actions/friend.ts removed — moved to apis/friend.ts::FriendApi. -// actions/group-admin.ts removed — moved to `apis/group-admin.ts::GroupAdminApi`. -// actions/group-album.ts removed — moved to `apis/group-album.ts::GroupAlbumApi`. -// Group file CRUD + private c2c upload + media URL resolvers moved to -// `apis.groupFile` (see `apis/group-file.ts::GroupFileApi`). The shared -// result type still lives here because the OneBot side imports it -// through bridge.ts. -import type { GroupFilesResult } from './apis/group-file'; -// actions/group-message.ts removed — `setGroupEssence` moved to -// apis/interaction.ts::InteractionApi. The recall/markRead helpers -// were absorbed into MessageApi back in commit 1. -// actions/interaction.ts removed — sendPoke/sendLike/setReaction/ -// getEmojiLikes moved to apis/interaction.ts::InteractionApi. -// actions/misc.ts removed — moved to apis/misc.ts::MiscApi. -// actions/profile.ts removed — moved to apis/profile.ts::ProfileApi. -// `bridge-contacts.ts` removed — its 6 functions are now methods on -// `apis.contacts` (see `apis/contacts.ts::ContactsApi`). -import { BridgeEventBus } from '@snowluma/bridge/event-bus'; -// web-actions/* removed — moved to apis/web.ts::WebApi. -export { AiVoiceChatType }; -export type { AiVoiceCategory, StrangerStatus }; +import type { BridgeInterface } from './bridge-interface'; + +export class Bridge implements BridgeInterface { + readonly identity: IdentityService; + private pids_ = new Set(); + readonly events = new BridgeEventBus(); + readonly apis: ApiHub; + private readonly pipeline: IncomingPacketPipeline; + private packetClient_: PacketSender | null = null; + private static readonly UPLOADED_FILE_CACHE_MAX = 1024; + private uploadedFileMeta_ = new Map(); + private clientSeq_ = 100000000 + (Date.now() % 1000000000); + private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0; + + constructor(identity: IdentityService) { + this.identity = identity; + this.apis = buildApiHub(this); + this.identity.setFetcher({ + fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin), + fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid), + }); + this.pipeline = new IncomingPacketPipeline({ + identity: this.identity, + events: this.events, + refreshMemberCache: (groupId, refreshGroupList, forceMemberList) => + this.refreshMemberCache(groupId, refreshGroupList, forceMemberList), + resolveStrangerProfile: async (uid) => { + try { + const p = await this.apis.contacts.fetchUserProfileByUid(uid); + if (p.uin <= 0) return null; + return { uin: p.uin, nickname: p.nickname }; + } catch { + return null; + } + }, + resolveGroupJoinRequest: async (groupId, uid, subType) => { + try { + const requests = await this.apis.contacts.fetchGroupRequests(); + const match = requests.find(r => { + if (r.groupId !== groupId) return false; + return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid; + }); + if (!match) return null; + return { comment: match.comment, sequence: match.sequence }; + } catch { + return null; + } + }, + }); + this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush); + } + + dispose(): void { + this.identity.close(); + this.events.clear(); + } + + setPacketClient(client: PacketSender): void { + this.packetClient_ = client; + } + + registerCmd(cmd: string, parser: CmdParser): void { + this.pipeline.registerCmd(cmd, parser); + } + + handlesCmd(cmd: string): boolean { + return this.pipeline.handlesCmd(cmd); + } + + attachPid(pid: number): void { + this.pids_.add(pid); + } + detachPid(pid: number): void { + this.pids_.delete(pid); + } + hasPid(pid: number): boolean { return this.pids_.has(pid); } + get empty(): boolean { return this.pids_.size === 0; } + get activePid(): number | null { + for (const pid of this.pids_) return pid; + return null; + } + onPacket(pkt: PacketInfo): void { + this.pipeline.process(pkt); + } + + private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise { + if (refreshGroupList) { + try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ } + } + if (!this.identity.findGroup(groupId)) return false; + await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList }); + return true; + } + rememberUploadedFile(meta: UploadedFileMeta): void { + if (!meta.fileId) return; + if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) { + // Map iteration order is insertion order — drop the oldest. + const oldest = this.uploadedFileMeta_.keys().next().value; + if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest); + } + this.uploadedFileMeta_.set(meta.fileId, meta); + } + + recallUploadedFile(fileId: string): UploadedFileMeta | undefined { + if (!fileId) return undefined; + return this.uploadedFileMeta_.get(fileId); + } + + nextClientSequence(): number { + return ++this.clientSeq_; + } + + nextMessageRandom(): number { + this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0; + return this.msgRandom_ & 0x7FFFFFFF; + } + async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise { + if (!this.packetClient_) { + return { + success: false, gotResponse: false, errorCode: -1, + errorMessage: 'no packet sender attached', responseData: null, + }; + } + return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs); + } + async resolveUserUid(uin: number, groupId?: number): Promise { + return this.identity.resolveUid(uin, groupId); + } +} export interface SendMessageReceipt { messageId: number; sequence: number; @@ -48,12 +148,6 @@ export interface SendMessageReceipt { timestamp: number; } -/** - * Metadata remembered after `upload_group_file` / `upload_private_file` - * succeeds. Lets the OneBot send-message path reconstruct the full - * payload when the caller only echoes the `file_id` back later. See - * `Bridge.rememberUploadedFile` / `recallUploadedFile`. - */ export interface UploadedFileMeta { fileId: string; scope: 'group' | 'private'; @@ -84,223 +178,6 @@ export interface ClientKeyInfo { expireTime: string; keyIndex: string } - -export class Bridge implements BridgeInterface { - readonly identity: IdentityService; - private pids_ = new Set(); - /** - * Per-kind event subscription. Replaces the legacy single-callback - * firehose: downstream consumers now register exactly the kinds they - * care about and the pipeline fans out in parallel. - */ - readonly events = new BridgeEventBus(); - /** - * Typed Api hub. Each entry is a class encapsulating one logical - * area of the QQ protocol (sending messages, group admin, file - * uploads, etc.). Built eagerly in the constructor — every Bridge - * instance gets its own `apis.*` set with `this` (typed as - * `BridgeContext`) injected. See `apis/index.ts`. - */ - readonly apis: ApiHub; - private readonly pipeline: IncomingPacketPipeline; - private packetClient_: PacketSender | null = null; - // (fetchGroupMemberList throttle cache moved to ContactsApi — same - // 60s TTL + inflight coalesce semantics, just owned by the Api class - // that exposes the method.) - - // ── Uploaded-file metadata cache ──────────────────────────────────── - // - // After a file goes through `upload_group_file` / `upload_private_file` - // we remember the (fileName, fileSize, fileMd5, fileHash) tuple keyed - // by the returned file_id. The OneBot send-message paths consult this - // when the caller later passes `{type:'file', file_id:'xxx'}` without - // the rest of the metadata — c2c file send needs the size/md5/name - // for the wire packet (server-side rejection / "0 byte file" otherwise), - // and the group send path falls back to the name for the log line. - // - // Bounded at ~1024 entries with simple FIFO eviction. Files older - // than 7 days expire on QQ's side anyway, so this isn't load-bearing - // for correctness — just a UX convenience cache so the OneBot caller - // doesn't have to thread the metadata themselves between upload and - // send_msg. - private static readonly UPLOADED_FILE_CACHE_MAX = 1024; - private uploadedFileMeta_ = new Map(); - - // Sequence and random generators for outgoing messages - private clientSeq_ = 100000000 + (Date.now() % 1000000000); - private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0; - - constructor(identity: IdentityService) { - this.identity = identity; - // Build Api hub FIRST — `setFetcher` below installs callbacks - // that reach into `this.apis.contacts.*`, so the hub must exist - // by the time those callbacks could fire. The Bridge instance IS - // the BridgeContext (Bridge implements BridgeInterface which - // includes the BridgeContext surface). - this.apis = buildApiHub(this); - this.identity.setFetcher({ - fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin), - fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid), - }); - this.pipeline = new IncomingPacketPipeline({ - identity: this.identity, - events: this.events, - refreshMemberCache: (groupId, refreshGroupList, forceMemberList) => - this.refreshMemberCache(groupId, refreshGroupList, forceMemberList), - }); - this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush); - } - - dispose(): void { - this.identity.close(); - this.events.clear(); - } - - setPacketClient(client: PacketSender): void { - this.packetClient_ = client; - } - - registerCmd(cmd: string, parser: CmdParser): void { - this.pipeline.registerCmd(cmd, parser); - } - - handlesCmd(cmd: string): boolean { - return this.pipeline.handlesCmd(cmd); - } - - // --- PID management --- - - attachPid(pid: number): void { - this.pids_.add(pid); - } - detachPid(pid: number): void { - this.pids_.delete(pid); - } - hasPid(pid: number): boolean { return this.pids_.has(pid); } - get empty(): boolean { return this.pids_.size === 0; } - get activePid(): number | null { - for (const pid of this.pids_) return pid; - return null; - } - - // --- Packet dispatch --- - - onPacket(pkt: PacketInfo): void { - this.pipeline.process(pkt); - } - - private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise { - if (refreshGroupList) { - try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ } - } - if (!this.identity.findGroup(groupId)) return false; - await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList }); - return true; - } - - // --- Uploaded-file metadata cache --- - - /** - * Remember a freshly-uploaded file so a later `send_*_msg` carrying - * just the file_id can reconstruct the full c2c-file packet (fileName - * / fileSize / fileMd5 are required by the QQ NT server's c2c file - * intake, even if only the uuid is needed for the OIDB lookup - * internally — without them the file shows as 0 B in the recipient's - * chat or is silently rejected). Insertion is FIFO; oldest entry is - * evicted when the cache hits `UPLOADED_FILE_CACHE_MAX`. - */ - rememberUploadedFile(meta: UploadedFileMeta): void { - if (!meta.fileId) return; - if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) { - // Map iteration order is insertion order — drop the oldest. - const oldest = this.uploadedFileMeta_.keys().next().value; - if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest); - } - this.uploadedFileMeta_.set(meta.fileId, meta); - } - - /** - * Recall metadata for a previously-uploaded file. Returns `undefined` - * if the file_id was never uploaded through this bridge instance, or - * if it's been evicted from the cache. - */ - recallUploadedFile(fileId: string): UploadedFileMeta | undefined { - if (!fileId) return undefined; - return this.uploadedFileMeta_.get(fileId); - } - - // --- Sequence / random generators --- - // - // `public` (formerly `private`) because the Api classes in - // `apis/*.ts` need them to build `SendMessageRequest` packets. Part - // of the `BridgeContext` surface, so a third party that only sees - // `BridgeContext` can still synthesise wire packets without reaching - // into the concrete Bridge class. - - nextClientSequence(): number { - return ++this.clientSeq_; - } - - nextMessageRandom(): number { - this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0; - return this.msgRandom_ & 0x7FFFFFFF; - } - - // --- Send packet (raw) --- - - async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise { - if (!this.packetClient_) { - return { - success: false, gotResponse: false, errorCode: -1, - errorMessage: 'no packet sender attached', responseData: null, - }; - } - return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs); - } - - // `Bridge.SEND_MSG_CMD` and the inline `sendGroupMessage` / - // `sendPrivateMessage` / `sendC2cFileMessage` implementations were - // moved to `apis/message.ts::MessageApi` as part of the #6 - // Api-on-ctx refactor. Callers route through `bridge.apis.message.*`. - - // --- Delegated: OIDB helpers --- - - async resolveUserUid(uin: number, groupId?: number): Promise { - return this.identity.resolveUid(uin, groupId); - } - - // fetchFriendList / fetchGroupList / fetchGroupMemberList / - // fetchUserProfile / fetchGroupRequests / fetchDownloadRKeys - // moved to apis.contacts (see apis/contacts.ts::ContactsApi). - - // --- Delegated: action methods --- - // - // GroupAdmin methods (mute/kick/admin/card/name/title/leave/ - // add-option/search/add-request/remark/at-all-remain) moved to - // apis.groupAdmin (apis/group-admin.ts::GroupAdminApi). - // Friend methods (handleRequest/delete/setRemark) moved to - // apis.friend. - // GroupFile methods (upload/uploadPrivate/publish/list/getUrl/ - // getPrivateUrl/{Ptt,Video}Url/getPrivate{Ptt,Video}Url/delete/move/ - // createFolder/deleteFolder/renameFolder/getCount) moved to - // apis.groupFile (apis/group-file.ts::GroupFileApi). - // Forward methods (upload / fetch) moved to apis.forward. - // Interaction methods (sendPoke/sendLike/setReaction/setEssence/ - // getEmojiLikes) moved to apis.interaction. - // recall* / markRead* moved to apis/message.ts::MessageApi. - // GroupAlbum methods (list/upload/getMediaList/comment/like/delete) - // moved to apis.groupAlbum (apis/group-album.ts::GroupAlbumApi). - // Web methods (getHonorInfo / forceFetchClientKey / getEssence / - // getEssenceAll / sendNotice / getNotice / deleteNotice / - // getCookiesStr / getCsrfToken / getCredentials) moved to apis.web. - // Profile methods (setOnlineStatus / setDiyOnlineStatus / setProfile / - // setSelfLongNick / setInputStatus / setAvatar / setGroupAvatar / - // fetchCustomFace / getLike / getUnidirectionalFriendList) moved to - // apis.profile. - // Misc methods (translateEn2Zh / getMiniAppArk / - // clickInlineKeyboardButton / sendGroupSign) moved to apis.misc. - - // --- Tier-2 napcat-parity extras (group todo / stranger status / - // AI voice) moved to apis.extras. --- -} +export { AiVoiceChatType }; +export type { AiVoiceCategory, StrangerStatus }; diff --git a/packages/core/src/bridge/manager.ts b/packages/core/src/bridge/manager.ts index c31a8255..48a9101e 100644 --- a/packages/core/src/bridge/manager.ts +++ b/packages/core/src/bridge/manager.ts @@ -1,8 +1,8 @@ +import { createLogger } from '@snowluma/common/logger'; import type { PacketSender } from '@snowluma/common/packet-sender'; import type { PacketInfo } from '@snowluma/common/protocol-types'; -import { createLogger } from '@snowluma/common/logger'; +import { IdentityService } from '@snowluma/protocol/identity-service'; import { Bridge } from './bridge'; -import { IdentityService } from '@snowluma/bridge/identity-service'; export type SessionStartedCallback = (uin: string, bridge: Bridge) => void; export type SessionClosedCallback = (uin: string) => void; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d365a966..26f84eae 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,8 +1,8 @@ -import { BridgeManager } from './bridge/manager'; -import { OneBotManager } from '@snowluma/onebot/manager'; -import { loadRuntimeConfig } from '@snowluma/common/runtime'; +import { HookManager } from '@snowluma/bridge'; import { closeLogger, createLogger } from '@snowluma/common/logger'; -import { HookManager } from './hook/hook-manager'; +import { loadRuntimeConfig } from '@snowluma/common/runtime'; +import { OneBotManager } from '@snowluma/onebot/manager'; +import { BridgeManager } from './bridge/manager'; const runtimeConfig = loadRuntimeConfig(); const log = createLogger('App'); @@ -12,12 +12,6 @@ async function main() { const bridgeManager = new BridgeManager(); const oneBotManager = new OneBotManager(); - // HookManager defaults its packet sink to bridgeManager.onPacket, so - // every parsed hook packet reaches the per-UIN bridge dispatcher with - // no intermediate layer. - // Env var SNOWLUMA_HOOK_AUTOLOAD wins over runtime.json so Docker / - // headless deployments can flip auto-injection on without touching the - // persisted user config volume. const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad); const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery }); if (autoLoadOnDiscovery) { diff --git a/packages/core/src/webui/auth.ts b/packages/core/src/webui/auth.ts index f10bff81..93e5fae0 100644 --- a/packages/core/src/webui/auth.ts +++ b/packages/core/src/webui/auth.ts @@ -1,7 +1,7 @@ +import { createLogger } from '@snowluma/common/logger'; import { randomBytes, scryptSync, timingSafeEqual } from 'crypto'; import fs from 'fs'; import path from 'path'; -import { createLogger } from '@snowluma/common/logger'; const log = createLogger('WebUI.Auth'); diff --git a/packages/core/src/webui/port.ts b/packages/core/src/webui/port.ts index 8006cc92..ae94181a 100644 --- a/packages/core/src/webui/port.ts +++ b/packages/core/src/webui/port.ts @@ -1,9 +1,5 @@ import net from 'net'; -/** - * Probe whether a TCP port is bindable on the given host. - * Resolves to true when bind+listen succeed. - */ function isPortAvailable(port: number, host = '0.0.0.0'): Promise { return new Promise((resolve) => { const server = net.createServer(); diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 03e19658..0b7099e1 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -1,18 +1,18 @@ import { serve } from '@hono/node-server'; import { serveStatic } from '@hono/node-server/serve-static'; -import { Hono, type Context } from 'hono'; -import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; +import type { HookManager, HookProcessInfo } from '@snowluma/bridge'; import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger'; -import { randomBytes } from 'crypto'; -import type { OneBotManager } from '@snowluma/onebot/manager'; import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config'; +import type { OneBotManager } from '@snowluma/onebot/manager'; import type { OneBotConfig } from '@snowluma/onebot/types'; -import type { HookManager, HookProcessInfo } from '../hook/hook-manager'; -import path from 'path'; +import { randomBytes } from 'crypto'; import { existsSync, readFileSync } from 'fs'; -import { fileURLToPath } from 'url'; +import { Hono, type Context } from 'hono'; import os from 'os'; -import { WebuiAuth, evaluatePasswordRules, isStrongPassword } from './auth'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth'; +import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { findAvailablePort } from './port'; const log = createLogger('WebUI'); @@ -446,8 +446,8 @@ export async function initWebUI( } }; } - app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid))); - app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid))); + app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid))); + app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid))); app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid))); app.get('/api/processes/:pid/probe-login', async (c) => { diff --git a/packages/core/tests/actions/extras.test.ts b/packages/core/tests/actions/extras.test.ts index 66231fb8..d062345f 100644 --- a/packages/core/tests/actions/extras.test.ts +++ b/packages/core/tests/actions/extras.test.ts @@ -1,189 +1,162 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { protobuf_encode } from '@snowluma/proton'; +import { describe, it, expect } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { + OidbGroupTodo, + OidbStrangerStatusReq, OidbStrangerStatusResp, } from '@snowluma/proto-defs/oidb-actions/base'; import type { + OidbAiVoiceListReq, OidbAiVoiceListResp, + OidbAiVoiceReq, OidbAiVoiceResp, } from '@snowluma/proto-defs/oidb-actions/media'; -// `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('@snowluma/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '@snowluma/bridge/bridge-oidb', - ); - return { - ...actual, - runOidb: vi.fn(async () => new Uint8Array()), - makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), - }; -}); - -import * as oidb from '@snowluma/bridge/bridge-oidb'; +// Post-namespace migration: ExtrasApi forwards 6 OIDB cmds through +// namespaces under @snowluma/protocol/oidb-services/extras. Tests assert +// against bridge.sendRawPacket directly. import { ExtrasApi, AiVoiceChatType } from '../../src/bridge/apis/extras'; import { mockBridge } from './_helpers'; -describe('apis/extras / group todo (0xF90)', () => { - beforeEach(() => { - vi.mocked(oidb.runOidb).mockClear(); - vi.mocked(oidb.makeOidbEnvelope).mockClear(); - }); +function packResponse(body: Uint8Array) { + return { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(body), + }; +} +describe('apis/extras / group todo (0xF90)', () => { it.each([ - ['setGroupTodo', 'OidbSvcTrpcTcp.0xf90_1', 1] as const, - ['completeGroupTodo', 'OidbSvcTrpcTcp.0xf90_2', 2] as const, - ['cancelGroupTodo', 'OidbSvcTrpcTcp.0xf90_3', 3] as const, - ])('%s dispatches the right subCmd with shared body', async (method, cmd, subCmd) => { + ['setGroupTodo', 'OidbSvcTrpcTcp.0xf90_1'] as const, + ['completeGroupTodo', 'OidbSvcTrpcTcp.0xf90_2'] as const, + ['cancelGroupTodo', 'OidbSvcTrpcTcp.0xf90_3'] as const, + ])('%s dispatches the right subCmd with shared body', async (method, cmd) => { const bridge = mockBridge(); const api = new ExtrasApi(bridge as any); await (api as any)[method](12345, 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 }); + const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe(cmd); + const env = protobuf_decode>(bytes); + expect(env.body).toEqual({ groupUin: 12345, msgSeq: 9876543210n }); }); }); describe('apis/extras / getStrangerStatus (0xFE1_2)', () => { - 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( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { data: { status: { value: 5n } } } }), - ); + )); await new ExtrasApi(bridge as any).getStrangerStatus(100200); - 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 }] }); + const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2'); + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0xFE1); + expect(env.subCommand).toBe(2); + expect(env.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( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { data: { status: { value: 7n } } } }), - ); + )); expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toEqual({ status: 70, ext_status: 0 }); }); it('high-band values decompose into the (0xff00 + (>>16 & 0xff)) status word', async () => { const bridge = mockBridge(); - // 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( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { data: { status: { value: 0x42F100n } } } }), - ); + )); const status = await new ExtrasApi(bridge as any).getStrangerStatus(1); expect(status).toEqual({ status: 10, ext_status: 0xF142 }); }); it('returns null when the runner throws (transport error)', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockRejectedValueOnce(new Error('boom')); + bridge.sendRawPacket.mockRejectedValueOnce(new Error('boom')); expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull(); }); it('returns null when the server omits the status field', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: {} }), - ); + )); expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toBeNull(); }); }); describe('apis/extras / AI voice (0x929D / 0x929B)', () => { - 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( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { content: fake } } as any), - ); + )); const out = await new ExtrasApi(bridge as any).fetchAiVoiceList(4242, AiVoiceChatType.Sound); expect(out).toEqual(fake); - 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 }); + const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0x929d_0'); + const env = protobuf_decode>(bytes); + expect(env.body).toEqual({ groupUin: 4242, chatType: 1 }); }); it('fetchAiVoiceList returns [] when server replies with no content', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: {} }), - ); + )); const out = await new ExtrasApi(bridge as any).fetchAiVoiceList(1, 1); expect(out).toEqual([]); }); it('fetchAiVoice retries while msgInfo is empty, returns the first IndexNode it sees', async () => { const bridge = mockBridge(); - // 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(protobuf_encode>({ body: { statusCode: 2 } })) - .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [] } } as any })) - .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })); + bridge.sendRawPacket + .mockResolvedValueOnce(packResponse(protobuf_encode>({ body: { statusCode: 2 } } as any))) + .mockResolvedValueOnce(packResponse(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [] } } as any }))) + .mockResolvedValueOnce(packResponse(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any }))); const out = await new ExtrasApi(bridge as any).fetchAiVoice(100, 'voice-id', 'hi', AiVoiceChatType.Sound); expect(out).toMatchObject(node); - expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3); - 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({ + expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3); + const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0x929b_0'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ groupUin: 100, voiceId: 'voice-id', text: 'hi', chatType: 1, }); - // sessionId is randomized but must be a uint32. - expect(body.session.sessionId).toBeTypeOf('number'); - expect(body.session.sessionId).toBeGreaterThanOrEqual(0); - expect(body.session.sessionId).toBeLessThanOrEqual(0xFFFFFFFF); + const sessionId = env.body?.session?.sessionId; + expect(typeof sessionId).toBe('number'); + expect(sessionId).toBeGreaterThanOrEqual(0); + expect(sessionId).toBeLessThanOrEqual(0xFFFFFFFF); }); it('fetchAiVoice throws after exhausting the retry budget', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValue( - protobuf_encode>({ body: { statusCode: 1 } }), - ); + bridge.sendRawPacket.mockResolvedValue(packResponse( + protobuf_encode>({ body: { statusCode: 1 } as any }), + )); await expect(new ExtrasApi(bridge as any).fetchAiVoice(1, 'v', 't', 1, 3)).rejects.toThrow( /AI voice synthesis did not complete/, ); - expect(vi.mocked(oidb.runOidb)).toHaveBeenCalledTimes(3); + expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3); }); it('fetchAiVoice keeps the same sessionId across retries', async () => { const bridge = mockBridge(); - const node = { fileUuid: 'uuid', subType: 0 }; - vi.mocked(oidb.runOidb) - .mockResolvedValueOnce(protobuf_encode>({ body: {} })) - .mockResolvedValueOnce(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })); + const node = { fileUuid: 'uuid', subType: 1 }; + bridge.sendRawPacket + .mockResolvedValueOnce(packResponse(protobuf_encode>({ body: {} }))) + .mockResolvedValueOnce(packResponse(protobuf_encode>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any }))); await new ExtrasApi(bridge as any).fetchAiVoice(1, 'v', 't', 1); - 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); + const env1 = protobuf_decode>(bridge.sendRawPacket.mock.calls[0]![1]); + const env2 = protobuf_decode>(bridge.sendRawPacket.mock.calls[1]![1]); + expect(env1.body?.session?.sessionId).toBe(env2.body?.session?.sessionId); }); }); diff --git a/packages/core/tests/actions/forward-file.test.ts b/packages/core/tests/actions/forward-file.test.ts index 99320d3a..dc67a058 100644 --- a/packages/core/tests/actions/forward-file.test.ts +++ b/packages/core/tests/actions/forward-file.test.ts @@ -25,7 +25,7 @@ import { describe, it, expect, vi } from 'vitest'; -vi.mock('@snowluma/bridge/bridge-oidb', () => ({ +vi.mock('@snowluma/protocol/bridge-oidb', () => ({ runOidb: vi.fn(async () => new Uint8Array()), makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), encodeOidbEnv: vi.fn(() => new Uint8Array()), @@ -40,7 +40,7 @@ vi.mock('@snowluma/bridge/bridge-oidb', () => ({ const { buildSendElemsMock } = vi.hoisted(() => ({ buildSendElemsMock: vi.fn(async (_elements: unknown[], _ctx?: Record) => []), })); -vi.mock('@snowluma/bridge/element-builder', () => ({ +vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: buildSendElemsMock, })); diff --git a/packages/core/tests/actions/forward-nested.test.ts b/packages/core/tests/actions/forward-nested.test.ts new file mode 100644 index 00000000..1d2c97d1 --- /dev/null +++ b/packages/core/tests/actions/forward-nested.test.ts @@ -0,0 +1,181 @@ +// Wire-byte alignment regression for nested forward upload — verifies +// that the OUTER LongMsgResult's `actions[]` carries: +// - `{actionCommand: 'MultiMsg', actionData.msgBody: }` +// - `{actionCommand: , actionData.msgBody: }` +// AND that the same uuid appears as `meta.detail.uniseq` inside the +// LightApp `com.tencent.multimsg` JSON of the outer's preview element +// pointing at the inner res_id. +// +// Without this alignment the QQ-NT recipient has no way to walk the +// piggyback — they see the inner preview's resid, look for a matching +// uniseq among the actions, find none, and either fall back to a fresh +// server fetch (extra latency) or render an empty bubble. +// +// Reference impls cross-checked: +// dev/NapCatQQ/.../SendMsg.ts:208-347 +// dev/Lagrange.Core/.../Message/Entity/MultiMsgEntity.cs:43-115 +// dev/NapCatQQ/.../helper/forward-msg-builder.ts:52-122 + +import { describe, it, expect, vi } from 'vitest'; +import { gunzipSync, inflateSync } from 'zlib'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { SendLongMsgReq, SendLongMsgResp, LongMsgResult } from '@snowluma/proto-defs/longmsg'; +import type { PushMsgBody } from '@snowluma/proto-defs/message'; +import type { Elem } from '@snowluma/proto-defs/element'; + +// Don't mock element-builder — we WANT the real forward preview +// element to land in the encoded wire bytes so we can verify the +// `uniseq` round-trip against the piggyback's `actionCommand`. + +// Mock highway uploads only — they're irrelevant for text-only nodes +// but the import would otherwise pull in the native ffmpeg addon. +vi.mock('@snowluma/protocol/highway/image-upload', () => ({ + uploadImageMsgInfo: vi.fn(async () => new Uint8Array()), +})); +vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ + uploadPttMsgInfo: vi.fn(async () => new Uint8Array()), +})); +vi.mock('@snowluma/protocol/highway/video-upload', () => ({ + uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()), +})); + +import { ForwardApi } from '../../src/bridge/apis/forward'; +import { mockBridge } from './_helpers'; + +function uploadResponseWithResId(resId: string) { + return { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode({ result: { resId } })), + }; +} + +function decodeOuterLongMsg(rawBytes: Uint8Array): LongMsgResult { + const env = protobuf_decode(rawBytes); + const payload = env.info?.payload; + if (!(payload instanceof Uint8Array)) throw new Error('payload missing on the SendLongMsgReq'); + return protobuf_decode(gunzipSync(Buffer.from(payload))); +} + +function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string } | null { + for (const body of msgBody) { + const elems: Elem[] = body.body?.richText?.elems ?? []; + for (const elem of elems) { + if (elem.lightApp?.data && elem.lightApp.data.length > 1) { + const data = elem.lightApp.data; + if (data[0] !== 0x01) continue; + try { + const json = inflateSync(Buffer.from(data.subarray(1))).toString('utf8'); + const parsed = JSON.parse(json); + if (parsed?.app === 'com.tencent.multimsg') { + return { + app: parsed.app, + resid: parsed.meta?.detail?.resid, + uniseq: parsed.meta?.detail?.uniseq, + }; + } + } catch { /* ignore */ } + } + } + } + return null; +} + +describe('forward / nested upload wire alignment', () => { + it('outer LongMsgResult contains both MultiMsg and the inner uuid piggyback action', async () => { + // Inner upload returns inner-res; outer upload returns outer-res. + const responses = ['inner-res', 'outer-res']; + const sendRawPacket = vi.fn(async () => + uploadResponseWithResId(responses.shift()!)) as any; + const bridge = mockBridge({ sendRawPacket }); + + const resId = await new ForwardApi(bridge as any).upload([ + { + userUin: 111, nickname: 'outer', elements: [], + innerForward: [ + { userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] }, + ], + }, + ]); + + expect(resId).toBe('outer-res'); + expect(sendRawPacket).toHaveBeenCalledTimes(2); + + // Second call is the OUTER's upload (the inner went first). + const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array; + const outerLongMsg = decodeOuterLongMsg(outerBytes); + + const actions = outerLongMsg.action ?? []; + expect(actions).toHaveLength(2); + expect(actions[0]!.actionCommand).toBe('MultiMsg'); + // The second action carries the inner's msgBody under a uuid + // actionCommand (NOT 'MultiMsg'). + const piggybackUuid = actions[1]!.actionCommand!; + expect(piggybackUuid).not.toBe('MultiMsg'); + expect(piggybackUuid).toMatch(/^[0-9a-f-]{36}$/i); + expect(actions[1]!.actionData?.msgBody?.length ?? 0).toBeGreaterThan(0); + }); + + it('outer preview LightApp uniseq matches the piggyback actionCommand uuid', async () => { + // This is the alignment bug: without it the QQ-NT receiver + // can't link the inner preview to its piggyback in actions[]. + const responses = ['inner-res-A', 'outer-res-A']; + const sendRawPacket = vi.fn(async () => + uploadResponseWithResId(responses.shift()!)) as any; + const bridge = mockBridge({ sendRawPacket }); + + await new ForwardApi(bridge as any).upload([ + { + userUin: 111, nickname: 'outer', elements: [], + innerForward: [ + { userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] }, + ], + }, + ]); + + const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array; + const outerLongMsg = decodeOuterLongMsg(outerBytes); + + const piggybackUuid = outerLongMsg.action![1]!.actionCommand!; + const outerMsgBody = outerLongMsg.action![0]!.actionData!.msgBody!; + const preview = findLightAppJson(outerMsgBody); + + expect(preview).not.toBeNull(); + expect(preview!.app).toBe('com.tencent.multimsg'); + expect(preview!.resid).toBe('inner-res-A'); + expect(preview!.uniseq).toBe(piggybackUuid); + }); + + it('three-deep nesting: outermost action[] carries 1+2 entries (MultiMsg + 2 piggybacks)', async () => { + // The middle level's upload produces 1 MultiMsg + 1 piggyback + // (for the deepest). The outermost level then concatenates its + // own MultiMsg + the middle's piggyback set, so action[].length = 3. + const responses = ['deepest', 'middle', 'outermost']; + const sendRawPacket = vi.fn(async () => + uploadResponseWithResId(responses.shift()!)) as any; + const bridge = mockBridge({ sendRawPacket }); + + await new ForwardApi(bridge as any).upload([ + { + userUin: 1, nickname: 'L1', elements: [], + innerForward: [{ + userUin: 2, nickname: 'L2', elements: [], + innerForward: [ + { userUin: 3, nickname: 'L3', elements: [{ type: 'text', text: 'deep' }] }, + ], + }], + }, + ]); + + expect(sendRawPacket).toHaveBeenCalledTimes(3); + const outermostBytes = sendRawPacket.mock.calls[2]![1] as Uint8Array; + const outermost = decodeOuterLongMsg(outermostBytes); + expect(outermost.action).toHaveLength(3); + expect(outermost.action![0]!.actionCommand).toBe('MultiMsg'); + expect(outermost.action![1]!.actionCommand).not.toBe('MultiMsg'); + expect(outermost.action![2]!.actionCommand).not.toBe('MultiMsg'); + expect(outermost.action![1]!.actionCommand).not.toBe(outermost.action![2]!.actionCommand); + }); +}); diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index e354478b..fa424d0b 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi } from 'vitest'; -vi.mock('@snowluma/bridge/bridge-oidb', () => ({ +vi.mock('@snowluma/protocol/bridge-oidb', () => ({ runOidb: vi.fn(async () => new Uint8Array()), makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), encodeOidbEnv: vi.fn(() => new Uint8Array()), @@ -10,7 +10,7 @@ vi.mock('@snowluma/bridge/bridge-oidb', () => ({ // element-builder reaches into protoEncode with element-specific schemas // that we don't want to construct manually in tests; stub it to return // a benign placeholder. -vi.mock('@snowluma/bridge/element-builder', () => ({ +vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: vi.fn(async () => []), })); diff --git a/packages/core/tests/actions/friend.test.ts b/packages/core/tests/actions/friend.test.ts index 8f3b0d70..2dba2c47 100644 --- a/packages/core/tests/actions/friend.test.ts +++ b/packages/core/tests/actions/friend.test.ts @@ -1,54 +1,52 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbDeleteFriend, + OidbFriendRequestAction, + OidbSetFriendRemark, +} from '@snowluma/proto-defs/oidb-actions/base'; -vi.mock('@snowluma/bridge/bridge-oidb', () => ({ - runOidb: vi.fn(async () => new Uint8Array()), - makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), - encodeOidbEnv: vi.fn(() => new Uint8Array()), - decodeOidbEnv: vi.fn(() => ({ body: {} })), -})); - -import * as oidb from '@snowluma/bridge/bridge-oidb'; +// Post-namespace migration: FriendApi is a thin facade over the +// namespaces under @snowluma/protocol/oidb-services/friend. Tests assert +// against the bridge mock's sendRawPacket directly — no need for +// module-level bridge-oidb mocks anymore. import { FriendApi } from '../../src/bridge/apis/friend'; import { mockBridge } from './_helpers'; describe('apis/friend', () => { - beforeEach(() => { - vi.mocked(oidb.runOidb).mockClear(); - vi.mocked(oidb.makeOidbEnvelope).mockClear(); - }); - it('handleRequest: numeric input is treated as UIN and resolved', async () => { const bridge = mockBridge(); await new FriendApi(bridge as any).handleRequest('10001', true); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); - const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect(body).toMatchObject({ accept: 3, targetUid: 'resolved-uid' }); + const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0xb5d_44'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ accept: 3, targetUid: 'resolved-uid' }); }); it('handleRequest: non-numeric flag is forwarded as-is', async () => { const bridge = mockBridge(); await new FriendApi(bridge as any).handleRequest('flag-abc', false); expect(bridge.resolveUserUid).not.toHaveBeenCalled(); - const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect(body).toMatchObject({ accept: 5, targetUid: 'flag-abc' }); + const [, bytes] = bridge.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ accept: 5, targetUid: 'flag-abc' }); }); it('delete resolves UID, calls 0x126b_0, and triggers a friend-list refresh', async () => { const bridge = mockBridge(); await new FriendApi(bridge as any).delete(10001, true); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); - const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0x126b_0'); - const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect((body as any).field1.block).toBe(true); + const env = protobuf_decode>(bytes); + expect(env.body?.field1?.block).toBe(true); expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalled(); }); it('delete still succeeds when the friend-list refresh throws', async () => { const bridge = mockBridge(); - // `fetchFriendList` lives on `apis.contacts` post-#6 refactor; - // override the default no-op stub to make the friend-list refresh - // throw and verify delete swallows the error. bridge.apis.contacts.fetchFriendList = vi.fn(async () => { throw new Error('cache miss'); }); await expect(new FriendApi(bridge as any).delete(10001)) .resolves.toBeUndefined(); @@ -57,9 +55,9 @@ describe('apis/friend', () => { it('setRemark resolves UID and sends 0xb6e_2', async () => { const bridge = mockBridge(); await new FriendApi(bridge as any).setRemark(10001, 'best-friend'); - const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0xb6e_2'); - const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect(body).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' }); + const env = protobuf_decode>(bytes); + expect(env.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 fb49e146..008d6fe8 100644 --- a/packages/core/tests/actions/group-admin.test.ts +++ b/packages/core/tests/actions/group-admin.test.ts @@ -1,72 +1,73 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { protobuf_encode } from '@snowluma/proton'; +import { describe, it, expect, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { Oidb0x8a7Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { + Oidb0x8a0Req, + Oidb0x8a7Resp, + Oidb0x89a_0AddOption, + Oidb0x89a_0Search, + Oidb0xf16Req, + OidbGroupRequestAction, + OidbKickMember, + OidbLeaveGroup, + OidbMuteAll, + OidbMuteMember, + OidbRenameGroup, + OidbRenameMember, + OidbSetAdmin, + OidbSpecialTitle, +} from '@snowluma/proto-defs/oidb-actions/base'; -// `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('@snowluma/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '@snowluma/bridge/bridge-oidb', - ); - return { - ...actual, - runOidb: vi.fn(async () => new Uint8Array()), - makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), - }; -}); - -import * as oidb from '@snowluma/bridge/bridge-oidb'; +// Post-namespace migration: GroupAdminApi forwards through namespaces +// under @snowluma/protocol/oidb-services/group-admin. Tests assert +// against bridge.sendRawPacket directly — no module-level mocks. import { GroupAdminApi } from '../../src/bridge/apis/group-admin'; import { mockBridge } from './_helpers'; -describe('actions/group-admin', () => { - beforeEach(() => { - vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); - vi.mocked(oidb.makeOidbEnvelope).mockClear(); - }); +function packResponse(body: Uint8Array) { + return { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(body), + }; +} - it('muteGroupMember resolves UID and dispatches 0x1253_1', async () => { +describe('apis/group-admin', () => { + it('muteMember resolves UID and dispatches 0x1253_1', async () => { const bridge = mockBridge(); await new GroupAdminApi(bridge as any).muteMember(12345, 67890, 600); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345); - expect(oidb.runOidb).toHaveBeenCalledOnce(); - const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + const [cmd, bytes] = bridge.sendRawPacket.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({ + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0x1253); + expect(env.subCommand).toBe(1); + expect(env.body).toMatchObject({ groupUin: 12345, type: 1, body: { targetUid: 'resolved-uid', duration: 600 }, }); }); - it('muteGroupAll flips the muteState flag based on enable', async () => { + it('muteAll flips the muteState flag based on enable', async () => { const bridge = mockBridge(); await new GroupAdminApi(bridge as any).muteAll(12345, true); - expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ - groupUin: 12345, - muteState: { state: 0xFFFFFFFF }, - }); + const env1 = protobuf_decode>(bridge.sendRawPacket.mock.calls[0]![1]); + expect(env1.body).toMatchObject({ groupUin: 12345, muteState: { state: 0xFFFFFFFF } }); await new GroupAdminApi(bridge as any).muteAll(12345, false); - expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2]).toMatchObject({ - muteState: { state: 0 }, - }); + const env2 = protobuf_decode>(bridge.sendRawPacket.mock.calls[1]![1]); + // proto3 default 0 fields are omitted on the wire — equivalent to "state=0". + expect(env2.body?.muteState?.state ?? 0).toBe(0); }); - it('kickGroupMember resolves UID per-group and forwards reject + reason', async () => { + it('kickMember resolves UID per-group and forwards reject + reason', async () => { const bridge = mockBridge(); await new GroupAdminApi(bridge as any).kickMember(12345, 67890, true, 'bad behaviour'); expect(bridge.resolveUserUid).toHaveBeenCalledWith(67890, 12345); - expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ + const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x8a0_1'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ groupUin: 12345, targetUid: 'resolved-uid', rejectAddRequest: true, @@ -74,7 +75,7 @@ describe('actions/group-admin', () => { }); }); - it('kickGroupMembers resolves each UID in parallel', async () => { + it('kickMembers resolves each UID in parallel', async () => { const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid) .mockResolvedValueOnce('uid-a') @@ -82,28 +83,30 @@ describe('actions/group-admin', () => { await new GroupAdminApi(bridge as any).kickMembers(12345, [11, 22], false); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); - const payload: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect(payload.targetUids).toEqual(['uid-a', 'uid-b']); - expect(payload.rejectAddRequest).toBe(0); + const env = protobuf_decode>(bridge.sendRawPacket.mock.calls[0]![1]); + expect(env.body?.targetUids).toEqual(['uid-a', 'uid-b']); + expect(env.body?.rejectAddRequest ?? 0).toBe(0); }); - it('leaveGroup sends 0x1097_1 with the groupUin', async () => { + it('leave sends 0x1097_1 with the groupUin', async () => { const bridge = mockBridge(); await new GroupAdminApi(bridge as any).leave(12345); - const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0x1097_1'); - expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ groupUin: 12345 }); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ groupUin: 12345 }); }); - it('setGroupAdmin resolves UID and sends 0x1096_1', async () => { + it('setAdmin resolves UID and sends 0x1096_1', async () => { const bridge = mockBridge(); await new GroupAdminApi(bridge as any).setAdmin(12345, 67890, true); - expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]).toMatchObject({ - groupUin: 12345, uid: 'resolved-uid', isAdmin: true, - }); + const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x1096_1'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ groupUin: 12345, uid: 'resolved-uid', isAdmin: true }); }); - it('setGroupCard / setGroupName / setGroupSpecialTitle / setGroupRemark / setGroupAddOption / setGroupSearch dispatch the right command', async () => { + it('setCard / setName / setSpecialTitle / setRemark / setAddOption / setSearch dispatch the right command', async () => { const bridge = mockBridge(); await new GroupAdminApi(bridge as any).setCard(1, 2, 'newCard'); await new GroupAdminApi(bridge as any).setName(1, 'newName'); @@ -112,7 +115,7 @@ describe('actions/group-admin', () => { await new GroupAdminApi(bridge as any).setAddOption(1, 2); await new GroupAdminApi(bridge as any).setSearch(1); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]); + const cmds = bridge.sendRawPacket.mock.calls.map(call => call[0]); expect(cmds).toEqual([ 'OidbSvcTrpcTcp.0x8fc_3', 'OidbSvcTrpcTcp.0x89a_15', @@ -121,34 +124,58 @@ describe('actions/group-admin', () => { 'OidbSvcTrpcTcp.0x89a_0', 'OidbSvcTrpcTcp.0x89a_0', ]); + + const cardEnv = protobuf_decode>(bridge.sendRawPacket.mock.calls[0]![1]); + expect(cardEnv.body).toMatchObject({ groupUin: 1, body: { targetUid: 'resolved-uid', targetName: 'newCard' } }); + + const nameEnv = protobuf_decode>(bridge.sendRawPacket.mock.calls[1]![1]); + expect(nameEnv.body).toMatchObject({ groupUin: 1, body: { targetName: 'newName' } }); + + const titleEnv = protobuf_decode>(bridge.sendRawPacket.mock.calls[2]![1]); + // expireTime is proto int_32 with -1 sentinel; after wire round-trip the + // proton decoder surfaces it as the unsigned reinterpretation (-1 ≡ 0xFFFFFFFF). + expect(titleEnv.body?.groupUin).toBe(1); + expect(titleEnv.body?.body?.targetUid).toBe('resolved-uid'); + expect(titleEnv.body?.body?.specialTitle).toBe('newTitle'); + expect(titleEnv.body?.body?.expireTime).toBe(0xFFFFFFFF); + + const remarkEnv = protobuf_decode>(bridge.sendRawPacket.mock.calls[3]![1]); + expect(remarkEnv.body?.inner).toMatchObject({ groupId: 1n, remark: 'newRemark' }); + + const addOptEnv = protobuf_decode>(bridge.sendRawPacket.mock.calls[4]![1]); + expect(addOptEnv.body).toMatchObject({ groupUin: 1n, settings: { addType: 2 } }); + + const searchEnv = protobuf_decode>(bridge.sendRawPacket.mock.calls[5]![1]); + expect(searchEnv.body?.groupUin).toBe(1n); }); - it('setGroupAddRequest picks _1 / _2 based on filtered flag', async () => { + it('setAddRequest picks _1 / _2 based on filtered flag', async () => { const bridge = mockBridge(); await new GroupAdminApi(bridge as any).setAddRequest(12345, 5, 1, true, 'ok', false); await new GroupAdminApi(bridge as any).setAddRequest(12345, 5, 1, false, 'no', true); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(call => call[1]); + const cmds = bridge.sendRawPacket.mock.calls.map(call => call[0]); expect(cmds).toEqual([ 'OidbSvcTrpcTcp.0x10c8_1', 'OidbSvcTrpcTcp.0x10c8_2', ]); - const firstBody: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect(firstBody.accept).toBe(1); - expect(firstBody.body.message).toBe('ok'); + const env1 = protobuf_decode>(bridge.sendRawPacket.mock.calls[0]![1]); + expect(env1.reserved).toBe(1); // uinForm + expect(env1.body?.accept).toBe(1); + expect(env1.body?.body?.message).toBe('ok'); - const secondBody: any = vi.mocked(oidb.makeOidbEnvelope).mock.calls[1]![2]; - expect(secondBody.accept).toBe(2); + const env2 = protobuf_decode>(bridge.sendRawPacket.mock.calls[1]![1]); + expect(env2.body?.accept).toBe(2); }); - it('getGroupAtAllRemain decodes the response and converts BigInts', async () => { + it('getAtAllRemain decodes the response and converts BigInts', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { canAtAll: true, groupRemain: 12, uinRemain: 5 } as any, }), - ); + )); const out = await new GroupAdminApi(bridge as any).getAtAllRemain(12345); expect(out).toEqual({ can_at_all: true, @@ -157,13 +184,19 @@ describe('actions/group-admin', () => { }); }); - it('getGroupAtAllRemain throws when the response is empty', async () => { + it('getAtAllRemain falls back to zero / false when the response is empty', async () => { const bridge = mockBridge(); - // An empty OidbBase envelope (no body) — production code sees `body` - // undefined and throws the "empty" error. - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + // Empty OidbBase envelope (no body) — invokeOidb substitutes `{}` + // for the deserialize argument; canAtAll/groupRemain/uinRemain + // become undefined and get coerced to false/0. + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({}), - ); - await expect(new GroupAdminApi(bridge as any).getAtAllRemain(12345)).rejects.toThrow(/empty/); + )); + const out = await new GroupAdminApi(bridge as any).getAtAllRemain(12345); + expect(out).toEqual({ + can_at_all: false, + remain_at_all_count_for_group: 0, + remain_at_all_count_for_uin: 0, + }); }); }); diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 3250f35a..2894ffa8 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -1,39 +1,33 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { protobuf_encode } from '@snowluma/proton'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { OidbGroupFileCountViewResp, + OidbGroupFileReq, OidbGroupFileResp, OidbGroupFileViewResp, OidbGroupFileFolderResp, + OidbGroupSendFileReq, } from '@snowluma/proto-defs/oidb-actions/group-file'; import type { OidbPrivateFileUploadResp, NTV2RichMediaResp, } from '@snowluma/proto-defs/oidb-actions/media'; -// `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('@snowluma/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '@snowluma/bridge/bridge-oidb', - ); - return { - ...actual, - runOidb: vi.fn(async () => new Uint8Array()), - makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), - }; -}); +// Post-namespace migration: GroupFileApi forwards single-OIDB methods +// through namespaces under @snowluma/protocol/oidb-services/group-file. +// The multi-stage methods (`upload` / `uploadPrivate`) keep their +// orchestration on the facade; we assert against bridge.sendRawPacket +// directly. Highway calls (fetchHighwaySession / uploadHighwayHttp) +// and the file-source loader are still module-mocked because the +// facade owns those calls directly. -vi.mock('@snowluma/bridge/highway', () => ({ +vi.mock('@snowluma/protocol/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({})), uploadHighwayHttp: vi.fn(async () => undefined), })); -vi.mock('@snowluma/bridge/highway/utils', () => ({ +vi.mock('@snowluma/protocol/highway/utils', () => ({ loadBinarySource: vi.fn(async (_src: string, fallback: string) => ({ bytes: new Uint8Array([1, 2, 3]), fileName: `${fallback}.bin`, @@ -43,55 +37,56 @@ vi.mock('@snowluma/bridge/highway/utils', () => ({ FILE_UPLOAD_MAX_BYTES: 4 * 1024 * 1024 * 1024, })); -import * as oidb from '@snowluma/bridge/bridge-oidb'; -import * as highwayClient from '@snowluma/bridge/highway'; +import * as highwayClient from '@snowluma/protocol/highway'; import { GroupFileApi } from '../../src/bridge/apis/group-file'; import { mockBridge } from './_helpers'; -describe('actions/group-file', () => { +function packResponse(body: Uint8Array) { + return { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(body), + }; +} + +describe('apis/group-file', () => { beforeEach(() => { - vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); - vi.mocked(oidb.makeOidbEnvelope).mockClear(); vi.mocked(highwayClient.fetchHighwaySession).mockClear(); vi.mocked(highwayClient.uploadHighwayHttp).mockClear(); }); it('getCount returns { fileCount, maxCount } from the OIDB response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { count: { fileCount: 42, maxCount: 1000 } }, }), - ); + )); const out = await new GroupFileApi(bridge as any).getCount(12345); expect(out).toEqual({ fileCount: 42, maxCount: 1000 }); }); it('getCount falls back to defaults on partial response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { count: {} } }), - ); + )); const out = await new GroupFileApi(bridge as any).getCount(12345); expect(out).toEqual({ fileCount: 0, maxCount: 10000 }); }); it('upload skips highway when boolFileExist is true', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { - // retCode 0 omitted by proto3 — production only checks against nonzero fileId: 'fid-xyz', boolFileExist: true, }, } as any, }), - ); + )); const api = new GroupFileApi(bridge as any); - // Suppress the auto-publish — that path is covered separately. vi.spyOn(api, 'publish').mockResolvedValue(); const out = await api.upload(12345, '/path/file.bin'); expect(out).toEqual({ fileId: 'fid-xyz' }); @@ -101,13 +96,12 @@ describe('actions/group-file', () => { it('upload runs highway PUT when boolFileExist is false', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( 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". + // boolFileExist is the proto3 default (false) — omit. uploadIp: '1.2.3.4', uploadPort: 8080, fileKey: new Uint8Array([9]), @@ -115,7 +109,7 @@ describe('actions/group-file', () => { }, } as any, }), - ); + )); const api = new GroupFileApi(bridge as any); vi.spyOn(api, 'publish').mockResolvedValue(); await api.upload(12345, '/path/file.bin'); @@ -125,20 +119,20 @@ describe('actions/group-file', () => { it('upload throws on missing upload response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: {} }), - ); + )); await expect(new GroupFileApi(bridge as any).upload(12345, '/path/file.bin')) .rejects.toThrow(/response missing/); }); it('upload bubbles up OIDB retCode errors', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { retCode: 999, retMsg: 'quota exceeded' } as any }, }), - ); + )); await expect(new GroupFileApi(bridge as any).upload(12345, '/path/file.bin')) .rejects.toThrow(/code=999/); }); @@ -146,17 +140,13 @@ describe('actions/group-file', () => { it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => { // Reproduces the bug report: OIDB upload + highway PUT alone only // stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB - // call the file never appears in the chat. Earlier attempts used - // PbSendMsg with a transElem(24) but the QQ-NT server rejects that - // with result=79 (transElem(24) is a receive-side decoding shape, - // not a send-side one). Asserts that `this.publish` is invoked - // with the uploaded fileId. + // call the file never appears in the chat. const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { fileId: 'fid-pub', boolFileExist: true } as any }, }), - ); + )); const api = new GroupFileApi(bridge as any); const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue(); await api.upload(12345, '/path/some-file.bin', 'mynote.txt'); @@ -164,18 +154,16 @@ describe('actions/group-file', () => { const [groupId, fileId] = publishSpy.mock.calls[0]!; expect(groupId).toBe(12345); expect(fileId).toBe('fid-pub'); - // sendGroup must NOT be touched — the previous wire shape - // (PbSendMsg w/ transElem(24)) is the bug we're guarding against. expect(bridge.apis.message.sendGroup).not.toHaveBeenCalled(); }); it('upload skips the chat post when uploadFile=false', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { fileId: 'fid-skip', boolFileExist: true } as any }, }), - ); + )); const api = new GroupFileApi(bridge as any); const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue(); await api.upload(12345, '/path/file.bin', '', '/', false); @@ -184,11 +172,11 @@ describe('actions/group-file', () => { it('upload returns success even when the chat post fails (file is still uploaded)', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { fileId: 'fid-tolerant', boolFileExist: true } as any }, }), - ); + )); const api = new GroupFileApi(bridge as any); const publishSpy = vi.spyOn(api, 'publish').mockRejectedValueOnce(new Error('message rejected')); const out = await api.upload(12345, '/path/file.bin'); @@ -197,15 +185,12 @@ describe('actions/group-file', () => { }); it('upload caches the upload metadata for later resend by file_id', async () => { - // After upload, a later `send_group_msg` carrying just the file_id - // needs to recover the name/size/md5 from somewhere. Production - // populates `ctx.rememberUploadedFile` with the full tuple. const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { fileId: 'fid-cached', boolFileExist: true } as any }, }), - ); + )); const api = new GroupFileApi(bridge as any); vi.spyOn(api, 'publish').mockResolvedValue(); await api.upload(12345, '/path/x.bin', 'x.bin'); @@ -220,30 +205,23 @@ describe('actions/group-file', () => { }); it('publish hits OIDB 0x6d9_4 with the right body', async () => { - // Direct cover of the new bridge method. The previous send-shape - // (PbSendMsg + transElem(24)) failed with result=79; this is the - // Lagrange-V2-mirrored fix. const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce(new Uint8Array()); await new GroupFileApi(bridge as any).publish(12345, 'fid-publish'); - expect(oidb.runOidb).toHaveBeenCalledOnce(); - const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; - expect(cmd).toBe('OidbSvcTrpcTcp.0x6d9_4'); - // The envelope wraps a `{body: {groupUin, type=2, info: {busiType=102, fileId, ...}}}`. - expect(oidb.makeOidbEnvelope).toHaveBeenCalledWith( - 0x6D9, 4, - expect.objectContaining({ - body: expect.objectContaining({ - groupUin: 12345, - type: 2, - info: expect.objectContaining({ - busiType: 102, - fileId: 'fid-publish', - field5: true, - }), - }), + expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); + const [wire, bytes] = bridge.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x6d9_4'); + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0x6D9); + expect(env.subCommand).toBe(4); + expect(env.body?.body).toMatchObject({ + groupUin: 12345, + type: 2, + info: expect.objectContaining({ + busiType: 102, + fileId: 'fid-publish', + field5: true, }), - ); + }); }); it('uploadPrivate resolves both target + self UID before OIDB call', async () => { @@ -258,31 +236,26 @@ describe('actions/group-file', () => { }, }); vi.mocked(bridge.resolveUserUid) - .mockResolvedValueOnce('target-uid') // target user - .mockResolvedValueOnce('self-uid-resolved'); // self fallback - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + .mockResolvedValueOnce('target-uid') + .mockResolvedValueOnce('self-uid-resolved'); + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { uuid: 'fid', fileAddon: 'hash', boolFileExist: true } as any }, }), - ); + )); const out = await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file'); expect(out).toEqual({ fileId: 'fid', fileHash: 'hash' }); expect(bridge.resolveUserUid).toHaveBeenCalledTimes(2); }); it('uploadPrivate publishes the file via apis.message.sendC2cFile after upload', async () => { - // C2C files use `RichText.notOnlineFile` (not in the elems array), - // so `uploadPrivate` calls the dedicated `sendC2cFile` path on - // the bridge rather than `sendPrivate`. Same bug class as the - // group case — without this the recipient sees no message even - // though the bytes are on the server. const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any }, }), - ); + )); await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/private-file.bin', 'doc.pdf'); expect(bridge.apis.message.sendC2cFile).toHaveBeenCalledOnce(); const [userUin, userUid, info] = bridge.apis.message.sendC2cFile.mock.calls[0]!; @@ -293,18 +266,13 @@ describe('actions/group-file', () => { }); it('uploadPrivate caches the upload metadata for later resend by file_id', async () => { - // C2C file resend (send_private_msg with just file_id) was the - // "sends a 0 B file" bug: the wire packet needs fileSize/fileMd5/ - // fileName/fileHash, but the OneBot caller only knows the file_id. - // Caching the upload tuple lets the OneBot send-message path - // recover the rest via `ctx.recallUploadedFile(fileId)`. const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { uuid: 'pfid-cache', fileAddon: 'addon-hash', boolFileExist: true } as any }, }), - ); + )); await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/cache-me.txt', 'cache-me.txt'); expect(bridge.rememberUploadedFile).toHaveBeenCalledOnce(); const [meta] = bridge.rememberUploadedFile.mock.calls[0]!; @@ -320,32 +288,24 @@ describe('actions/group-file', () => { it('uploadPrivate skips the chat post when uploadFile=false', async () => { const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { uuid: 'pfid', fileAddon: 'phash', boolFileExist: true } as any }, }), - ); + )); await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file', '', false); expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled(); }); it('uploadPrivate reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => { - // The 2026 QQ-NT server rollout moved the upload host out of the - // legacy `uploadIp` (field 60) string into the new - // `rtpMediaPlatformUploadAddress` (field 210, repeated IPv4 message). - // Mirrors acidify's `UploadPrivateFile.kt` consumer logic — read - // `inIP` (LAN, same DC as the OIDB endpoint) and pair with `inPort`. - // The int is little-endian-packed: 0x0101A8C0 → 192.168.1.1. const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { uuid: 'pfid', fileAddon: 'phash', - // boolFileExist defaults to false — forces highway path - // 192.168.1.1 little-endian packed = (1 << 24) | (1 << 16) | (168 << 8) | 192 = 16885952 rtpMediaPlatformUploadAddress: [ { outIP: 0, outPort: 0, inIP: 16885952, inPort: 8080, iPType: 1 }, ], @@ -353,59 +313,46 @@ describe('actions/group-file', () => { } as any, }, }), - ); + )); await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin'); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); }); it('uploadPrivate falls back to uploadDomain when uploadIp is empty', async () => { - // Regression: the server has been observed in the wild returning the - // highway host in `uploadDomain` (field 70) instead of `uploadIp` - // (field 60), causing "private file upload host is invalid". The - // helper should walk the parallel host fields rather than dying on - // a single missing slot. Cross-referenced against napcat's proto - // (`Oidb.0XE37_800.ts` ApplyUploadRespV3) — fields 60/70/130/150/160 - // all carry plausible host values from the same server endpoint. const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { uuid: 'pfid', fileAddon: 'phash', - // boolFileExist defaults to false (proto3) — forces the - // highway path where the host fields actually matter. uploadDomain: 'upload.qpic.cn', uploadPort: 8080, mediaPlatformUploadKey: new Uint8Array([1, 2, 3]), } as any, }, }), - ); + )); await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin'); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); }); it('uploadPrivate throws "host is invalid" only when every host field is empty', async () => { - // The diagnostic warn-log lists every host slot to help users - // report which one the server actually populated; this test just - // asserts that the throw still fires when none of them carry a - // value (boolFileExist=false + no usable host). const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { upload: { uuid: 'pfid', fileAddon: 'phash', uploadPort: 8080 } as any }, }), - ); + )); await expect(new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file.bin')) .rejects.toThrow(/upload host is invalid/); }); it('list paginates files + folders out of OIDB items', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { list: { @@ -417,7 +364,7 @@ describe('actions/group-file', () => { } as any, }, }), - ); + )); const out = await new GroupFileApi(bridge as any).list(12345); expect(out.files).toHaveLength(1); expect(out.files[0]).toMatchObject({ fileId: 'f1', fileName: 'a.txt', uploader: 1, uploaderName: 'alice' }); @@ -427,7 +374,7 @@ describe('actions/group-file', () => { it('getUrl builds the https URL from downloadDns + hex-encoded path', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { download: { @@ -436,49 +383,53 @@ describe('actions/group-file', () => { } as any, }, }), - ); + )); const url = await new GroupFileApi(bridge as any).getUrl(12345, 'fid-xyz'); expect(url).toBe('https://cdn.example.com/ftn_handler/0102/?fname=fid-xyz'); }); it('getUrl throws when response is missing dns or url', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { download: {} as any }, }), - ); + )); await expect(new GroupFileApi(bridge as any).getUrl(12345, 'fid-xyz')) .rejects.toThrow(/invalid/); }); it('delete / move dispatch the right sub-commands', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb) - .mockResolvedValueOnce(protobuf_encode>({ body: { delete: {} as any } })) - .mockResolvedValueOnce(protobuf_encode>({ body: { move: {} as any } })); + bridge.sendRawPacket + .mockResolvedValueOnce(packResponse(protobuf_encode>({ body: { delete: {} as any } }))) + .mockResolvedValueOnce(packResponse(protobuf_encode>({ body: { move: {} as any } }))); const api = new GroupFileApi(bridge as any); await api.delete(12345, 'fid'); await api.move(12345, 'fid', '/a', '/b'); - expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[1])).toEqual([3, 5]); + const env1 = protobuf_decode>(bridge.sendRawPacket.mock.calls[0]![1]); + const env2 = protobuf_decode>(bridge.sendRawPacket.mock.calls[1]![1]); + expect(env1.subCommand).toBe(3); + expect(env2.subCommand).toBe(5); }); it('createFolder / deleteFolder / renameFolder dispatch 0x6d7 family', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb) - .mockResolvedValueOnce(protobuf_encode>({ body: { create: {} as any } })) - .mockResolvedValueOnce(protobuf_encode>({ body: { delete: {} as any } })) - .mockResolvedValueOnce(protobuf_encode>({ body: { rename: {} as any } })); + bridge.sendRawPacket + .mockResolvedValueOnce(packResponse(protobuf_encode>({ body: { create: {} as any } }))) + .mockResolvedValueOnce(packResponse(protobuf_encode>({ body: { delete: {} as any } }))) + .mockResolvedValueOnce(packResponse(protobuf_encode>({ body: { rename: {} as any } }))); const api = new GroupFileApi(bridge as any); await api.createFolder(1, 'folder'); await api.deleteFolder(1, 'fid'); await api.renameFolder(1, 'fid', 'newname'); - expect(vi.mocked(oidb.makeOidbEnvelope).mock.calls.map(c => c[0])).toEqual([0x6D7, 0x6D7, 0x6D7]); + const cmds = bridge.sendRawPacket.mock.calls.map(c => c[0]); + expect(cmds).toEqual(['OidbSvcTrpcTcp.0x6d7_0', 'OidbSvcTrpcTcp.0x6d7_1', 'OidbSvcTrpcTcp.0x6d7_2']); }); it('get*Url builds https://domain/path?rkey from the NTV2 response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValue( + bridge.sendRawPacket.mockResolvedValue(packResponse( protobuf_encode>({ body: { respHead: {}, @@ -488,7 +439,7 @@ describe('actions/group-file', () => { } as any, } as any, }), - ); + )); const url = await new GroupFileApi(bridge as any).getVideoUrl(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 56ffcdcf..a607dedb 100644 --- a/packages/core/tests/actions/group-message.test.ts +++ b/packages/core/tests/actions/group-message.test.ts @@ -6,7 +6,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -vi.mock('@snowluma/bridge/bridge-oidb', () => ({ +vi.mock('@snowluma/protocol/bridge-oidb', () => ({ runOidb: vi.fn(async () => new Uint8Array()), makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), encodeOidbEnv: vi.fn(() => new Uint8Array()), diff --git a/packages/core/tests/actions/interaction.test.ts b/packages/core/tests/actions/interaction.test.ts index 7d5705b6..a2d6dc65 100644 --- a/packages/core/tests/actions/interaction.test.ts +++ b/packages/core/tests/actions/interaction.test.ts @@ -1,66 +1,44 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect } from 'vitest'; import { protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { Oidb0x9083Resp } from '@snowluma/proto-defs/oidb-actions/base'; -// `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('@snowluma/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '@snowluma/bridge/bridge-oidb', - ); - return { - ...actual, - runOidb: vi.fn(async () => new Uint8Array()), - makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), - }; -}); - -import * as oidb from '@snowluma/bridge/bridge-oidb'; +// Post-namespace-migration: InteractionApi is a thin facade and +// production code routes through the namespace path (sender → +// sendRawPacket). Tests now assert against the bridge mock's +// sendRawPacket directly — no need for module-level mocks on the +// bridge-oidb internals. import { InteractionApi } from '../../src/bridge/apis/interaction'; import { mockBridge } from './_helpers'; describe('apis/interaction', () => { - beforeEach(() => { - vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); - vi.mocked(oidb.makeOidbEnvelope).mockClear(); - }); it('sendPoke group: groupUin set, friendUin=0', async () => { const bridge = mockBridge(); await new InteractionApi(bridge as any).sendPoke(true, 12345, 67890); - const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect(body).toMatchObject({ uin: 67890, groupUin: 12345, friendUin: 0 }); + expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xed3_1'); }); it('sendPoke friend: friendUin set, groupUin=0, targetUin defaults to peer', async () => { const bridge = mockBridge(); await new InteractionApi(bridge as any).sendPoke(false, 67890); - const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect(body).toMatchObject({ uin: 67890, groupUin: 0, friendUin: 67890 }); + expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xed3_1'); }); it('sendLike forwards target + count to 0x7e5_104', async () => { const bridge = mockBridge(); await new InteractionApi(bridge as any).sendLike(10001, 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 }); + expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x7e5_104'); }); it('setReaction picks _1 for set and _2 for unset', async () => { + // setReaction now forwards through the SetReaction namespace, which + // calls bridge.sendRawPacket directly (bypassing runOidb). const bridge = mockBridge(); const api = new InteractionApi(bridge as any); await api.setReaction(12345, 99, '128516', true); await api.setReaction(12345, 99, '128516', false); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]); + const cmds = bridge.sendRawPacket.mock.calls.map((c: any[]) => c[0]); expect(cmds).toEqual(['OidbSvcTrpcTcp.0x9082_1', 'OidbSvcTrpcTcp.0x9082_2']); }); @@ -69,31 +47,33 @@ describe('apis/interaction', () => { const api = new InteractionApi(bridge as any); await api.setEssence(12345, 99, 0, true); await api.setEssence(12345, 99, 0, false); - const cmds = vi.mocked(oidb.runOidb).mock.calls.map(c => c[1]); + const cmds = bridge.sendRawPacket.mock.calls.map((c: any[]) => c[0]); expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']); }); it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ body: { - inner: { userInfo: { uin: 10001n } }, + inner: { userInfo: [{ uin: 10001n }, { uin: 20002n }] }, cookie: new Uint8Array([0xCA, 0xFE]), } as any, - }), - ); + })), + }); const out = await new InteractionApi(bridge as any).getEmojiLikes(12345, 99, '128516'); - expect(out.users).toEqual([{ uin: 10001 }]); + expect(out.users).toEqual([{ uin: 10001 }, { uin: 20002 }]); expect(out.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64')); expect(out.isLast).toBe(false); }); it('getEmojiLikes reports isLast=true when no cookie comes back', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ body: {} }), - ); + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ body: {} })), + }); const out = await new InteractionApi(bridge as any).getEmojiLikes(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 0c95a387..d60483d6 100644 --- a/packages/core/tests/actions/misc.test.ts +++ b/packages/core/tests/actions/misc.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; import { protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { @@ -6,64 +6,49 @@ import type { Oidb0x112eResp, } from '@snowluma/proto-defs/oidb-actions/base'; -// `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('@snowluma/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '@snowluma/bridge/bridge-oidb', - ); - return { - ...actual, - runOidb: vi.fn(async () => new Uint8Array()), - makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })), - }; -}); - -import * as oidb from '@snowluma/bridge/bridge-oidb'; +// Post-namespace migration: MiscApi forwards 3 OIDB cmds through +// @snowluma/protocol/oidb-services/misc namespaces. The non-OIDB +// `getMiniAppArk` (LightAppSvc) stays inline on the facade. Tests +// hit bridge.sendRawPacket directly. import { MiscApi } from '../../src/bridge/apis/misc'; import { mockBridge } from './_helpers'; -describe('apis/misc', () => { - beforeEach(() => { - vi.mocked(oidb.runOidb).mockReset(); - vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array()); - vi.mocked(oidb.makeOidbEnvelope).mockClear(); - }); +function packResponse(body: Uint8Array) { + return { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(body), + }; +} +describe('apis/misc', () => { it('translateEn2Zh returns dstWords when present', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { translateResp: { dstWords: ['你好', '世界'] } } as any, }), - ); - const out = await new MiscApi(bridge as any).translateEn2Zh( ['hello', 'world']); + )); + const out = await new MiscApi(bridge as any).translateEn2Zh(['hello', 'world']); expect(out).toEqual(['你好', '世界']); }); it('translateEn2Zh throws on empty response', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: {} }), - ); - await expect(new MiscApi(bridge as any).translateEn2Zh( ['hello'])) + )); + await expect(new MiscApi(bridge as any).translateEn2Zh(['hello'])) .rejects.toThrow(/empty/); }); it('getMiniAppArk rejects unsupported types', async () => { const bridge = mockBridge(); await expect( - new MiscApi(bridge as any).getMiniAppArk( 'youtube', 't', 'd', 'p', 'u'), + new MiscApi(bridge as any).getMiniAppArk('youtube', 't', 'd', 'p', 'u'), ).rejects.toThrow(/unsupported type/); }); it('getMiniAppArk routes to LightAppSvc with the encoded body', async () => { - // sendRawPacket is what the action calls; we need a deterministic - // successful response with a decodable body. Easiest: stub the - // raw packet with the encoded response we expect to come back. const bridge = mockBridge({ sendRawPacket: vi.fn(async () => ({ success: true, @@ -73,9 +58,7 @@ describe('apis/misc', () => { responseData: null, })) as any, }); - // With null responseData, the action should throw on decode — that - // still proves the right serviceCmd was used. - await expect(new MiscApi(bridge as any).getMiniAppArk( 'bili', 't', 'd', 'p', 'u')).rejects.toThrow(); + await expect(new MiscApi(bridge as any).getMiniAppArk('bili', 't', 'd', 'p', 'u')).rejects.toThrow(); expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); expect(bridge.sendRawPacket.mock.calls[0]![0]) .toBe('LightAppSvc.mini_app_share.AdaptShareInfo'); @@ -83,19 +66,22 @@ describe('apis/misc', () => { it('clickInlineKeyboardButton returns shaped result', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( protobuf_encode>({ body: { result: 1, errMsg: 'ok', promptText: 'hi' } as any, }), - ); - const out = await new MiscApi(bridge as any).clickInlineKeyboardButton( 1, 2, 'btn', 'data', 100); + )); + const out = await new MiscApi(bridge as any).clickInlineKeyboardButton(1, 2, 'btn', 'data', 100); expect(out).toMatchObject({ result: 1, errMsg: 'ok', promptText: 'hi', status: 0 }); }); - it('sendGroupSign dispatches to 0xEB7_1', async () => { + it('sendGroupSign dispatches to 0xEB7_1 (uppercase preserved)', async () => { const bridge = mockBridge(); - await new MiscApi(bridge as any).sendGroupSign( 12345); - const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; + await new MiscApi(bridge as any).sendGroupSign(12345); + const [cmd] = bridge.sendRawPacket.mock.calls[0]!; + // **Important**: this cmd keeps the historic UPPERCASE EB7 wire + // name. Default scheme would emit lowercase; the namespace + // overrides `wireName` to preserve byte-equality with NTQQ wire. 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 2d0a9c64..f33901b1 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -14,9 +14,9 @@ import type { // 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('@snowluma/bridge/bridge-oidb', async () => { - const actual = await vi.importActual( - '@snowluma/bridge/bridge-oidb', +vi.mock('@snowluma/protocol/bridge-oidb', async () => { + const actual = await vi.importActual( + '@snowluma/protocol/bridge-oidb', ); return { ...actual, @@ -25,19 +25,19 @@ vi.mock('@snowluma/bridge/bridge-oidb', async () => { }; }); -vi.mock('@snowluma/bridge/highway', () => ({ +vi.mock('@snowluma/protocol/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({})), uploadHighwayHttp: vi.fn(async () => undefined), })); -vi.mock('@snowluma/bridge/highway/utils', () => ({ +vi.mock('@snowluma/protocol/highway/utils', () => ({ loadBinarySource: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]), fileName: 'avatar.bin' })), computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })), computeMd5: vi.fn(() => new Uint8Array(16)), })); -import * as oidb from '@snowluma/bridge/bridge-oidb'; -import * as highwayClient from '@snowluma/bridge/highway'; +import * as oidb from '@snowluma/protocol/bridge-oidb'; +import * as highwayClient from '@snowluma/protocol/highway'; import { ProfileApi } from '../../src/bridge/apis/profile'; import { mockBridge } from './_helpers'; @@ -104,30 +104,28 @@ describe('apis/profile', () => { it('setProfile is a no-op when both arguments are undefined', async () => { const bridge = mockBridge(); await new ProfileApi(bridge as any).setProfile(); - expect(oidb.runOidb).not.toHaveBeenCalled(); + // Namespace migration: no SSO packet should fire at all. + expect(bridge.sendRawPacket).not.toHaveBeenCalled(); }); it('setProfile only sends non-undefined fields', async () => { const bridge = mockBridge(); await new ProfileApi(bridge as any).setProfile('New Nick'); - expect(oidb.runOidb).toHaveBeenCalledOnce(); - const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect((body as any).stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]); + expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); + expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2'); }); - it('setSelfLongNick wraps the long nick in profile tag 102', async () => { + it('setSelfLongNick targets 0x112a_2 wire cmd', async () => { const bridge = mockBridge(); await new ProfileApi(bridge as any).setSelfLongNick( 'hello world'); - const body = vi.mocked(oidb.makeOidbEnvelope).mock.calls[0]![2]; - expect((body as any).profile).toEqual({ tag: 102, value: 'hello world' }); + expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2'); }); it('setInputStatus resolves UID first and sends 0xcd4_1', async () => { const bridge = mockBridge(); await new ProfileApi(bridge as any).setInputStatus( 10001, 1); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); - const [, cmd] = vi.mocked(oidb.runOidb).mock.calls[0]!; - expect(cmd).toBe('OidbSvcTrpcTcp.0xcd4_1'); + expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xcd4_1'); }); it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => { @@ -161,7 +159,7 @@ describe('apis/profile', () => { it('setGroupAvatar rejects an empty file before hitting highway', async () => { const bridge = mockBridge(); - const { loadBinarySource } = await import('@snowluma/bridge/highway/utils'); + const { loadBinarySource } = await import('@snowluma/protocol/highway/utils'); vi.mocked(loadBinarySource).mockResolvedValueOnce({ bytes: new Uint8Array(0), fileName: 'empty.png', } as any); @@ -171,8 +169,9 @@ describe('apis/profile', () => { it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ body: { userLikeInfos: [{ uid: 'u', @@ -181,8 +180,8 @@ describe('apis/profile', () => { voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n }, }], } as any, - }), - ); + })), + }); const out = await new ProfileApi(bridge as any).getLike(); expect(out.favoriteInfo.total_count).toBe(5); expect(out.voteInfo.total_count).toBe(7); @@ -190,19 +189,21 @@ describe('apis/profile', () => { it('getProfileLike throws on empty result', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ body: { userLikeInfos: [] } as any }), - ); + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ body: { userLikeInfos: [] } as any })), + }); await expect(new ProfileApi(bridge as any).getLike()).rejects.toThrow(/empty/); }); it('getUnidirectionalFriendList parses the embedded JSON body', async () => { const bridge = mockBridge(); - vi.mocked(oidb.runOidb).mockResolvedValueOnce( - protobuf_encode>({ + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protobuf_encode>({ body: { jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }) } as any, - }), - ); + })), + }); const out = await new ProfileApi(bridge as any).getUnidirectionalFriendList(); expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]); }); diff --git a/packages/core/tests/bridge-event-bus.test.ts b/packages/core/tests/bridge-event-bus.test.ts index 4a441ea7..39c64bdd 100644 --- a/packages/core/tests/bridge-event-bus.test.ts +++ b/packages/core/tests/bridge-event-bus.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; -import { BridgeEventBus } from '@snowluma/bridge/event-bus'; -import type { FriendMessage, GroupMessage } from '@snowluma/bridge/events'; +import { BridgeEventBus } from '@snowluma/protocol/event-bus'; +import type { FriendMessage, GroupMessage } from '@snowluma/protocol/events'; function makeFriendMessage(): FriendMessage { return { diff --git a/packages/core/tests/bridge-member-identity.test.ts b/packages/core/tests/bridge-member-identity.test.ts index 720bb99c..fbe3f25e 100644 --- a/packages/core/tests/bridge-member-identity.test.ts +++ b/packages/core/tests/bridge-member-identity.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; import { Bridge } from '../src/bridge/bridge'; -import { IdentityService } from '@snowluma/bridge/identity-service'; -import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/bridge/qq-info'; -import type { GroupMemberJoin, QQEventVariant } from '@snowluma/bridge/events'; +import { IdentityService } from '@snowluma/protocol/identity-service'; +import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; +import type { GroupMemberJoin, QQEventVariant } from '@snowluma/protocol/events'; import type { PacketInfo } from '@snowluma/common/protocol-types'; const SELF_UIN = '10001'; diff --git a/packages/core/tests/bridge-private-routing.test.ts b/packages/core/tests/bridge-private-routing.test.ts index 6c2c61af..d2b1d5fd 100644 --- a/packages/core/tests/bridge-private-routing.test.ts +++ b/packages/core/tests/bridge-private-routing.test.ts @@ -4,14 +4,14 @@ import type { SendPacketResult } from '@snowluma/common/packet-sender'; import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action'; import type { FileExtra } from '@snowluma/proto-defs/message'; -vi.mock('@snowluma/bridge/element-builder', () => ({ +vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]), })); describe('Bridge private media routing', () => { it('includes resolved uid in the final c2c send request for media messages', async () => { const { Bridge } = await import('../src/bridge/bridge'); - const { IdentityService } = await import('@snowluma/bridge/identity-service'); + const { IdentityService } = await import('@snowluma/protocol/identity-service'); class TestBridge extends Bridge { capturedBody: Uint8Array | null = null; @@ -60,7 +60,7 @@ describe('Bridge private media routing', () => { // implementation wrote c2c routing + richText.notOnlineFile + // c2cCmd=11 — the QQ-NT server rejected every c2c file send. const { Bridge } = await import('../src/bridge/bridge'); - const { IdentityService } = await import('@snowluma/bridge/identity-service'); + const { IdentityService } = await import('@snowluma/protocol/identity-service'); class TestBridge extends Bridge { capturedBody: Uint8Array | null = null; diff --git a/packages/core/tests/element-builder.test.ts b/packages/core/tests/element-builder.test.ts index 2e80b797..7909d614 100644 --- a/packages/core/tests/element-builder.test.ts +++ b/packages/core/tests/element-builder.test.ts @@ -15,18 +15,19 @@ // recognise and got rejected with result=79. import { describe, expect, it, vi } from 'vitest'; +import { inflateSync } from 'zlib'; -vi.mock('@snowluma/bridge/highway/image-upload', () => ({ +vi.mock('@snowluma/protocol/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn(async () => new Uint8Array([7, 8, 9])), })); -vi.mock('@snowluma/bridge/highway/ptt-upload', () => ({ +vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPttMsgInfo: vi.fn(async () => new Uint8Array([4, 5, 6])), })); -vi.mock('@snowluma/bridge/highway/video-upload', () => ({ +vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn(async () => new Uint8Array([1, 2, 3])), })); -import { buildSendElems } from '@snowluma/bridge/element-builder'; +import { buildSendElems } from '@snowluma/protocol/element-builder'; const fakeBridge = {} as any; @@ -118,3 +119,90 @@ describe('element-builder / file element is no longer carried in elems[]', () => expect(result).toEqual([]); }); }); + +describe('element-builder / forward preview (com.tencent.multimsg LightApp)', () => { + // The forward preview is the bubble the recipient renders in chat + // before tapping to expand. It MUST be the modern LightApp / + // `com.tencent.multimsg` JSON (not the older `richMsg serviceID=35` + // XML) because nested forwards rely on `meta.detail.uniseq` to link + // each inner preview to the matching `actionCommand` piggyback on + // the outer's LongMsgResult — without uniseq the QQ-NT client has + // no way to walk the tree and has to re-fetch each inner resId. + function decodeLightApp(elem: any): unknown { + const data: Uint8Array = elem.lightApp.data; + expect(data[0]).toBe(0x01); // deflate prefix + const inflated = inflateSync(Buffer.from(data.subarray(1))).toString('utf8'); + return JSON.parse(inflated); + } + + it('emits a lightApp.data blob with prefix=0x01 (deflated JSON, not XML/serviceID=35)', async () => { + const [elem] = await buildSendElems( + [{ type: 'forward', resId: 'res-XYZ' } as any], + { bridge: fakeBridge, groupId: 12345 }, + ); + expect(elem.lightApp).toBeDefined(); + expect((elem as any).richMsg).toBeUndefined(); + expect(elem.lightApp!.data![0]).toBe(0x01); + }); + + it('places resid + uniseq inside meta.detail (and uniseq matches extra.filename)', async () => { + const [elem] = await buildSendElems( + [{ type: 'forward', resId: 'res-XYZ', forwardUuid: 'fixed-uuid-1234' } as any], + { bridge: fakeBridge, groupId: 12345 }, + ); + const json = decodeLightApp(elem) as any; + expect(json.app).toBe('com.tencent.multimsg'); + expect(json.meta.detail.resid).toBe('res-XYZ'); + expect(json.meta.detail.uniseq).toBe('fixed-uuid-1234'); + // `extra` is a JSON string holding {filename, tsum}; filename must + // round-trip the same uniseq so the QQ-NT client links them. + const extra = JSON.parse(json.extra); + expect(extra.filename).toBe('fixed-uuid-1234'); + }); + + it('autogenerates a uniseq when the element omits forwardUuid (flat forward — cosmetic)', async () => { + const [elem] = await buildSendElems( + [{ type: 'forward', resId: 'res-flat' } as any], + { bridge: fakeBridge, groupId: 12345 }, + ); + const json = decodeLightApp(elem) as any; + expect(json.meta.detail.resid).toBe('res-flat'); + // Auto-generated UUID — non-empty, non-trivial. + expect(json.meta.detail.uniseq).toMatch(/^[0-9a-f-]{36}$/i); + const extra = JSON.parse(json.extra); + expect(extra.filename).toBe(json.meta.detail.uniseq); + }); + + it('threads forwardSource / forwardSummary / forwardPrompt / forwardNews / forwardTSum verbatim', async () => { + const [elem] = await buildSendElems( + [{ + type: 'forward', resId: 'r1', forwardUuid: 'u1', + forwardSource: 'alice和bob的聊天记录', + forwardSummary: '查看3条转发消息', + forwardPrompt: '[聊天记录]', + forwardNews: [{ text: 'alice: hi' }, { text: 'bob: hey' }], + forwardTSum: 3, + } as any], + { bridge: fakeBridge, groupId: 12345 }, + ); + const json = decodeLightApp(elem) as any; + expect(json.meta.detail.source).toBe('alice和bob的聊天记录'); + expect(json.meta.detail.summary).toBe('查看3条转发消息'); + expect(json.meta.detail.news).toEqual([{ text: 'alice: hi' }, { text: 'bob: hey' }]); + expect(json.desc).toBe('[聊天记录]'); + expect(json.prompt).toBe('[聊天记录]'); + expect(JSON.parse(json.extra).tsum).toBe(3); + }); + + it('drops the forward element when resId is missing (preview unrenderable, fail open)', async () => { + // The dispatcher's `case 'forward': if (elem.resId) ...` short- + // circuits when resId is empty so a malformed segment from the + // OneBot client doesn't blow up the whole send. Receiver sees + // no forward bubble — same outcome as omitting the segment. + const out = await buildSendElems( + [{ type: 'forward' } as any], + { bridge: fakeBridge, groupId: 12345 }, + ); + expect(out).toEqual([]); + }); +}); diff --git a/packages/core/tests/event-format.test.ts b/packages/core/tests/event-format.test.ts index b41149ad..4e47ee5f 100644 --- a/packages/core/tests/event-format.test.ts +++ b/packages/core/tests/event-format.test.ts @@ -12,8 +12,8 @@ import { formatMessageSegments, formatReply, formatUser, -} from '@snowluma/bridge/format'; -import type { QQEventVariant } from '@snowluma/bridge/events'; +} from '@snowluma/protocol/format'; +import type { QQEventVariant } from '@snowluma/protocol/events'; // ─── Test fakes (just the find* surface event-format uses) ─── diff --git a/packages/core/tests/highway-utils.test.ts b/packages/core/tests/highway-utils.test.ts index 8e79595e..87f5c6c0 100644 --- a/packages/core/tests/highway-utils.test.ts +++ b/packages/core/tests/highway-utils.test.ts @@ -3,7 +3,7 @@ import os from 'os'; import path from 'path'; import { pathToFileURL } from 'url'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { loadBinarySource, resolveLocalFilePath } from '@snowluma/bridge/highway/utils'; +import { loadBinarySource, resolveLocalFilePath } from '@snowluma/protocol/highway/utils'; describe('highway source paths', () => { it('normalizes file URLs with an extra leading slash on POSIX', () => { diff --git a/packages/core/tests/highway/image-upload.test.ts b/packages/core/tests/highway/image-upload.test.ts index a35e8cc9..82bb36fa 100644 --- a/packages/core/tests/highway/image-upload.test.ts +++ b/packages/core/tests/highway/image-upload.test.ts @@ -5,13 +5,13 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -vi.mock('@snowluma/bridge/highway/pipeline', () => ({ +vi.mock('@snowluma/protocol/highway/pipeline', () => ({ runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })), finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0xCA, 0xFE])), hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)), })); -vi.mock('@snowluma/bridge/highway/utils', () => ({ +vi.mock('@snowluma/protocol/highway/utils', () => ({ loadBinarySource: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]), fileName: 'src.jpg' })), computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), @@ -22,9 +22,9 @@ vi.mock('@snowluma/bridge/highway/utils', () => ({ detectImageFormat: vi.fn(() => ({ format: 1000, width: 800, height: 600 })), })); -import * as pipeline from '@snowluma/bridge/highway/pipeline'; -import { uploadImageMsgInfo } from '@snowluma/bridge/highway/image-upload'; -import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from '@snowluma/bridge/highway'; +import * as pipeline from '@snowluma/protocol/highway/pipeline'; +import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload'; +import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from '@snowluma/protocol/highway'; describe('image-upload', () => { beforeEach(() => { @@ -67,16 +67,18 @@ describe('image-upload', () => { expect(fileInfo.original).toBe(1); }); - it('forwards subType into bizType and ${subType}-aware textSummary', async () => { + it('forwards subType=1 (sticker) into bizType + Chinese textSummary `[动画表情]`', async () => { + // QQ chat-list bubble preview text — must match the literal + // strings mobile QQ / Lagrange.Core / NapCat all emit. await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x', subType: 1 } as any); const args = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0]; expect((args.extBizInfo as any).pic.bizType).toBe(1); - expect((args.extBizInfo as any).pic.textSummary).toBe('[sticker]'); + expect((args.extBizInfo as any).pic.textSummary).toBe('[动画表情]'); }); it('fingerprint path (noByteFallback): zero bytes, fastOnly error message ready', async () => { await uploadImageMsgInfo({} as any, true, 12345, { - noByteFallback: true, md5Hex: 'aa', sha1Hex: 'bb', summary: '[image]', + noByteFallback: true, md5Hex: 'aa', sha1Hex: 'bb', summary: '[图片]', } as any); const sub = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads[0]!; expect(sub.bytes.length).toBe(0); @@ -89,10 +91,20 @@ describe('image-upload', () => { } as any)).rejects.toThrow(/requires md5Hex/); }); - it('finalize is invoked with pic defaults for image', async () => { + it('finalize is invoked with pic defaults for image (Chinese `[图片]`)', async () => { await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x', subType: 0 } as any); expect(pipeline.finalizeMediaMsgInfo).toHaveBeenCalledOnce(); const [, defaultPic] = vi.mocked(pipeline.finalizeMediaMsgInfo).mock.calls[0]!; - expect(defaultPic).toEqual({ bizType: 0, textSummary: '[image]' }); + expect(defaultPic).toEqual({ bizType: 0, textSummary: '[图片]' }); + }); + + it('caller-supplied summary wins over the Chinese default', async () => { + // OneBot clients can pass `summary: '[心形图片]'` (or any custom + // text) — that overrides our default and goes through verbatim. + await uploadImageMsgInfo({} as any, true, 12345, { + url: 'http://x', subType: 0, summary: '[custom-bubble]', + } as any); + const [, defaultPic] = vi.mocked(pipeline.finalizeMediaMsgInfo).mock.calls[0]!; + expect(defaultPic).toEqual({ bizType: 0, textSummary: '[custom-bubble]' }); }); }); diff --git a/packages/core/tests/highway/multi-image.test.ts b/packages/core/tests/highway/multi-image.test.ts new file mode 100644 index 00000000..4c075e0f --- /dev/null +++ b/packages/core/tests/highway/multi-image.test.ts @@ -0,0 +1,241 @@ +// Regression test for the "two images in one message" bug user report. +// +// User saw: 1st image fast-uploaded (server already had the bytes), 2nd +// image triggered an actual highway PUT and the highway server returned +// `error_code=921`. +// +// This test walks two `runNtv2Upload` calls back-to-back through the +// real pipeline + buildHighwayExtend code path with the highway TCP/HTTP +// transport stubbed, and verifies: +// +// - the two calls don't share state (each has its own session, its +// own OIDB request, its own extend bytes), +// - the second call's extend payload is well-formed (uKey + msgInfoBody +// + ipv4s come from the *second* call's response, not the first), +// - the highway PUT receives the second image's bytes + md5 + sha1 +// verbatim (no aliasing / truncation across calls). +// +// If this test ever starts failing, it's a real bug in the pipeline +// (state sharing, async race, or wrong-buffer aliasing). If it +// continues to pass, the user's 921 is almost certainly server-side +// (rate limit, malformed image rejection, expired session) rather than +// a client-emit issue. + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; + +vi.mock('@snowluma/protocol/highway', async () => { + const real = await vi.importActual('@snowluma/protocol/highway'); + return { + ...real, + // Only the TCP/HTTP transport is mocked — we keep real + // `buildHighwayExtend` so we can inspect its output bytes. + fetchHighwaySession: vi.fn(async () => ({ + sigSession: new Uint8Array([0xAA]), + sessionKey: new Uint8Array([0xBB]), + host: 'highway.example', + port: 80, + })), + uploadHighwayHttp: vi.fn(async () => undefined), + }; +}); + +import * as highway from '@snowluma/protocol/highway'; +import { runNtv2Upload, type MediaSubFileUpload } from '@snowluma/protocol/highway/pipeline'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + NTV2UploadRichMediaReq, + NTV2UploadRichMediaResp, + NTV2RichMediaHighwayExt, +} from '@snowluma/proto-defs/highway'; + +function encodeOidbResponse(body: any): Buffer { + return Buffer.from(protobuf_encode>({ + command: 0x11C4, subCommand: 100, errorCode: 0, + body: body as Record, errorMsg: '', reserved: 1, + })); +} + +function makeBridge(responses: Buffer[]) { + const sendRawPacket = vi.fn(); + for (const r of responses) { + sendRawPacket.mockResolvedValueOnce({ + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: r, + }); + } + return { sendRawPacket, identity: { uin: '10001' } } as any; +} + +const baseParams = (bridge: any) => ({ + bridge, isGroup: true, targetIdOrUid: 894750076, + oidbCmd: 0x11C4, serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100', + requestId: 1, businessType: 1, + compatQmsgSceneType: 2, + extBizInfo: { pic: { bizType: 0, textSummary: '[image]' } }, +}); + +describe('runNtv2Upload — two images in one message (sequential)', () => { + beforeEach(() => { + vi.mocked(highway.fetchHighwaySession).mockClear(); + vi.mocked(highway.uploadHighwayHttp).mockClear(); + }); + + it('does not leak the first image\'s upload metadata into the second\'s extend', async () => { + // Image 1 server response: NO uKey (fast-upload hit). The pipeline + // must skip the highway PUT entirely for this call. + // Image 2 server response: uKey + ipv4s + msgInfoBody set → real PUT. + const image1Bytes = Buffer.from(new Uint8Array(238963)); + const image1Md5 = new Uint8Array(16).fill(0xF4); + const image2Bytes = Buffer.from(new Uint8Array(58)); + const image2Md5 = new Uint8Array(16).fill(0xDD); + const image2Sha1 = new Uint8Array(20).fill(0x11); + + const bridge = makeBridge([ + // First OIDB upload response: fast-path hit (no uKey). + encodeOidbResponse({ + upload: { + msgInfo: { + msgInfoBody: [{ index: { fileUuid: 'uuid-1' } }], + extBizInfo: {}, + }, + }, + }), + // Second OIDB upload response: needs highway PUT. + encodeOidbResponse({ + upload: { + uKey: 'ukey-image-2', + ipv4s: [{ outIp: 0x04030201, outPort: 8080 }], + msgInfo: { + msgInfoBody: [{ index: { fileUuid: 'uuid-2', info: { fileHash: 'dd', fileSha1: '11' } } }], + extBizInfo: {}, + }, + }, + }), + ]); + + const uploads1: MediaSubFileUpload[] = [{ + source: 'top', cmdId: 1004, + bytes: image1Bytes, md5: image1Md5, sha1: new Uint8Array(20).fill(0xAB), + fastOnlyError: 'image fast-upload not available', + }]; + const uploads2: MediaSubFileUpload[] = [{ + source: 'top', cmdId: 1004, + bytes: image2Bytes, md5: image2Md5, sha1: image2Sha1, + fastOnlyError: 'image fast-upload not available', + }]; + + // Image 1 — fast path; must NOT touch the highway transport. + await runNtv2Upload({ + ...baseParams(bridge), + uploadInfo: [{ + fileInfo: { fileName: 'a.jpg', fileSize: 238963 }, + subFileType: 0, + }], + uploads: uploads1, + label: 'image', + }); + expect(highway.fetchHighwaySession).not.toHaveBeenCalled(); + expect(highway.uploadHighwayHttp).not.toHaveBeenCalled(); + + // Image 2 — must PUT through highway exactly once. + await runNtv2Upload({ + ...baseParams(bridge), + uploadInfo: [{ + fileInfo: { fileName: 'b.jpg', fileSize: 58 }, + subFileType: 0, + }], + uploads: uploads2, + label: 'image', + }); + expect(highway.fetchHighwaySession).toHaveBeenCalledOnce(); + expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce(); + + // The PUT receives image-2's bytes, image-2's md5, and the + // image-2-derived extend (NOT image-1's data). + const [, , cmdId, putBytes, putMd5, putExtend] = vi.mocked(highway.uploadHighwayHttp).mock.calls[0]!; + expect(cmdId).toBe(1004); + expect(putBytes).toBe(image2Bytes); + expect(putMd5).toBe(image2Md5); + + // Decode the extend bytes; uKey + fileUuid must come from image-2's + // response, ipv4s must come from image-2's response. + const extend = protobuf_decode(putExtend); + expect(extend.uKey).toBe('ukey-image-2'); + expect(extend.fileUuid).toBe('uuid-2'); + expect(extend.msgInfoBody?.[0]?.index?.fileUuid).toBe('uuid-2'); + expect(extend.network?.ipv4s?.length).toBeGreaterThan(0); + }); + + it('image 2 fetches its own fresh session (no leftover from a prior call)', async () => { + // Both images hit the highway PUT path. The pipeline must call + // fetchHighwaySession once PER runNtv2Upload (not share session + // across calls), matching NapCat's per-context lifetime semantics + // would actually be a future optimisation, but for now correctness + // = "session is non-null when PUT runs". + const ok = encodeOidbResponse({ + upload: { + uKey: 'ukey', ipv4s: [{ outIp: 1, outPort: 80 }], + msgInfo: { msgInfoBody: [{ index: { fileUuid: 'u' } }], extBizInfo: {} }, + }, + }); + const bridge = makeBridge([ok, ok]); + + const uploads: MediaSubFileUpload[] = [{ + source: 'top', cmdId: 1004, + bytes: Buffer.from([1, 2, 3]), + md5: new Uint8Array(16), sha1: new Uint8Array(20), + fastOnlyError: 'image fast-upload not available', + }]; + + await runNtv2Upload({ + ...baseParams(bridge), + uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }], + uploads, label: 'image', + }); + await runNtv2Upload({ + ...baseParams(bridge), + uploadInfo: [{ fileInfo: { fileName: 'b.jpg' }, subFileType: 0 }], + uploads, label: 'image', + }); + + expect(highway.fetchHighwaySession).toHaveBeenCalledTimes(2); + expect(highway.uploadHighwayHttp).toHaveBeenCalledTimes(2); + // The session object passed to the PUT must be non-null both times. + for (const call of vi.mocked(highway.uploadHighwayHttp).mock.calls) { + const session = call[1]; + expect(session).toBeDefined(); + expect((session as any).sigSession).toBeDefined(); + } + }); + + it('image 2\'s OIDB request body carries image-2\'s fileInfo (not image-1\'s)', async () => { + // Catches a hypothetical bug where someone mutates a shared body + // object across calls. Today the pipeline always builds a fresh + // body, but the regression is cheap to guard. + const ok = encodeOidbResponse({ + upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } }, + }); + const bridge = makeBridge([ok, ok]); + + await runNtv2Upload({ + ...baseParams(bridge), + uploadInfo: [{ fileInfo: { fileName: 'first.jpg', fileSize: 100 }, subFileType: 0 }], + uploads: [], label: 'image', + }); + await runNtv2Upload({ + ...baseParams(bridge), + uploadInfo: [{ fileInfo: { fileName: 'second.jpg', fileSize: 200 }, subFileType: 0 }], + uploads: [], label: 'image', + }); + + expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2); + const body1 = protobuf_decode>(bridge.sendRawPacket.mock.calls[0]![1]); + const body2 = protobuf_decode>(bridge.sendRawPacket.mock.calls[1]![1]); + expect(body1.body?.upload?.uploadInfo?.[0]?.fileInfo?.fileName).toBe('first.jpg'); + expect(body2.body?.upload?.uploadInfo?.[0]?.fileInfo?.fileName).toBe('second.jpg'); + + // And the clientRandomId is different per call (sanity). + expect(body1.body?.upload?.clientRandomId).not.toBe(body2.body?.upload?.clientRandomId); + }); +}); diff --git a/packages/core/tests/highway/pipeline.test.ts b/packages/core/tests/highway/pipeline.test.ts index 8a08cf79..9a951515 100644 --- a/packages/core/tests/highway/pipeline.test.ts +++ b/packages/core/tests/highway/pipeline.test.ts @@ -5,10 +5,10 @@ // The OIDB response is built with real protobuf encoding so we exercise // the actual decode path inside the pipeline. -import { describe, it, expect, vi, beforeEach } from 'vitest'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; -vi.mock('@snowluma/bridge/highway', () => ({ +vi.mock('@snowluma/protocol/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })), uploadHighwayHttp: vi.fn(async () => undefined), buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])), @@ -16,16 +16,16 @@ vi.mock('@snowluma/bridge/highway', () => ({ GROUP_IMAGE_CMD_ID: 1004, })); -import * as highway from '@snowluma/bridge/highway'; +import type { EncodableMediaMsgInfo, NTV2UploadRichMediaReq, NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import * as highway from '@snowluma/protocol/highway'; import { finalizeMediaMsgInfo, hexToBytes, makeClientRandomId, runNtv2Upload, type MediaSubFileUpload, -} from '@snowluma/bridge/highway/pipeline'; -import type { OidbBase } from '@snowluma/proto-defs/oidb'; -import type { EncodableMediaMsgInfo, NTV2UploadRichMediaReq, NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway'; +} from '@snowluma/protocol/highway/pipeline'; interface FakeUploadResponse { upload?: { @@ -151,7 +151,7 @@ describe('pipeline — runNtv2Upload', () => { }); const upload = await runNtv2Upload(baseParams({ bridge })); expect(upload.uKey).toBe('fake-ukey'); - expect(upload.msgInfo.msgInfoBody).toHaveLength(1); + expect(upload.msgInfo?.msgInfoBody).toHaveLength(1); }); it('throws on transport failure', async () => { @@ -315,7 +315,7 @@ describe('pipeline — finalizeMediaMsgInfo', () => { it('encodes msgInfoBody + extBizInfo from the server response', () => { const out = finalizeMediaMsgInfo({ msgInfo: { - msgInfoBody: [{ index: { fileType: 1 }, fileExist: true }], + msgInfoBody: [{ index: { subType: 1 }, fileExist: true }], extBizInfo: { busiType: 1 }, }, }); diff --git a/packages/core/tests/highway/ptt-upload.test.ts b/packages/core/tests/highway/ptt-upload.test.ts index 72efe321..8bc2f6c4 100644 --- a/packages/core/tests/highway/ptt-upload.test.ts +++ b/packages/core/tests/highway/ptt-upload.test.ts @@ -7,14 +7,14 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -vi.mock('@snowluma/bridge/highway/pipeline', () => ({ +vi.mock('@snowluma/protocol/highway/pipeline', () => ({ runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })), finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0xAA, 0xBB])), hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)), })); -import * as pipeline from '@snowluma/bridge/highway/pipeline'; -import { uploadPttMsgInfo, GROUP_PTT_CMD_ID, PRIVATE_PTT_CMD_ID } from '@snowluma/bridge/highway/ptt-upload'; +import * as pipeline from '@snowluma/protocol/highway/pipeline'; +import { uploadPttMsgInfo, GROUP_PTT_CMD_ID, PRIVATE_PTT_CMD_ID } from '@snowluma/protocol/highway/ptt-upload'; const FINGERPRINT = { noByteFallback: true, diff --git a/packages/core/tests/highway/video-upload.test.ts b/packages/core/tests/highway/video-upload.test.ts index a7910cc2..4e64fb59 100644 --- a/packages/core/tests/highway/video-upload.test.ts +++ b/packages/core/tests/highway/video-upload.test.ts @@ -11,20 +11,20 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -vi.mock('@snowluma/bridge/highway/pipeline', () => ({ +vi.mock('@snowluma/protocol/highway/pipeline', () => ({ runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })), finalizeMediaMsgInfo: vi.fn(() => new Uint8Array([0x12, 0x34])), hexToBytes: vi.fn((hex: string) => new Uint8Array(hex.length / 2)), })); -import * as pipeline from '@snowluma/bridge/highway/pipeline'; +import * as pipeline from '@snowluma/protocol/highway/pipeline'; import { uploadVideoMsgInfo, GROUP_VIDEO_CMD_ID, GROUP_VIDEO_THUMB_CMD_ID, PRIVATE_VIDEO_CMD_ID, PRIVATE_VIDEO_THUMB_CMD_ID, -} from '@snowluma/bridge/highway/video-upload'; +} from '@snowluma/protocol/highway/video-upload'; const FINGERPRINT = { noByteFallback: true, diff --git a/packages/core/tests/identity-service.test.ts b/packages/core/tests/identity-service.test.ts index 327e87d0..a1ee2ac9 100644 --- a/packages/core/tests/identity-service.test.ts +++ b/packages/core/tests/identity-service.test.ts @@ -1,8 +1,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import fs from 'fs'; import path from 'path'; -import { IdentityService } from '@snowluma/bridge/identity-service'; -import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/bridge/qq-info'; +import { IdentityService } from '@snowluma/protocol/identity-service'; +import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info'; const SELF_UIN = '10001'; const GROUP_ID = 123456789; @@ -188,7 +188,7 @@ describe('IdentityService', () => { describe('IdentityService.resolveUid', () => { function makeProfile(uin: number, uid: string): UserProfileInfo { - return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '' }; + return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0 }; } it('returns the cached uid without invoking the fetcher', async () => { diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index ef96567a..8373a16c 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; import { protobuf_encode } from '@snowluma/proton'; -import { parseMsgPush, MSG_PUSH_CMD } from '@snowluma/bridge/msg-push'; -import { IdentityService } from '@snowluma/bridge/identity-service'; -import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/bridge/qq-info'; +import { parseMsgPush, MSG_PUSH_CMD } from '@snowluma/protocol/msg-push'; +import { IdentityService } from '@snowluma/protocol/identity-service'; +import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; // Proton's call-site analyzer keys off the literal type identifier // printed in `protobuf_encode` — it walks imports by *original* // name (not alias). If both `import { X } from 'proto/notify'` and @@ -18,7 +18,7 @@ import type { import type { PushMsg } from '@snowluma/proto-defs/message'; import type { GroupMemberJoin, FriendAddEvent, QQEventVariant, -} from '@snowluma/bridge/events'; +} from '@snowluma/protocol/events'; // Local alias for the event-side recall type — derived via Extract so // we avoid an `import { FriendRecall as X }` that collides with the diff --git a/packages/core/tests/observability-logs.test.ts b/packages/core/tests/observability-logs.test.ts index 12798493..7310b9d0 100644 --- a/packages/core/tests/observability-logs.test.ts +++ b/packages/core/tests/observability-logs.test.ts @@ -13,7 +13,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { protobuf_encode } from '@snowluma/proton'; import { subscribeLogs, type LogEntry } from '@snowluma/common/logger'; -vi.mock('@snowluma/bridge/highway', () => ({ +vi.mock('@snowluma/protocol/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })), uploadHighwayHttp: vi.fn(async () => undefined), buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])), @@ -24,12 +24,12 @@ vi.mock('@snowluma/bridge/highway', () => ({ import { runNtv2Upload, type MediaSubFileUpload, -} from '@snowluma/bridge/highway/pipeline'; +} from '@snowluma/protocol/highway/pipeline'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway'; -import { MsgPushRegistry } from '@snowluma/bridge/msg-push/registry'; -import type { MsgPushContext } from '@snowluma/bridge/msg-push/context'; -import { decodeEvent0x2DC } from '@snowluma/bridge/msg-push/decoders/event-0x2dc'; +import { MsgPushRegistry } from '@snowluma/protocol/msg-push/registry'; +import type { MsgPushContext } from '@snowluma/protocol/msg-push/context'; +import { decodeEvent0x2DC } from '@snowluma/protocol/msg-push/decoders/event-0x2dc'; function encodeOidbResponse(body: unknown): Buffer { return Buffer.from(protobuf_encode>({ diff --git a/packages/onebot/package.json b/packages/onebot/package.json index 64a8c113..13120b2e 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/onebot", - "version": "1.9.1", + "version": "1.9.2", "private": true, "type": "module", "description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis..method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/'` collapses to `import { … } from '@snowluma/onebot/'`.", @@ -86,11 +86,11 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "@snowluma/bridge": "workspace:*", "@snowluma/common": "workspace:*", "@snowluma/core": "workspace:*", "@snowluma/proto-defs": "workspace:*", "@snowluma/proton": "workspace:*", + "@snowluma/protocol": "workspace:*", "@snowluma/sqlite": "workspace:*", "@snowluma/websocket": "workspace:*" }, diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index aae39bca..cb39ba49 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1,7 +1,7 @@ import type { ApiActionContext, ApiHandler } from '../api-handler'; import { asBoolean, asMessage, asNumber, asString } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; -import { RETCODE, failedResponse, okResponse } from '../types'; +import { JsonObject, RETCODE, failedResponse, okResponse } from '../types'; const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB const DOWNLOAD_FILE_TIMEOUT_MS = 60_000; @@ -31,10 +31,7 @@ async function fetchDownloadFile( } return bytes; } - - // Stream so a server that omits / understates Content-Length can't make - // us buffer past maxBytes — abort the read as soon as the running total - // crosses the cap. + // 流式读取,防止服务器 Content-Length 导致内存占用过大 — 一旦累计字节数超过上限就中止读取。 const chunks: Uint8Array[] = []; let total = 0; try { @@ -55,11 +52,7 @@ async function fetchDownloadFile( return Buffer.concat(chunks, total); } -/** - * Pull NapCat-compatible forward preview overrides off a send_*_forward_msg - * payload. All four fields are optional — when omitted, the module layer - * derives sensible defaults from the actual node list. - */ +// 从 send_*_forward_msg 的参数里提取 NapCat 兼容的转发预览元信息。四个字段都是可选的——如果没有提供,模块层会根据实际消息节点列表推断出合理的默认值。 function readForwardPreviewMeta(params: Record): ForwardPreviewMeta | undefined { const source = asString(params.source) || undefined; const summary = asString(params.summary) || undefined; @@ -82,8 +75,7 @@ function readForwardPreviewMeta(params: Record): ForwardPreview } export function register(h: ApiHandler, ctx: ApiActionContext): void { - // --- Likes & Pokes --- - + // 赞 h.registerAction('send_like', async (params) => { const userId = asNumber(params.user_id); const times = asNumber(params.times) || 1; @@ -91,7 +83,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { await ctx.bridge.apis.interaction.sendLike(userId, times); return okResponse(); }); - + // 拍一拍 h.registerAction('friend_poke', async (params) => { const userId = asNumber(params.user_id); const targetId = asNumber(params.target_id) || undefined; @@ -120,8 +112,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse(); }); - // --- Essence --- - + // 精华消息 h.registerAction('set_essence_msg', async (params) => { const messageId = asNumber(params.message_id); if (!Number.isInteger(messageId) || messageId === 0) { @@ -148,7 +139,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { const essenceDataAll = await ctx.bridge.apis.web.getEssenceAll(groupId); - const allMsgs = essenceDataAll.flatMap((res: any) => res.data?.msg_list || []); + const allMsgs = essenceDataAll.flatMap((res) => res.data?.msg_list || []); return okResponse(allMsgs); } catch (e) { @@ -156,8 +147,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } }); - // --- Reactions --- - + // 群聊表情回应 h.registerAction('set_group_reaction', async (params) => { const groupId = asNumber(params.group_id); const messageId = asNumber(params.message_id); @@ -181,8 +171,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse(); }); - // --- History --- - + // 消息历史 h.registerAction('get_group_msg_history', async (params) => { const groupId = asNumber(params.group_id); const messageId = asNumber(params.message_id) || 0; @@ -201,6 +190,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse({ messages }); }); + // 标记消息已读 h.registerAction('mark_group_msg_as_read', async (params) => { const messageId = asNumber(params.message_id); const groupId = asNumber(params.group_id); @@ -264,8 +254,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { }); - // --- RKey --- - + // 下载密钥 const handleGetRkey = async () => { if (ctx.getDownloadRKeys) { return okResponse(await ctx.getDownloadRKeys()); @@ -273,11 +262,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); }; h.registerAction('get_rkey', handleGetRkey); - // napcat exposes the same payload under `nc_get_rkey`; mirror the alias - // so clients that follow napcat's docs work out-of-the-box. h.registerAction('nc_get_rkey', handleGetRkey); - // --- OCR stubs --- + // OCR 兜底未实现。 h.registerAction('ocr_image', async () => { return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); @@ -287,8 +274,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); }); - // --- Group notice stubs --- - + // 群公告 h.registerAction('_send_group_notice', async (params) => { const groupId = asNumber(params.group_id); const content = asString(params.content); @@ -348,17 +334,12 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } }); - // --- Forward messages --- - + // 转发消息。 h.registerAction('upload_forward_msg', async (params) => { const messages = asMessage(params.messages ?? params.message); const groupId = asNumber(params.group_id); if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - - // Group and private forwards live in different resId namespaces - // (see bridge/actions/forward.ts: type=3+groupUin vs type=1+selfUid). - // Passing groupId through is what makes the resulting resId usable - // when the caller later sends it into the same group. + // 群聊和私聊转发消息的 resId 是分开的(前者是 type=3+groupUin,后者是 type=1+selfUid), const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); const data: Record = { res_id: result.forwardId, @@ -366,11 +347,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { message_id: 0, }; if (groupId > 0) data.group_id = groupId; - return okResponse(data as any); + return okResponse(data as import('../types').JsonObject); }); - // Kept for backward compat with clients that follow the historical - // gocqhttp/NapCat docs misspelling; same semantics as upload_forward_msg. h.registerAction('upload_foward_msg', async (params) => { const messages = asMessage(params.messages ?? params.message); const groupId = asNumber(params.group_id); @@ -458,7 +437,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse({ messages }); }); - // --- Media --- + // 文件信息 h.registerAction('get_image', async (params) => { const file = asString(params.file) || asString(params.file_id); @@ -476,7 +455,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache'); }); - // --- Credentials --- + // Cookie、CSRF 令牌和账号信息 h.registerAction('get_cookies', async (params) => { const domain = asString(params.domain) || 'qun.qq.com'; @@ -511,7 +490,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, String(e)); } }); - // --- Utility --- + // 重启和清理缓存 h.registerAction('set_restart', async () => { return failedResponse(RETCODE.ACTION_FAILED, 'not supported'); @@ -530,13 +509,10 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse(); }); - // --- NapCat-compatible extended APIs --- - + // 以下接口在方便用户迁移和兼容现有的 OneBot/NapCat 客户端。 h.registerAction('set_friend_remark', async (params) => { const userId = asNumber(params.user_id); if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - // remark must be explicitly provided. Falling back to '' on a missing - // field would silently CLEAR the operator's existing remark. if (params.remark === undefined) { return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)'); } @@ -598,10 +574,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const tempDir = pathMod.resolve('data', 'downloads'); if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); - // Sanitize file name: strip any path components, reject anything that - // resolves outside `tempDir`. Without this guard, `name = "../../config/onebot_x.json"` - // would let an authenticated OneBot client overwrite arbitrary files - // (config / dist / node_modules) under the working directory. + // 清理文件名:移除所有路径部分,并拒绝任何会解析到 tempDir 外部的路径。 + // 如果没有这个保护,name = "../../config/onebot_x.json" 会让已认证的 OneBot 客户端覆盖工作目录下的任意文件。 + // 例如 config、dist、node_modules 等目录中的文件。 const resolveSafePath = (preferredName: string, fallbackBuf: Buffer): string | null => { const raw = preferredName || cryptoMod.createHash('md5').update(fallbackBuf).digest('hex'); const safeName = pathMod.basename(raw); @@ -614,9 +589,8 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { let buf: Buffer; if (base64) { - // Every 4 base64 chars decode to at most 3 bytes. Reject before - // `Buffer.from` allocates anything to avoid OOM on a giant payload - // that wouldn't pass the post-decode check anyway. + // 每 4 个 base64 字符最多解码成 3 个字节。 + // 在 Buffer.from 分配内存前先拒绝过大的载荷,避免最终也无法通过解码后检查的大载荷导致内存溢出。 const upperBound = Math.floor((base64.length * 3) / 4); if (upperBound > DOWNLOAD_FILE_MAX_BYTES) { return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); @@ -640,8 +614,8 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const safe = resolveSafePath(name, buf); if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); - // Async write so we don't block the event loop on a GiB-class download - // (the prior `writeFileSync` stalled every other bot action while it ran). + // 使用异步写入,避免 GiB 级下载阻塞事件循环。 + // 之前的 writeFileSync 会在运行期间卡住其他所有机器人动作。 await fs.promises.writeFile(safe, buf); return okResponse({ file: safe }); }); @@ -661,7 +635,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { }); h.registerAction('set_online_status', async (params) => { - // 按 OneBot/NapCat 习惯提取参数,状态码默认为 11 const status = asNumber(params.status); const extStatus = asNumber(params.ext_status) || 0; const batteryStatus = asNumber(params.battery_status) || 100; @@ -680,11 +653,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } }); - // DIY status — same wire packet as set_online_status, only the - // customExt sub-message is populated and status/extStatus are forced - // to the QQ-defined "I have a custom status" values (10 / 2000). - // face_id / face_type accept either number or numeric string (napcat - // parity); wording is the human-readable text shown next to the icon. + // 自定义在线状态:与 set_online_status 使用相同的网络包。 + // 这里只填充 customExt 子消息,并将 status/extStatus 强制设为 QQ 定义的“我有自定义状态”取值(10 / 2000)。 + // face_id 和 face_type 可接受数字或数字字符串,以兼容 NapCat;wording 是图标旁展示的可读文本。 h.registerAction('set_diy_online_status', async (params) => { const faceId = asNumber(params.face_id); const faceType = asNumber(params.face_type) || 1; @@ -698,10 +669,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } }); - // Filtered (机器人/被忽略) group join requests. SnowLuma already - // implements the underlying oidb 0x10c8_2 fetch via fetchGroupRequests; - // these three actions just rename / project the same data for the - // OneBot dialects clients use in the wild. + // 已过滤(机器人/被忽略)的入群请求。 + // SnowLuma 已通过 fetchGroupRequests 实现底层 oidb 0x10c8_2 拉取。 + // 这几个动作只是为实际使用中的 OneBot 方言客户端重命名并投影相同数据。 const fetchFilteredGroupRequests = async () => { try { return await ctx.bridge.apis.contacts.fetchGroupRequests(true); @@ -727,10 +697,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { }))); }); - // napcat name for the subset of ignored notifies that are join requests - // (notify type==7). We map every entry that flowed through filtered - // 0x10c8_2 into napcat's shape — eventType already encodes the request - // category in our pipeline. + // NapCat 对“被忽略通知中属于入群请求的子集”的命名(notify type == 7)。 + // 这里把经过过滤的 0x10c8_2 每一项映射成 NapCat 结构。 + // eventType 已经在当前流水线中编码了请求类别。 h.registerAction('get_group_ignore_add_request', async () => { const reqs = await fetchFilteredGroupRequests(); return okResponse(reqs.map((r) => ({ @@ -746,8 +715,8 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { }))); }); - // get_group_shut_list lives behind an oidb we don't yet wrap; honour - // the napcat contract (empty list) so callers don't blow up. + // get_group_shut_list 依赖尚未封装的 oidb。 + // 这里遵循 NapCat 约定返回空列表,避免调用方出错。 h.registerAction('get_group_shut_list', async () => { return okResponse([]); }); @@ -778,21 +747,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } }); - // todo 我的建议是引入数据库api 纯协议我不知道这种api怎么实现,ntQQ在实现这个方法的时候只进行了数据库查询,完全没碰网络 - h.registerAction('get_recent_contact', async () => { - return okResponse([]); - }); - h.registerAction('get_profile_like', async (params) => { const userId = asNumber(params.user_id); const start = asNumber(params.start) || 0; const count = asNumber(params.count) || 10; - - try { - // getLike treats falsy userId as "self" (it does `isSelf = !userId` - // internally), so passing 0 or undefined is equivalent — matches the - // old `ctx.getProfileLike(userId, start, count)` wrapper exactly. const data = await ctx.bridge.apis.profile.getLike(userId, start, count); return okResponse(data); } catch (e) { @@ -815,10 +774,10 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const emojiId = asString(params.emoji_id) || ''; if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required'); try { - const meta = ctx.getMessageMeta(messageId); - if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message'); - const result = await ctx.bridge.apis.interaction.getEmojiLikes(meta.targetId, meta.sequence, emojiId); - return okResponse({ emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })) }); + const result = await ctx.fetchEmojiLikeUsers(messageId, emojiId, 1000); + return okResponse({ + emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })), + }); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); } @@ -827,21 +786,21 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('fetch_emoji_like', async (params) => { const messageId = asNumber(params.message_id); const emojiId = asString(params.emojiId) || ''; - const emojiType = asNumber(params.emojiType) || 1; const count = asNumber(params.count) || 10; const cookie = asString(params.cookie) || ''; if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emojiId are required'); try { - const meta = ctx.getMessageMeta(messageId); - if (!meta?.isGroup || !meta?.sequence) return failedResponse(RETCODE.BAD_REQUEST, 'message not found or not a group message'); - const result = await ctx.bridge.apis.interaction.getEmojiLikes(meta.targetId, meta.sequence, emojiId, emojiType, count, cookie); + const offset = cookie ? Number.parseInt(cookie, 10) || 0 : 0; + const result = await ctx.fetchEmojiLikeUsers(messageId, emojiId, count, offset); + const nextOffset = offset + result.users.length; + const isLastPage = nextOffset >= result.cachedCount; return okResponse({ result: 0, errMsg: '', emojiLikesList: result.users.map(u => ({ tinyId: String(u.uin), nickName: '', headUrl: '' })), - cookie: result.cookie, - isLastPage: result.isLast, - isFirstPage: !cookie, + cookie: isLastPage ? '' : String(nextOffset), + isLastPage, + isFirstPage: offset === 0, }); } catch (e) { return failedResponse(RETCODE.ACTION_FAILED, String(e)); @@ -855,9 +814,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse([]); }); - // --- Additional NapCat-compatible stubs --- - - ///napcat 似乎也用不了??,暂时不管了 + // NapCat 似乎也用不了,暂时不处理。 h.registerAction('get_online_clients', async () => { return okResponse({ clients: [] }); }); @@ -880,8 +837,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (!groupId) { return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id'); } - - try { const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(groupId); return okResponse(data); @@ -906,8 +861,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { if (typeof longNick !== 'string') { return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick'); } - - try { await ctx.bridge.apis.profile.setSelfLongNick(longNick); return okResponse({}); @@ -950,7 +903,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'invalid event_type'); } - try { await ctx.bridge.apis.profile.setInputStatus(userId, eventType); return okResponse({}); @@ -1033,7 +985,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } }); - const handleGroupSign = async (params: any) => { + const handleGroupSign = async (params: import('../types').JsonObject) => { const groupId = asNumber(params.group_id); if (!groupId) { @@ -1084,12 +1036,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); }); - // --- Raw packet escape hatch (napcat parity) --- - // - // napcat exposes both names; the dot-prefix variant is the original - // gocqhttp-era backdoor, the no-prefix one is the modern API. They do - // the same thing in SnowLuma: encode hex → Bridge.sendRawPacket → hex. - const handleSendPacket = async (params: import('../types').JsonObject) => { + const handleSendPacket = async (params: JsonObject) => { const cmd = asString(params.cmd); const dataHex = asString(params.data); const rsp = asBoolean(params.rsp, true); @@ -1113,24 +1060,19 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('send_packet', handleSendPacket); h.registerAction('.send_packet', handleSendPacket); - // --- Bot lifecycle (napcat parity) --- - + // 机器人生命周期(兼容 NapCat)。 h.registerAction('bot_exit', async () => { - // Defer so the OK response actually flushes before the process dies. setTimeout(() => process.exit(0), 50); return okResponse(); }); - // SnowLuma has no separate packet-backend process (napcat's packet - // service runs out-of-process and can fail independently). Always - // report healthy. h.registerAction('nc_get_packet_status', async () => { return okResponse(null); }); - // napcat exposes `delete_group_folder`; SnowLuma's existing - // `delete_group_file_folder` is the same operation. Alias so clients - // following napcat docs work without rewriting payloads. + // NapCat 暴露 delete_group_folder。 + // SnowLuma 现有的 delete_group_file_folder 是相同操作。 + // 添加别名以便遵循 NapCat 文档的客户端无需重写载荷。 h.registerAction('delete_group_folder', async (params) => { const groupId = asNumber(params.group_id); const folderId = asString(params.folder_id); @@ -1141,12 +1083,10 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse(); }); - // --- Group todo (oidb 0xF90) --- - // - // The three subcommands share an identical payload (group + msgSeq); - // we extract once and dispatch by action name. msgSeq comes from the - // message metadata cache (set/complete/cancel always target a real - // message the bot has seen). + // 群待办(oidb 0xF90)。 + // 三个子命令共享相同载荷(群号 + msgSeq)。 + // 这里统一提取一次,并按动作名称分发。 + // msgSeq 来自消息元数据缓存;设置、完成、取消总是指向机器人见过的真实消息。 type GroupTodoOp = (groupId: number, msgSeq: bigint | number | string) => Promise; const handleGroupTodo = (op: GroupTodoOp) => async (params: import('../types').JsonObject) => { const groupId = asNumber(params.group_id); @@ -1169,7 +1109,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('complete_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.completeGroupTodo(g, BigInt(s)))); h.registerAction('cancel_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.cancelGroupTodo(g, BigInt(s)))); - // --- User online/ext status (napcat: nc_get_user_status) --- + // 用户在线/扩展状态(NapCat:nc_get_user_status)。 h.registerAction('nc_get_user_status', async (params) => { const userId = asNumber(params.user_id); @@ -1179,7 +1119,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse({ ...status }); }); - // --- AI voice (oidb 0x929D / 0x929B) --- + // AI 语音(oidb 0x929D / 0x929B)。 h.registerAction('get_ai_characters', async (params) => { const groupId = asNumber(params.group_id); @@ -1217,9 +1157,9 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { } }); - // napcat's send_group_ai_record is a side-effect-only call: invoking - // fetchAiVoice publishes the voice into the group; the returned - // message_id is always 0 because the oidb call doesn't echo one back. + // NapCat 的 send_group_ai_record 是仅产生副作用的调用。 + // 调用 fetchAiVoice 会把语音发布到群里。 + // 返回的 message_id 始终为 0,因为 oidb 调用不会回显消息 ID。 h.registerAction('send_group_ai_record', async (params) => { const groupId = asNumber(params.group_id); const character = asString(params.character); @@ -1240,7 +1180,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { function hexToBytes(hex: string): Uint8Array { const out = new Uint8Array(hex.length / 2); for (let i = 0; i < out.length; i++) { - out[i] = parseInt(hex.substr(i * 2, 2), 16); + out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); } return out; } @@ -1250,9 +1190,6 @@ function bytesToHex(buf: Buffer | Uint8Array): string { return arr.toString('hex'); } -/** - * Parse download_file headers parameter into a Record. - */ function parseDownloadHeaders(headers: unknown): Record { const result: Record = {}; if (!headers) return result; diff --git a/packages/onebot/src/actions/group-admin.ts b/packages/onebot/src/actions/group-admin.ts index 23bda0e2..2eda8977 100644 --- a/packages/onebot/src/actions/group-admin.ts +++ b/packages/onebot/src/actions/group-admin.ts @@ -1,5 +1,5 @@ -import type { ApiHandler, ApiActionContext } from '../api-handler'; -import { asNumber, asString, asBoolean } from '../api-handler'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { asBoolean, asNumber, asString } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; export function register(h: ApiHandler, ctx: ApiActionContext): void { @@ -103,10 +103,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse(); }); - // Highway upload with cmdId 3000 + GroupAvatarExtra (Lagrange protocol). - // `file` accepts everything bridge.setGroupAvatar's underlying - // loadBinarySource handles: local paths, file:// URLs, http(s) URLs, - // and base64:// data URIs — same surface as set_qq_avatar. h.registerAction('set_group_portrait', async (params) => { const groupId = asNumber(params.group_id); const file = asString(params.file); @@ -119,4 +115,4 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); } }); -} \ No newline at end of file +} diff --git a/packages/onebot/src/actions/group-album.ts b/packages/onebot/src/actions/group-album.ts index b7f8b1e9..80628ded 100644 --- a/packages/onebot/src/actions/group-album.ts +++ b/packages/onebot/src/actions/group-album.ts @@ -1,7 +1,7 @@ -import type { ApiHandler, ApiActionContext } from '../api-handler'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; import { asNumber, asString } from '../api-handler'; -import { RETCODE, failedResponse, okResponse } from '../types'; import type { JsonValue } from '../types'; +import { RETCODE, failedResponse, okResponse } from '../types'; export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_group_album_list', async (params) => { @@ -47,9 +47,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(groupId, albumId, attachInfo); - // GroupAlbumMediaResult is a concrete domain type; okResponse - // expects JsonValue. The shape is JSON-compatible — same as the - // old ctx wrapper returning `Promise`. return okResponse(mediaList as unknown as JsonValue); } catch (error) { const message = error instanceof Error ? error.message : 'failed to get group album media list'; @@ -70,10 +67,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { try { const comment = await ctx.bridge.apis.groupAlbum.comment(groupId, albumId, lloc, content); - // GroupAlbumCommentResult is a concrete domain type; okResponse - // expects JsonValue. The shape is JSON-compatible (no functions - // / classes / bigints), so cast is safe — same as the old ctx - // wrapper returning `Promise`. return okResponse(comment as unknown as JsonValue); } catch (error) { const message = error instanceof Error ? error.message : 'failed to comment on album media'; diff --git a/packages/onebot/src/actions/group-info.ts b/packages/onebot/src/actions/group-info.ts index ae302de6..0e4d7eee 100644 --- a/packages/onebot/src/actions/group-info.ts +++ b/packages/onebot/src/actions/group-info.ts @@ -1,7 +1,7 @@ import type { ApiHandler, ApiActionContext } from '../api-handler'; import { asNumber, asBoolean, asString } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; -import { WebHonorType } from '@snowluma/bridge/web/group-honor'; +import { WebHonorType } from '@snowluma/protocol/web/group-honor'; export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_group_list', async (params) => { diff --git a/packages/onebot/src/actions/info.ts b/packages/onebot/src/actions/info.ts index 06ecdceb..ee8457e1 100644 --- a/packages/onebot/src/actions/info.ts +++ b/packages/onebot/src/actions/info.ts @@ -1,4 +1,4 @@ -import type { ApiHandler, ApiActionContext } from '../api-handler'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; import { okResponse } from '../types'; export function register(h: ApiHandler, ctx: ApiActionContext): void { @@ -12,8 +12,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse({ online, good: online }); }); - // __APP_VERSION__ is injected by Vite from the monorepo root package.json; - // it's undefined under vitest (no define plugin), so fall back to 'dev'. + // 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。 const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev'; h.registerAction('get_version_info', async () => { return okResponse({ diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index 60b0649e..7a9546f7 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -1,24 +1,20 @@ -import type { JsonObject, JsonValue, MessageMeta } from './types'; -import type { ForwardPreviewMeta } from './modules/message-actions'; -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; -import { RETCODE, failedResponse } from './types'; -import { createLogger, type Logger } from '@snowluma/common/logger'; import { summarizeParams } from '@snowluma/common/log-summary'; - -const moduleLog = createLogger('Bridge.Action'); - +import { createLogger, type Logger } from '@snowluma/common/logger'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import { register as registerExtended } from './actions/extended'; +import { register as registerFriend } from './actions/friend'; +import { register as registerGroupAdmin } from './actions/group-admin'; +import { register as registerGroupAlbum } from './actions/group-album'; +import { register as registerGroupFile } from './actions/group-file'; +import { register as registerGroupInfo } from './actions/group-info'; import { register as registerInfo } from './actions/info'; import { register as registerMessage } from './actions/message'; -import { register as registerFriend } from './actions/friend'; -import { register as registerGroupInfo } from './actions/group-info'; -import { register as registerGroupAdmin } from './actions/group-admin'; -import { register as registerGroupFile } from './actions/group-file'; import { register as registerRequest } from './actions/request'; -import { register as registerExtended } from './actions/extended'; -import { register as registerGroupAlbum } from './actions/group-album'; +import type { ForwardPreviewMeta } from './modules/message-actions'; +import type { JsonObject, JsonValue, MessageMeta } from './types'; +import { RETCODE, failedResponse } from './types'; +const moduleLog = createLogger('Bridge.Action'); -import { WebHonorType } from '@snowluma/bridge/web/group-honor'; -import type { ClientKeyInfo } from '@snowluma/core/bridge'; export interface MessageSendResult { messageId: number; @@ -30,21 +26,14 @@ export interface GroupEssenceMsgRet { retcode: number; data: { is_end: boolean; - msg_list: any[]; - [key: string]: any; + msg_list: JsonObject[]; + [key: string]: JsonValue; }; - [key: string]: any; + [key: string]: JsonValue; } export interface ApiActionContext { - /** - * Direct access to the BridgeInterface. Use for actions that are pure - * 1:1 calls to a Bridge method — no rename, no default args, no - * composition with messageStore / mediaStore. When translation IS - * needed, route through the named adapters declared below instead. - */ bridge: BridgeInterface; - getLoginInfo: () => { userId: number; nickname: string }; isOnline: () => boolean; getMessage: (messageId: number) => JsonObject | null; @@ -54,37 +43,16 @@ export interface ApiActionContext { deleteMessage: (messageId: number, meta: MessageMeta) => Promise; canSendImage: () => boolean; canSendRecord: () => boolean; - // Info retrieval (async — triggers OIDB fetch) getFriendList: () => Promise; getGroupList: (noCache?: boolean) => Promise; getGroupInfo: (groupId: number, noCache?: boolean) => Promise; getGroupMemberList: (groupId: number, noCache?: boolean) => Promise; getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => Promise; getStrangerInfo: (userId: number) => Promise; - // Group admin (mute/kick/admin/card/name/title/leave/etc) — all - // accessed directly through `ctx.bridge.apis.groupAdmin.method()` - // after the #6 OneBot-side slim-down; no per-method passthrough - // here anymore. - // Group file passthroughs are gone — actions call - // `ctx.bridge.apis.groupFile.{upload,uploadPrivate,getUrl, - // createFolder,getPrivateUrl,getCount}` directly. `getGroupFiles` - // stays because it composes through the `getGroupFiles` module - // helper (identity-lookup enrichment of uploader names). getGroupFiles: (groupId: number, folderId?: string) => Promise; - // Friend requests: direct via `ctx.bridge.apis.friend.handleRequest`. - // Group requests: stay on ctx because `handleGroupAddRequest` is a - // module helper that does the flag-parsing + group-request lookup - // dance before routing to `bridge.apis.groupAdmin.setAddRequest`. handleGroupRequest: (flag: string, subType: string, approve: boolean, reason: string) => Promise; - // Pokes: direct via `ctx.bridge.apis.interaction.sendPoke(isGroup, …)`. - // Essence (adapter: bakes the set/unset boolean) setEssenceMsg: (messageId: number) => Promise; deleteEssenceMsg: (messageId: number) => Promise; - // Profile reads and group essence reads: direct via - // `ctx.bridge.apis.profile.getLike(...)` and - // `ctx.bridge.apis.web.getEssence(...)`. - // Friend deletion: direct via `ctx.bridge.apis.friend.delete(userId, block)`. - // Module wrappers / multi-dep compositions getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise; getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise; handleGetGroupSystemMsg: () => Promise; @@ -94,19 +62,18 @@ export interface ApiActionContext { sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>; getForwardMsg: (resId: string) => Promise; forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>; - // setMsgEmojiLike: stays because it threads messageStore meta lookup. setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise; - // All other extended / NapCat-compatible / Web / Album actions are - // accessed directly through `ctx.bridge.apis..()`: - // * profile area: setProfile / setOnlineStatus / fetchCustomFace / - // setGroupAvatar / getLike - // * friend area: setRemark / delete / handleRequest - // * web area: getHonorInfo / getEssence(All) / sendNotice / - // getNotice / deleteNotice / getCookiesStr / - // getCsrfToken / getCredentials / forceFetchClientKey - // * groupAlbum area: list / upload / getMediaList / comment / - // delete / like - // Media lookup (populated from previously dispatched message segments) + fetchEmojiLikeUsers: ( + messageId: number, + emojiId: string, + count: number, + offset?: number, + ) => Promise<{ + users: Array<{ uin: number; uid: string; setAt: number }>; + cachedCount: number; + serverCount: number; + complete: boolean; + }>; getImageInfo: (file: string) => Promise; getRecordInfo: (file: string) => Promise; } diff --git a/packages/onebot/src/config.ts b/packages/onebot/src/config.ts index e2c94a18..828393b2 100644 --- a/packages/onebot/src/config.ts +++ b/packages/onebot/src/config.ts @@ -1,7 +1,7 @@ +import { createLogger } from '@snowluma/common/logger'; +import { randomBytes } from 'crypto'; import fs from 'fs'; import path from 'path'; -import { randomBytes } from 'crypto'; -import { createLogger } from '@snowluma/common/logger'; import type { HttpClientNetwork, HttpServerNetwork, @@ -54,13 +54,6 @@ function generateAccessToken(): string { } export interface LoadOneBotConfigOptions { - /** - * Persist the normalized config to disk when the file is missing or was - * in legacy format. Default `false` so accidental call sites (read-only - * GETs in particular) don't generate fresh access tokens, race on - * concurrent writes, or surprise the operator with materialized files. - * Pass `true` from boot / explicit POST handlers. - */ persistDefaults?: boolean; } @@ -70,9 +63,6 @@ export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions = const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`); const globalRaw = tryLoadJson(DEFAULT_CONFIG_PATH); const perUinRaw = tryLoadJson(perUinPath); - - // Detect legacy on-disk format (top-level per-type arrays). We auto-migrate - // these entries into `networks.*` and rewrite the file on the next save. const legacy = !!perUinRaw && hasLegacyTopLevel(perUinRaw); const sources: JsonObject[] = []; @@ -162,11 +152,6 @@ function wsClientToJson(n: WsClientNetwork): JsonObject { } function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig { - // Legacy top-level scalars are pulled DOWN into each adapter on the first - // load: the on-disk schema has no globals anymore, every adapter is - // self-describing. We compute the legacy fallbacks here so that adapters - // missing `messageFormat`/`reportSelfMessage` inherit them once and the - // file is rewritten in normalized form. let legacyFormat: MessageFormat | undefined; let legacyReport: boolean | undefined; let musicSignUrl = ''; @@ -178,19 +163,11 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig { } const inheritedFormat: MessageFormat = legacyFormat ?? 'array'; const inheritedReport: boolean = legacyReport ?? false; - - // Pluck per-type arrays from each source: prefer `networks.` over - // legacy top-level arrays, but accept both. Later sources override earlier - // ones at the network level (last write wins per `(kind, name)` pair). const adapterDefaults = { messageFormat: inheritedFormat, reportSelfMessage: inheritedReport }; const httpServers = collectByName(sources, 'httpServers', (raw) => parseHttpServer(raw, adapterDefaults)); const httpClients = collectByName(sources, 'httpClients', (raw) => parseHttpClient(raw, adapterDefaults), 'httpPostEndpoints'); const wsServers = collectByName(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults)); const wsClients = collectByName(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults)); - - // Seed defaults ONLY for a brand-new install (no source files at all). - // If the operator deliberately emptied every adapter, respect that and - // do NOT silently revive default 0.0.0.0 listeners. if ( freshInstall && httpServers.length === 0 && @@ -340,8 +317,6 @@ function clean>(obj: T): T { } function asRole(value: unknown, fallback: WsRole): WsRole { - // Accept both uppercase (canonical) and lowercase (legacy on-disk) forms. - // Lowercase values are auto-migrated to uppercase on the next save. const text = asString(value, fallback).toLowerCase(); if (text === 'api') return 'Api'; if (text === 'event') return 'Event'; diff --git a/packages/onebot/src/env.d.ts b/packages/onebot/src/env.d.ts index c1f1bcd1..32800b0b 100644 --- a/packages/onebot/src/env.d.ts +++ b/packages/onebot/src/env.d.ts @@ -1,8 +1,2 @@ -// Globals injected by Vite at build time (see `packages/core/vite.config.ts`). -// `__APP_VERSION__` reads from the monorepo root `package.json::version`; -// `__BUILD_WEBUI__` flips on when `BUILD_WEBUI=true` is set so the runner -// stitches the SPA assets in. Both are typed as `unknown` outside vite -// (e.g. when running tests via vitest where the plugin isn't applied) — -// callers guard with `typeof __APP_VERSION__ !== 'undefined'`. declare const __BUILD_WEBUI__: boolean; declare const __APP_VERSION__: string; diff --git a/packages/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index adb7dbe2..16f13f34 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -1,4 +1,4 @@ -import type { MessageElement, QQEventVariant } from '@snowluma/bridge/events'; +import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events'; import type { JsonObject } from '../types'; import { convertFriendMessage, @@ -25,16 +25,10 @@ import { } from './to-request'; import { elementsToJson } from './to-segment'; -// ─────────────── resolver callback types ─────────────── - export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string; export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise; export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number; -/** - * Side-channel callback invoked every time an image / record / video - * segment is produced, so callers can keep a lookup index (e.g. for - * `get_image` / `get_record`) without re-scanning the message store. - */ + export type MediaSegmentSink = ( mediaType: 'image' | 'record' | 'video', element: MessageElement, @@ -45,15 +39,7 @@ export type MediaSegmentSink = ( // ─────────────── context ─────────────── -/** - * Everything `convertEvent` needs that isn't on the bridge event itself. - * Built once per OneBotInstance and passed through unchanged. Resolvers - * are nullable because tests routinely omit them; when missing, the - * converter falls back to the bridge event's own fields (e.g. raw - * `element.url`, raw `event.msgSeq`). - */ export interface ConverterContext { - /** Self uin parsed once into a Number for inclusion in `self_id`. */ selfId: number; imageUrlResolver: ImageUrlResolver | null; mediaUrlResolver: MediaUrlResolver | null; @@ -63,11 +49,6 @@ export interface ConverterContext { // ─────────────── dispatcher ─────────────── -/** - * Convert a bridge `QQEventVariant` to the OneBot wire-shape JSON. - * Returns null for kinds we don't surface (so callers can skip them - * without an explicit allow-list). - */ export async function convertEvent( ctx: ConverterContext, event: QQEventVariant, @@ -101,15 +82,6 @@ export async function convertEvent( } } -// ─────────────── side-channel re-export ─────────────── - -/** - * Element-array -> OneBot segment-array helper. Used by - * `modules/message-actions.ts` for forward-message rebuilding (where - * we already know the elements but want the OneBot segment shape). - * The signature stays backwards-compatible: each resolver is an - * optional positional argument. - */ export async function elementsToOneBotSegments( elements: MessageElement[], isGroup: boolean, diff --git a/packages/onebot/src/event-converter/to-message.ts b/packages/onebot/src/event-converter/to-message.ts index f87353fd..5f667a95 100644 --- a/packages/onebot/src/event-converter/to-message.ts +++ b/packages/onebot/src/event-converter/to-message.ts @@ -1,9 +1,10 @@ -import type { QQEventVariant } from '@snowluma/bridge/events'; +import type { QQEventVariant } from '@snowluma/protocol/events'; +import { segmentsToRawMessage } from '../helper/cq'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id'; import type { JsonObject } from '../types'; import type { ConverterContext } from './index'; import { elementsToJson } from './to-segment'; -import { applyMessageIdResolver, segmentsToRawMessage } from './utils'; +import { applyMessageIdResolver } from './utils'; type FriendMessage = Extract; type GroupMessage = Extract; diff --git a/packages/onebot/src/event-converter/to-notice.ts b/packages/onebot/src/event-converter/to-notice.ts index 76af6b26..b66899f1 100644 --- a/packages/onebot/src/event-converter/to-notice.ts +++ b/packages/onebot/src/event-converter/to-notice.ts @@ -1,4 +1,4 @@ -import type { QQEventVariant } from '@snowluma/bridge/events'; +import type { QQEventVariant } from '@snowluma/protocol/events'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id'; import type { JsonObject } from '../types'; import type { ConverterContext } from './index'; @@ -183,17 +183,7 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO }; } -/** - * Group message emoji reaction notice. Matches the gocqhttp / NapCat - * extension shape (`notice_type: 'group_msg_emoji_like'`) since OneBot - * v11 standard has no slot for reactions and that's what every - * downstream framework keys off. - */ export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject { - // Reconstruct the OneBot message_id we originally minted for the - // reacted-to message. hashMessageIdInt32 is deterministic so the ID - // matches whatever the client received at receive-time, even when - // the message has fallen out of our store. const messageId = applyMessageIdResolver( ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT, ); diff --git a/packages/onebot/src/event-converter/to-request.ts b/packages/onebot/src/event-converter/to-request.ts index 9b3d0b50..3ef5024d 100644 --- a/packages/onebot/src/event-converter/to-request.ts +++ b/packages/onebot/src/event-converter/to-request.ts @@ -1,4 +1,4 @@ -import type { QQEventVariant } from '@snowluma/bridge/events'; +import type { QQEventVariant } from '@snowluma/protocol/events'; import type { JsonObject } from '../types'; import type { ConverterContext } from './index'; diff --git a/packages/onebot/src/event-converter/to-segment.ts b/packages/onebot/src/event-converter/to-segment.ts index 8e0829bb..f7a33d7c 100644 --- a/packages/onebot/src/event-converter/to-segment.ts +++ b/packages/onebot/src/event-converter/to-segment.ts @@ -1,4 +1,4 @@ -import type { MessageElement } from '@snowluma/bridge/events'; +import type { MessageElement } from '@snowluma/protocol/events'; import type { JsonArray, JsonObject } from '../types'; import type { ImageUrlResolver, @@ -142,8 +142,5 @@ async function elementToSegment( data: { id: element.resId ?? '' }, }; } - - // Unknown / unmapped element type — emit an empty segment to keep the - // outgoing message length consistent with the bridge event. return { type: element.type, data: {} }; } diff --git a/packages/onebot/src/event-converter/utils.ts b/packages/onebot/src/event-converter/utils.ts index 82523dc6..ab2af109 100644 --- a/packages/onebot/src/event-converter/utils.ts +++ b/packages/onebot/src/event-converter/utils.ts @@ -1,5 +1,4 @@ import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id'; -import type { JsonArray, JsonObject } from '../types'; import type { MessageIdResolver } from './index'; export function parseSelfId(instanceUin: string): number { @@ -7,11 +6,6 @@ export function parseSelfId(instanceUin: string): number { return Number.isNaN(parsed) ? 0 : parsed; } -/** - * Two QQEvent actors are "the same" when their uins match, or their - * uids match when uins aren't available. Used by the group_member_join - * sub-type calculation (self-approve vs. invite). - */ export function isSameActor( leftUin: number, leftUid: string | undefined, @@ -22,10 +16,6 @@ export function isSameActor( return Boolean(leftUid) && leftUid === rightUid; } -/** - * Run the optional MessageId resolver, falling back to the raw - * sequence when no resolver is wired or it returns 0. - */ export function applyMessageIdResolver( resolver: MessageIdResolver | null, isGroup: boolean, @@ -58,48 +48,3 @@ export function resolveReplyId( return seq; } - -// ─────────────── raw_message (CQ string) generation ─────────────── - -function cqEscape(text: string): string { - return text.replace(/&/g, '&').replace(/\[/g, '[').replace(/\]/g, ']').replace(/,/g, ','); -} - -export function segmentsToRawMessage(segments: JsonArray): string { - return segments.map(seg => segmentToCQ(seg as JsonObject)).join(''); -} - -function segmentToCQ(seg: JsonObject): string { - const type = String(seg.type ?? ''); - const data = (seg.data ?? {}) as Record; - switch (type) { - case 'text': - return cqEscape(String(data.text ?? '')); - case 'face': - return `[CQ:face,id=${data.id ?? 0}]`; - case 'image': - return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; - case 'at': - return `[CQ:at,qq=${data.qq ?? ''}]`; - case 'reply': - return `[CQ:reply,id=${data.id ?? 0}]`; - case 'record': - return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; - case 'video': - return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; - case 'json': - return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`; - case 'xml': - return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`; - case 'forward': - return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`; - case 'mface': - return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`; - case 'poke': - return `[CQ:poke,type=${data.type ?? 0}]`; - case 'file': - return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; - default: - return `[CQ:${type}]`; - } -} diff --git a/packages/onebot/src/event-filter.ts b/packages/onebot/src/event-filter.ts index a3d90ae6..b4893573 100644 --- a/packages/onebot/src/event-filter.ts +++ b/packages/onebot/src/event-filter.ts @@ -1,16 +1,9 @@ import type { JsonObject, JsonValue, MessageFormat } from './types'; export interface EventReportOptions { - /** Effective `messageFormat` for this adapter. */ messageFormat: MessageFormat; - /** Whether self-sent messages should be forwarded to this adapter. */ reportSelfMessage: boolean; } -/** - * Extract the dispatch options from an adapter. Each adapter is fully - * self-describing — there is no global fallback. Defaults are applied here - * only as a safety net for partially-deserialized legacy configs. - */ export function resolveReportOptions( network: { messageFormat?: MessageFormat; reportSelfMessage?: boolean }, ): EventReportOptions { @@ -20,32 +13,12 @@ export function resolveReportOptions( }; } -/** - * Pre-built payload covering every adapter variant of a single canonical event. - * - * The bridge produces one OneBot-shaped event per upstream packet. Because - * adapters only differ in (a) whether they receive `message_sent` self-events - * and (b) whether the `message` field is the segment array or its CQ-string - * form, we serialize the event at most twice up-front and let every adapter - * pick the slot it needs in O(1). - */ export interface DispatchPayload { - /** True when the canonical event is a self-sent message (`post_type='message_sent'`). */ isSelfMessage: boolean; - /** JSON for adapters using `messageFormat: 'array'` (the canonical event). */ arrayJson: string; - /** - * JSON for adapters using `messageFormat: 'string'`. For non-message events - * this points at the same string as `arrayJson` (no transformation needed). - */ stringJson: string; } -/** - * Build the dispatch payload for one canonical OneBot event. Performs at most - * two `JSON.stringify` calls (one per format variant) regardless of how many - * adapters the payload will fan out to. - */ export function buildDispatchPayload(event: JsonObject): DispatchPayload { const isSelfMessage = event.post_type === 'message_sent'; const arrayJson = JSON.stringify(event); @@ -60,11 +33,6 @@ export function buildDispatchPayload(event: JsonObject): DispatchPayload { return { isSelfMessage, arrayJson, stringJson }; } -/** - * Pick the pre-serialized payload variant an adapter should send, or `null` - * when the adapter chose not to receive this event. Hot-path helper: one - * branch + one map lookup per connection, no allocation. - */ export function pickDispatchJson( payload: DispatchPayload, options: EventReportOptions, @@ -73,14 +41,6 @@ export function pickDispatchJson( return options.messageFormat === 'string' ? payload.stringJson : payload.arrayJson; } -/** - * One-shot variant of {@link buildDispatchPayload} + {@link pickDispatchJson} - * for ad-hoc events (e.g. WS connection bootstrap meta events) that aren't - * worth pre-building a full payload for. - * - * Returns `null` when the adapter shouldn't see this event. Otherwise returns - * the original event untouched, or a shallow clone with `message` rewritten. - */ export function shapeEventForAdapter( event: JsonObject, options: EventReportOptions, diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index a9e04944..a6a637f7 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -1,20 +1,10 @@ -import type { QQEventVariant } from '@snowluma/bridge/events'; +import type { QQEventVariant } from '@snowluma/protocol/events'; import { convertEvent } from './event-converter'; import type { OneBotInstanceContext } from './instance-context'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id'; -/** - * Subscribe every `OneBotInstanceContext`-aware handler onto the bridge - * event bus. Returns a disposer that removes every subscription registered - * here in one shot — useful for tests and for tearing down a session. - */ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void { const disposers: Array<() => void> = []; - - // Every kind that maps onto an OB11 message event also seeds the - // message-meta cache; we do that synchronously before async conversion so - // reply / quote lookups for that message id work even if the converter - // takes a beat to finish (e.g. while resolving image URLs). disposers.push( ctx.bridge.events.on('group_message', async (event) => { cacheGroupMessageMeta(ctx, event); @@ -33,12 +23,12 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void { await convertAndDispatch(ctx, event); }), ); - - // Notice / request / non-message events: no meta caching needed, just - // convert and dispatch. for (const kind of NOTICE_KINDS) { disposers.push( ctx.bridge.events.on(kind, async (event) => { + if (event.kind === 'group_msg_emoji_like') { + cacheReaction(ctx, event); + } await convertAndDispatch(ctx, event); }), ); @@ -105,3 +95,28 @@ function cachePrivateMessageMeta( timestamp, }); } + +function cacheReaction( + ctx: OneBotInstanceContext, + event: Extract, +): void { + if (!event.groupId || !event.msgSeq || !event.emojiId || !event.operatorUin) return; + if (event.isAdd) { + ctx.reactionStore.recordAdd( + event.groupId, + event.msgSeq, + event.emojiId, + 1, + event.operatorUin, + event.operatorUid, + event.time, + ); + } else { + ctx.reactionStore.recordRemove( + event.groupId, + event.msgSeq, + event.emojiId, + event.operatorUin, + ); + } +} diff --git a/packages/onebot/src/helper/cq.ts b/packages/onebot/src/helper/cq.ts new file mode 100644 index 00000000..1ba348b0 --- /dev/null +++ b/packages/onebot/src/helper/cq.ts @@ -0,0 +1,80 @@ +import type { MessageElement } from '@snowluma/protocol/events'; +import { CQ_REGEX, parseCQParams, ParseMessageOptions, segmentToElement } from '../message-parser'; +import type { JsonArray, JsonObject } from '../types'; + + +export function segmentToCQ(seg: JsonObject): string { + const type = String(seg.type ?? ''); + const data = (seg.data ?? {}) as Record; + switch (type) { + case 'text': + return cqEscape(String(data.text ?? '')); + case 'face': + return `[CQ:face,id=${data.id ?? 0}]`; + case 'image': + return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + case 'at': + return `[CQ:at,qq=${data.qq ?? ''}]`; + case 'reply': + return `[CQ:reply,id=${data.id ?? 0}]`; + case 'record': + return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + case 'video': + return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + case 'json': + return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`; + case 'xml': + return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`; + case 'forward': + return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`; + case 'mface': + return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`; + case 'poke': + return `[CQ:poke,type=${data.type ?? 0}]`; + case 'file': + return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`; + default: + return `[CQ:${type}]`; + } +} export function segmentsToRawMessage(segments: JsonArray): string { + return segments.map(seg => segmentToCQ(seg as JsonObject)).join(''); +} +export function cqEscape(text: string): string { + return text.replace(/&/g, '&').replace(/\[/g, '[').replace(/\]/g, ']').replace(/,/g, ','); +} +export function cqUnescape(text: string): string { + // Order matters: `&` MUST be last so that, e.g., `&#91;` keeps + // the literal `[` instead of decoding twice into `[`. + return text + .replace(/[/g, '[') + .replace(/]/g, ']') + .replace(/,/g, ',') + .replace(/&/g, '&'); +} +export async function parseFromCQString(message: string, options?: ParseMessageOptions): Promise { + const elements: MessageElement[] = []; + let lastIndex = 0; + + for (const match of message.matchAll(CQ_REGEX)) { + // Text before this CQ code + if (match.index! > lastIndex) { + const text = cqUnescape(message.substring(lastIndex, match.index!)); + if (text) elements.push({ type: 'text', text }); + } + lastIndex = match.index! + match[0].length; + + const cqType = match[1]; + const params = parseCQParams(match[2] || ''); + const elem = await segmentToElement(cqType, params, options); + if (elem) elements.push(elem); + } + + // Trailing text + if (lastIndex < message.length) { + const text = cqUnescape(message.substring(lastIndex)); + if (text) elements.push({ type: 'text', text }); + } + + return elements; +} + diff --git a/packages/onebot/src/instance-context.ts b/packages/onebot/src/instance-context.ts index c6238e5c..e32fecfc 100644 --- a/packages/onebot/src/instance-context.ts +++ b/packages/onebot/src/instance-context.ts @@ -1,10 +1,10 @@ -import type { WebHonorType } from '@snowluma/bridge/web/group-honor'; import type { Bridge } from '@snowluma/core/bridge'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { WebHonorType } from '@snowluma/protocol/web/group-honor'; import type { ApiActionContext } from './api-handler'; import type { ConverterContext } from './event-converter'; import type { MediaStore } from './media-store'; import type { MessageStore } from './message-store'; -import type { JsonObject, MessageMeta, OneBotConfig } from './types'; import { getDownloadRKeys, getFriendList, @@ -17,6 +17,10 @@ import { getLoginInfo, getStrangerInfo, } from './modules/contact-actions'; +import { + getImageInfo as getCachedImageInfo, + getRecordInfo as getCachedRecordInfo, +} from './modules/media-actions'; import { deleteMessage, forwardSingleMessage, @@ -30,63 +34,26 @@ import { setEssenceMessage, uploadForwardMessage, } from './modules/message-actions'; -import { - getImageInfo as getCachedImageInfo, - getRecordInfo as getCachedRecordInfo, -} from './modules/media-actions'; import { handleGroupAddRequest } from './modules/request-actions'; -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { ReactionStore } from './reaction-store'; +import type { JsonObject, MessageMeta, OneBotConfig } from './types'; -/** - * Single shared context bag that flows through every OneBot instance-internal - * subsystem: API builder and the per-kind event pipeline. - * - * Only fields that are actually read through this bag live here. The API - * handler and network manager are owned by `OneBotInstance` directly because - * nothing reads them via ctx, and including them here would force a - * chicken-and-egg late-bound field dance during construction. - * - * `dispatchEvent` is the indirection used by the event pipeline to hand a - * converted OneBot event back to the instance for caching + adapter fan-out; - * it lets the pipeline stay decoupled from the network manager. - */ export interface OneBotInstanceContext { - /** Self UIN as string (matches what's on disk and on the wire). */ uin: string; - /** Self UIN parsed once, used in event payloads. */ selfId: number; - bridge: BridgeInterface; - messageStore: MessageStore; mediaStore: MediaStore; - + reactionStore: ReactionStore; converterCtx: ConverterContext; - config: OneBotConfig; musicSignUrl?: string; - - /** Persist meta about a message id; safe to call any number of times. */ cacheMessageMeta(messageId: number, meta: MessageMeta): void; - /** Hand a fully-converted OneBot event to the network manager + caches. */ dispatchEvent(event: JsonObject): void; } -/** - * Build the ApiActionContext that ApiHandler hands to each action file. - * - * Two flavours of entries live in here: - * - Adapters — rename a Bridge method (setGroupKick → kickGroupMember), - * compose with messageStore / mediaStore / ref, bake in a constant - * (setEssenceMsg passes true; deleteEssenceMsg passes false), bridge a - * bridge call into OneBot vocabulary (sendFriendPoke flattens the - * isGroup boolean), or extract a field from the bridge return shape. - * - Pass-throughs used to live here too but added zero value; OneBot - * actions now call `ctx.bridge.` directly when no translation is - * happening (set_group_admin, set_online_status, set_avatar, …). - */ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { - const { bridge, messageStore, mediaStore } = ref; + const { bridge, messageStore, mediaStore, reactionStore } = ref; return { bridge, @@ -97,38 +64,19 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { getMessageMeta: (messageId) => messageStore.findMeta(messageId), canSendImage: () => true, canSendRecord: () => true, - - // OneBot11 message actions. sendPrivateMessage: (userId, message, autoEscape) => sendPrivateMessage(ref, userId, message, autoEscape), sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape), deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta), - - // OneBot11 info actions (wrap modules that also touch identity). getFriendList: () => getFriendList(bridge), getGroupList: (noCache) => getGroupList(bridge, noCache), getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache), getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, groupId, noCache), getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, groupId, userId, noCache), getStrangerInfo: (userId) => getStrangerInfo(bridge, userId), - - // Group admin — actions now call `ctx.bridge.apis.groupAdmin.X(...)` - // directly; no per-method passthrough here anymore. - - // Group file — `getGroupFiles` stays because the module helper - // enriches uploader/creator names from the identity cache; the - // rest of the area is called directly via `ctx.bridge.apis.groupFile.*`. getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId), - - // Group request handling stays here because `handleGroupAddRequest` - // is a module helper (flag parsing + group-request lookup). Friend - // request handling moved to direct `ctx.bridge.apis.friend.handleRequest`. handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason), - - // Message-store-backed history reads. getGroupMsgHistory: (groupId, messageId, count) => getGroupMsgHistory(messageStore, groupId, messageId, count), getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count), - - // Module wrappers / multi-dep compositions. handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge), getDownloadRKeys: () => getDownloadRKeys(bridge), sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta), @@ -136,32 +84,40 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId), getForwardMsg: (resId) => getForwardMessage(ref, resId), forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target), - - // Essence — bakes the set/unset boolean (the only "compose with - // messageStore meta lookup" entry remaining outside of dedicated - // module helpers). setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true), deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false), - - // Emoji-like — same shape: meta lookup → bridge call. Group-only - // (QQ doesn't expose emoji reactions on private chats). setMsgEmojiLike: async (messageId, emojiId, set) => { const meta = messageStore.findMeta(messageId); if (!meta) throw new Error('message not found'); if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages'); await bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, emojiId, set); }, - - // Media lookup. + fetchEmojiLikeUsers: async (messageId, emojiId, count, offset = 0) => { + const meta = messageStore.findMeta(messageId); + if (!meta) throw new Error('message not found'); + if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages'); + const raw = reactionStore.listUsers(meta.targetId, meta.sequence, emojiId, count, offset); + const users = raw.map(r => ({ uin: r.operatorUin, uid: r.operatorUid, setAt: r.setAt })); + const cachedCount = reactionStore.countUsers(meta.targetId, meta.sequence, emojiId); + let serverCount = cachedCount; + try { + const summary = await bridge.apis.interaction.fetchReactionSummary(meta.targetId, meta.sequence); + const match = summary.find(s => s.emojiId === emojiId); + if (match) serverCount = match.count; + } catch { + /* keep serverCount = cachedCount */ + } + return { + users, + cachedCount, + serverCount, + complete: cachedCount >= serverCount, + }; + }, getImageInfo: (file) => getCachedImageInfo(mediaStore, file), getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file), }; } -// Re-export Bridge type so consumers of OneBotInstanceContext that need it -// (legacy) keep the import surface stable. -export type { Bridge }; +export type { Bridge, WebHonorType }; -// Re-export WebHonorType so legacy spots that imported it via this module -// keep working. -export type { WebHonorType }; diff --git a/packages/onebot/src/instance-rkey.ts b/packages/onebot/src/instance-rkey.ts index 101d6628..b713537c 100644 --- a/packages/onebot/src/instance-rkey.ts +++ b/packages/onebot/src/instance-rkey.ts @@ -1,7 +1,7 @@ -import type { MessageElement } from '@snowluma/bridge/events'; +import { createLogger } from '@snowluma/common/logger'; import type { DownloadRKeyInfo } from '@snowluma/core/bridge'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; -import { createLogger } from '@snowluma/common/logger'; +import type { MessageElement } from '@snowluma/protocol/events'; const log = createLogger('OneBot'); @@ -50,11 +50,6 @@ export class RKeyCache { const separator = url.includes('?') ? '&rkey=' : '?rkey='; return url + separator + encodeURIComponent(cleanRKey); } - - /** - * Resolve a URL for video/record/file media elements. - * Appends the correct RKey type based on media kind and group/private context. - */ resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string { const url = element.url ?? ''; if (!url || !urlNeedsRKey(url)) return url; @@ -111,18 +106,13 @@ export class RKeyCache { let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE); if (result) return result; - - // Refresh check cooldown if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null; this.lastRefreshAttempt = now; - - // Schedule async refresh bridge.apis.contacts.fetchDownloadRKeys().then( (rkeys) => this.updateCache(rkeys), () => { /* ignore */ }, ); - // Try again (won't be ready yet for this call, but future calls will benefit) result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE); return result; } @@ -132,8 +122,8 @@ function urlNeedsRKey(url: string): boolean { if (!url || url.includes('rkey=')) return false; if (url.includes('gchat.qpic.cn')) return false; return url.includes('multimedia.nt.qq.com.cn') || - url.includes('.nt.qq.com.cn') || - url.includes('/download'); + url.includes('.nt.qq.com.cn') || + url.includes('/download'); } function stripRKeyPrefix(rkey: string): string { diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 66831037..81c5a286 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -1,26 +1,27 @@ -import path from 'path'; +import { createLogger, type Logger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/protocol/format'; +import path from 'path'; import { ApiHandler } from './api-handler'; import type { ConverterContext } from './event-converter'; +import { registerEventPipeline } from './event-pipeline'; +import { buildApiContext, type OneBotInstanceContext } from './instance-context'; +import { RKeyCache } from './instance-rkey'; import { MediaIndexer } from './media-indexer'; import { MediaStore } from './media-store'; import { MediaUrlResolver } from './media-url-resolver'; -import { MessageStore } from './message-store'; -import { RKeyCache } from './instance-rkey'; -import { buildApiContext, type OneBotInstanceContext } from './instance-context'; -import { registerEventPipeline } from './event-pipeline'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id'; -import type { JsonObject, JsonValue, MessageMeta, OneBotConfig, NetworkBase } from './types'; +import { MessageStore } from './message-store'; import { - OneBotNetworkManager, - WsServerAdapter, - WsClientAdapter, - HttpServerAdapter, HttpPostAdapter, + HttpServerAdapter, + OneBotNetworkManager, + WsClientAdapter, + WsServerAdapter, type NetworkAdapterContext, } from './network'; -import { createLogger, type Logger } from '@snowluma/common/logger'; -import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/bridge/format'; +import { ReactionStore } from './reaction-store'; +import type { JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types'; const moduleLog = createLogger('Event'); @@ -32,9 +33,9 @@ export class OneBotInstance { private readonly converterCtx: ConverterContext; private readonly messageStore: MessageStore; private readonly mediaStore: MediaStore; + private readonly reactionStore: ReactionStore; private readonly networkManager: OneBotNetworkManager; private readonly rkeyCache: RKeyCache; - private readonly ctx: OneBotInstanceContext; private disposeEventPipeline: (() => void) | null = null; private readonly pids = new Set(); @@ -56,10 +57,7 @@ export class OneBotInstance { this.rkeyCache = new RKeyCache(); this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db')); this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json')); - - // The converter context's four callbacks delegate to small, focused - // modules so this constructor doesn't carry the bridge-URL fetch - // branching or the mediaStore field-mapping fanout inline. + this.reactionStore = new ReactionStore(path.join('data', this.uin, 'reactions.db')); const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache); const mediaIndexer = new MediaIndexer(this.mediaStore); this.converterCtx = { @@ -73,23 +71,19 @@ export class OneBotInstance { mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) => mediaIndexer.remember(mediaType, element, data, isGroup, sessionId), }; - - // Shared instance context. Only carries fields that are actually read - // through it — api handler and network manager stay as direct fields on - // the instance because nothing reads them via ctx. const ctx: OneBotInstanceContext = { uin: this.uin, selfId: parseInt(this.uin, 10) || 0, bridge: this.bridge, messageStore: this.messageStore, mediaStore: this.mediaStore, + reactionStore: this.reactionStore, converterCtx: this.converterCtx, config, musicSignUrl: config.musicSignUrl, cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta), dispatchEvent: (event) => this.dispatchEvent(event), }; - this.ctx = ctx; this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined); this.networkManager = new OneBotNetworkManager(); @@ -100,9 +94,6 @@ export class OneBotInstance { this.startHeartbeat(); this.rkeyCache.warmUp(this.bridge, this.uin); - - // Per-kind subscription on the typed event bus. Each bridge event kind - // gets its own focused handler in `event-pipeline`; the firehose is gone. this.disposeEventPipeline = registerEventPipeline(ctx); } @@ -122,6 +113,7 @@ export class OneBotInstance { }); this.messageStore.close(); this.mediaStore.close(); + this.reactionStore.close(); } addPid(pid: number): void { @@ -147,10 +139,6 @@ export class OneBotInstance { private dispatchEvent(event: JsonObject): void { this.cacheMessageEvent(event); this.logReceivedMessage(event); - // NetworkManager builds the dispatch payload once and fans out to every - // active adapter in parallel via Promise.allSettled — per-adapter errors - // are already isolated, so the outer promise should never reject. The - // .catch is a belt-and-suspenders guard against future refactors. void this.networkManager.emitEvent(event).catch((err) => { this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); }); @@ -213,14 +201,11 @@ export class OneBotInstance { await this.networkManager.closeOne(adapter.name); } } - - // Reload existing adapters in place; spin up new ones the manager hasn't - // seen before. for (const [name, net] of desired) { const existing = this.networkManager.get(name); if (existing) { try { - await existing.reload(net as never); + await existing.reload(net); } catch (err) { this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err)); } @@ -328,9 +313,6 @@ export class OneBotInstance { }, }; } - - // --- Heartbeat --- - private startHeartbeat(): void { this.heartbeatTimer = setInterval(() => { this.dispatchEvent(this.makeHeartbeatEvent()); diff --git a/packages/onebot/src/manager.ts b/packages/onebot/src/manager.ts index 5f49e0cc..ed52586a 100644 --- a/packages/onebot/src/manager.ts +++ b/packages/onebot/src/manager.ts @@ -1,6 +1,6 @@ +import { createLogger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import type { BridgeManager } from '@snowluma/core/manager'; -import { createLogger } from '@snowluma/common/logger'; import { loadOneBotConfig } from './config'; import { OneBotInstance } from './instance'; @@ -55,15 +55,10 @@ export class OneBotManager { if (activePid !== null) { instance.addPid(activePid); } - - // Seed nickname with the UIN so the WebUI never renders blank while - // warmup is in flight or if warmup never resolves a real nickname. if (!bridge.identity.nickname) bridge.identity.nickname = uin; this.instances.set(uin, instance); log.info('session started: UIN=%s', uin); - - // Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state) warmUpBridgeState(uin, bridge).catch((err) => { log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err)); }); @@ -97,7 +92,7 @@ async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise< bridge.identity.setSelfProfile({ uin: f.uin, uid: f.uid, nickname: f.nickname || uin, - remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', + remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0, }); bridge.identity.nickname = f.nickname || uin; log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? ''); diff --git a/packages/onebot/src/media-indexer.ts b/packages/onebot/src/media-indexer.ts index 91f4c6a8..4c4be292 100644 --- a/packages/onebot/src/media-indexer.ts +++ b/packages/onebot/src/media-indexer.ts @@ -1,8 +1,4 @@ -// Side-channel observer that watches every image / record / video -// segment emitted by the event converter and writes a row into the -// MediaStore so later `get_image` / `get_record` OneBot actions can - -import type { MessageElement } from '@snowluma/bridge/events'; +import type { MessageElement } from '@snowluma/protocol/events'; import type { MediaStore } from './media-store'; import type { JsonObject } from './types'; diff --git a/packages/onebot/src/media-store.ts b/packages/onebot/src/media-store.ts index 9e6ee8ca..b9f3a0d8 100644 --- a/packages/onebot/src/media-store.ts +++ b/packages/onebot/src/media-store.ts @@ -1,31 +1,18 @@ -// Persistent media metadata store. -// -// The `get_image` / `get_record` actions need to map a `data.file` (or related -// identifier) we previously emitted in a message segment back to the URL, -// size, name, and any OIDB media-node info needed to re-resolve a stale URL. - -import fs from 'fs'; +import type { MessageElement } from '@snowluma/protocol/events'; import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; +import fs from 'fs'; import path from 'path'; -import type { MessageElement } from '@snowluma/bridge/events'; - export interface CachedImage { - /** Primary `data.file` value as exposed in the OneBot segment. */ file: string; - /** Last known resolved URL (may be empty if resolution failed). */ url: string; fileSize: number; fileName: string; subType: number; summary: string; - /** Conversation the media originated from. */ isGroup: boolean; sessionId: number; - /** Original imageUrl from the MessageElement, used for RKey re-appending. */ imageUrl: string; - /** Fingerprints used for md5/sha1 fast-upload on forward. Optional because - * legacy CustomFace / NotOnlineImage only carry md5. */ md5Hex?: string; sha1Hex?: string; width?: number; @@ -34,19 +21,14 @@ export interface CachedImage { } export interface CachedRecord { - /** Primary `data.file` value as exposed in the OneBot segment. */ file: string; - /** Raw fileId from the MessageElement (typically the fileUuid). */ fileId: string; - /** Last known resolved URL (may be empty if resolution failed). */ url: string; fileSize: number; fileName: string; duration: number; fileHash: string; - /** OIDB media node used to re-fetch the URL via getPtt*UrlByNode. */ mediaNode?: MessageElement['mediaNode']; - /** Conversation the media originated from (group vs private path). */ isGroup: boolean; sessionId: number; /** Fingerprints used for md5/sha1 fast-upload on forward. */ diff --git a/packages/onebot/src/media-url-resolver.ts b/packages/onebot/src/media-url-resolver.ts index 2fc0079e..a2cf4c1f 100644 --- a/packages/onebot/src/media-url-resolver.ts +++ b/packages/onebot/src/media-url-resolver.ts @@ -1,5 +1,5 @@ import type { BridgeInterface } from '@snowluma/core/bridge-interface'; -import type { MessageElement } from '@snowluma/bridge/events'; +import type { MessageElement } from '@snowluma/protocol/events'; import type { RKeyCache } from './instance-rkey'; export class MediaUrlResolver { @@ -19,10 +19,6 @@ export class MediaUrlResolver { } return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup); } - - /** Branches by element.type + isGroup to pick the right Bridge API. - * Mutates `element.url` in-place so the caller sees the same URL - * the downstream rkey/media-store path will see. */ private async populateUrl(element: MessageElement, isGroup: boolean, sessionId: number): Promise { if (element.type === 'file' && element.fileId) { if (isGroup) { diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index 940d8d52..23f6fe3f 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -1,5 +1,6 @@ -import type { MessageElement } from '@snowluma/bridge/events'; import { createLogger } from '@snowluma/common/logger'; +import type { MessageElement } from '@snowluma/protocol/events'; +import { parseFromCQString } from './helper/cq'; import type { JsonValue } from './types'; const log = createLogger('MsgParser'); @@ -13,14 +14,8 @@ export interface ParseMessageOptions { // --- CQ Code parsing --- -const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g; +export const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g; -/** - * Best-effort base-10 integer coercion. Falls back to `fallback` (default 0) - * when the input can't be parsed as a finite integer — `parseInt('abc')` - * is `NaN`, which silently turns into `0`/`null` further down the wire - * pipeline and produces undebuggable protocol-level failures. - */ function intOr(value: unknown, fallback = 0): number { if (value === undefined || value === null) return fallback; if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback; @@ -28,7 +23,7 @@ function intOr(value: unknown, fallback = 0): number { return Number.isFinite(n) ? n : fallback; } -function parseCQParams(raw: string): Record { +export function parseCQParams(raw: string): Record { const params: Record = {}; if (!raw) return params; for (const pair of raw.split(',')) { @@ -44,43 +39,6 @@ function parseCQParams(raw: string): Record { return params; } -function cqUnescape(text: string): string { - // Order matters: `&` MUST be last so that, e.g., `&#91;` keeps - // the literal `[` instead of decoding twice into `[`. - return text - .replace(/[/g, '[') - .replace(/]/g, ']') - .replace(/,/g, ',') - .replace(/&/g, '&'); -} - -async function parseFromCQString(message: string, options?: ParseMessageOptions): Promise { - const elements: MessageElement[] = []; - let lastIndex = 0; - - for (const match of message.matchAll(CQ_REGEX)) { - // Text before this CQ code - if (match.index! > lastIndex) { - const text = cqUnescape(message.substring(lastIndex, match.index!)); - if (text) elements.push({ type: 'text', text }); - } - lastIndex = match.index! + match[0].length; - - const cqType = match[1]; - const params = parseCQParams(match[2] || ''); - const elem = await segmentToElement(cqType, params, options); - if (elem) elements.push(elem); - } - - // Trailing text - if (lastIndex < message.length) { - const text = cqUnescape(message.substring(lastIndex)); - if (text) elements.push({ type: 'text', text }); - } - - return elements; -} - // --- JSON segment parsing --- interface MessageSegment { @@ -95,7 +53,7 @@ function isSegmentArray(val: unknown): val is MessageSegment[] { ); } -async function segmentToElement(type: string, data: Record, options?: ParseMessageOptions): Promise { +export async function segmentToElement(type: string, data: Record, options?: ParseMessageOptions): Promise { const normalizedType = type.toLowerCase(); switch (normalizedType) { case 'text': { @@ -120,10 +78,6 @@ async function segmentToElement(type: string, data: Record, opt if (!uid && options?.resolveMentionUid) { uid = (await options.resolveMentionUid(uin))?.trim() ?? ''; } - - // Leave `text` undefined when the caller didn't supply a display - // name. The element-builder then resolves it from the group roster - // (so QQ renders `@昵称` instead of `@QQ号`). const element: MessageElement = { type: 'at', targetUin: uin }; if (uid) element.uid = uid; if (name) element.text = `@${name} `; @@ -333,14 +287,6 @@ async function segmentToElement(type: string, data: Record, opt return null; } case 'file': { - // OneBot11 file segment referencing a previously-uploaded file - // (returned by `upload_group_file` / `upload_private_file`). - // We deliberately do NOT support `{file: '/path'}` here because - // the upload pipeline is async and lives behind the bridge — - // the element-builder runs synchronously over the parsed - // message. Callers that want upload-and-send should use the - // dedicated `upload_*` actions which now publish the file in - // chat atomically (`actions/group-file.ts`). const fileId = String(data.file_id ?? data.fileId ?? '').trim(); if (!fileId) { log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)'); @@ -350,10 +296,6 @@ async function segmentToElement(type: string, data: Record, opt const fileSize = intOr(data.size ?? data.fileSize, 0); const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim(); const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim(); - // file_hash is the c2c-file server-issued addon string — needed - // on the wire when re-sending a previously-uploaded c2c file. - // get_private_file_url callers already pass it through, so honour - // the same field naming here. const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim(); const elem: MessageElement = { type: 'file', fileId }; if (fileName) elem.fileName = fileName; @@ -381,14 +323,6 @@ function segmentPayload(seg: MessageSegment): Record { // --- Public API --- -/** - * Parse an OneBot11 message value into internal MessageElement array. - * Supports: - * - string (plain text or CQ code string) - * - array of { type, data } segments (JSON segment format) - * - * If autoEscape is true, the string is treated as plain text (no CQ parsing). - */ export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise { if (typeof message === 'string') { if (autoEscape) { diff --git a/packages/onebot/src/message-store.ts b/packages/onebot/src/message-store.ts index 32f70d52..c30a3946 100644 --- a/packages/onebot/src/message-store.ts +++ b/packages/onebot/src/message-store.ts @@ -1,21 +1,8 @@ -import fs from 'fs'; import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; +import fs from 'fs'; import path from 'path'; import type { JsonObject, MessageMeta } from './types'; -// Prepared statements are cached as `readonly` fields so the SQL parser -// runs once at construction time. Previously each `db.prepare(sql)` -// inside a hot-path method re-parsed on every call — the textbook -// SQLite anti-pattern. RoadMap #5 bench numbers showed -// storeMeta ≈ 17μs/op and storeEvent ≈ 23μs/op before caching; -// caching + better-sqlite3 drops both to single-digit-μs (see the -// commit-message numbers). -// -// Also: `node:sqlite` is still an experimental Node API (the -// "ExperimentalWarning: SQLite is an experimental feature" line shows -// up on every test run) — better-sqlite3 is the stable, sync, widely- -// deployed wrapper that proposes the same prepared-statement model. - export class MessageStore { private readonly db: DatabaseType; private readonly stmtStoreEvent: Statement; diff --git a/packages/onebot/src/modules/contact-actions.ts b/packages/onebot/src/modules/contact-actions.ts index 805d2941..62e44a67 100644 --- a/packages/onebot/src/modules/contact-actions.ts +++ b/packages/onebot/src/modules/contact-actions.ts @@ -1,5 +1,5 @@ import type { BridgeInterface } from '@snowluma/core/bridge-interface'; -import type { IdentityService } from '@snowluma/bridge/identity-service'; +import type { IdentityService } from '@snowluma/protocol/identity-service'; import type { OneBotInstanceContext } from '../instance-context'; import type { JsonObject } from '../types'; @@ -9,13 +9,11 @@ export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nick return { userId, nickname }; } -// Keep refreshes scoped. A broad "refresh all members in all groups" call can -// turn one OneBot request into N OIDB calls, which is risky for busy clients. async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: number): Promise { try { await bridge.apis.contacts.fetchGroupMemberList(groupId); } catch { - // Use cached data. + // 需要打log以便排查问题,但不应当让调用者感知到这个失败。 } } @@ -23,15 +21,15 @@ export async function getFriendList(bridge: BridgeInterface): Promise ({ - user_id: f.uin as any, - nickname: f.nickname as any, - remark: f.remark as any, + user_id: f.uin, + nickname: f.nickname, + remark: f.remark, })); } catch { return bridge.identity.friends.map(f => ({ - user_id: f.uin as any, - nickname: f.nickname as any, - remark: f.remark as any, + user_id: f.uin, + nickname: f.nickname, + remark: f.remark, })); } } @@ -48,10 +46,10 @@ export async function getGroupList( // Use cached data. } return bridge.identity.groups.map(g => ({ - group_id: g.groupId as any, - group_name: g.groupName as any, - member_count: g.memberCount as any, - max_member_count: g.memberMax as any, + group_id: g.groupId, + group_name: g.groupName, + member_count: g.memberCount, + max_member_count: g.memberMax, })); } @@ -70,10 +68,10 @@ export async function getGroupInfo( const g = bridge.identity.findGroup(groupId); if (!g) return null; return { - group_id: g.groupId as any, - group_name: g.groupName as any, - member_count: g.memberCount as any, - max_member_count: g.memberMax as any, + group_id: g.groupId, + group_name: g.groupName, + member_count: g.memberCount, + max_member_count: g.memberMax, }; } @@ -117,27 +115,27 @@ export async function getGroupFiles( const result = await bridge.apis.groupFile.list(groupId, folderId ?? '/'); return { files: result.files.map((file) => ({ - group_id: groupId as any, - file_id: file.fileId as any, - file_name: file.fileName as any, - busid: file.busId as any, - file_size: file.fileSize as any, - upload_time: file.uploadTime as any, - dead_time: file.deadTime as any, - modify_time: file.modifyTime as any, - download_times: file.downloadTimes as any, - uploader: file.uploader as any, - uploader_name: file.uploaderName as any, - } as JsonObject)) as any, + group_id: groupId, + file_id: file.fileId, + file_name: file.fileName, + busid: file.busId, + file_size: file.fileSize, + upload_time: file.uploadTime, + dead_time: file.deadTime, + modify_time: file.modifyTime, + download_times: file.downloadTimes, + uploader: file.uploader, + uploader_name: file.uploaderName, + } as JsonObject)), folders: result.folders.map((folder) => ({ - group_id: groupId as any, - folder_id: folder.folderId as any, - folder_name: folder.folderName as any, - create_time: folder.createTime as any, - creator: folder.creator as any, - create_name: folder.creatorName as any, - total_file_count: folder.totalFileCount as any, - } as JsonObject)) as any, + group_id: groupId, + folder_id: folder.folderId, + folder_name: folder.folderName, + create_time: folder.createTime, + creator: folder.creator, + create_name: folder.creatorName, + total_file_count: folder.totalFileCount, + } as JsonObject)), }; } @@ -148,19 +146,23 @@ export async function getStrangerInfo( try { const p = await bridge.apis.contacts.fetchUserProfile(userId); return { - user_id: p.uin as any, - nickname: p.nickname as any, - sex: p.sex as any, - age: p.age as any, + user_id: p.uin, + nickname: p.nickname, + sex: p.sex, + age: p.age, + qq_level: p.level, + level: p.level, }; } catch { const p = bridge.identity.findUserProfile(userId); if (!p) return null; return { - user_id: p.uin as any, - nickname: p.nickname as any, - sex: p.sex as any, - age: p.age as any, + user_id: p.uin, + nickname: p.nickname, + sex: p.sex, + age: p.age, + qq_level: p.level, + level: p.level, }; } } @@ -176,7 +178,7 @@ export async function getGroupSystemMessages(bridge: BridgeInterface): Promise { const cached = mediaStore.findRecord(file); if (!cached) return null; - - // Re-resolve via OIDB if the cached URL is missing or empty. - // Mirrors NapCat's getPttUrl path: GetGroupPttUrl / GetPttUrl by fileUuid. let url = cached.url; if (!url && cached.mediaNode) { try { @@ -43,7 +40,6 @@ export async function getRecordInfo( log.warn('get_record url refetch failed: %s', err instanceof Error ? err.message : String(err)); } } - return { file: url || cached.file, url: url || '', diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index 4238e9ca..8b80c5e8 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -1,14 +1,14 @@ -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; -import type { ForwardNodePayload, MessageElement } from '@snowluma/bridge/events'; import { createLogger } from '@snowluma/common/logger'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events'; import type { MessageSendResult } from '../api-handler'; import { elementsToOneBotSegments } from '../event-converter'; -import { segmentsToRawMessage } from '../event-converter/utils'; +import { segmentsToRawMessage } from '../helper/cq'; +import type { OneBotInstanceContext } from '../instance-context'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id'; import { parseMessage } from '../message-parser'; import type { MessageStore } from '../message-store'; import type { JsonArray, JsonObject, JsonValue, MessageMeta } from '../types'; -import type { OneBotInstanceContext } from '../instance-context'; const log = createLogger('OneBot'); diff --git a/packages/onebot/src/modules/request-actions.ts b/packages/onebot/src/modules/request-actions.ts index 5d15c8c9..29954e2b 100644 --- a/packages/onebot/src/modules/request-actions.ts +++ b/packages/onebot/src/modules/request-actions.ts @@ -6,7 +6,7 @@ export async function handleGroupAddRequest( approve: boolean, reason: string, ): Promise { - // flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter) + // flag format: "add:groupId:uid" or "invite:groupId:uid" const parts = flag.split(':'); if (parts.length < 3) throw new Error('invalid group request flag'); const requestType = parts[0]; @@ -26,7 +26,6 @@ export async function handleGroupAddRequest( if (!matching) { throw new Error('matching group request not found'); } - await bridge.apis.groupAdmin.setAddRequest( groupId, matching.sequence, diff --git a/packages/onebot/src/network/adapter.ts b/packages/onebot/src/network/adapter.ts index 7e194d53..8162707e 100644 --- a/packages/onebot/src/network/adapter.ts +++ b/packages/onebot/src/network/adapter.ts @@ -3,24 +3,16 @@ import type { DispatchPayload } from '../event-filter'; import type { JsonObject, NetworkBase } from '../types'; export interface NetworkAdapterContext { - /** Self UIN as string — written into outbound headers. */ uin: string; - /** Shared API dispatcher used by request/response style adapters. */ api: ApiHandler; - /** Build a lifecycle event payload (connect/enable/disable). */ buildLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject; - /** Build a heartbeat event payload. */ buildHeartbeatEvent(): JsonObject; } export enum NetworkReloadType { - /** Configuration unchanged or only soft fields updated. */ Normal = 0, - /** Underlying socket/listener restarted in place. */ Reopened = 1, - /** Was running, now closed. */ Closed = 2, - /** Was idle, now opened. */ Opened = 3, } @@ -32,25 +24,17 @@ export abstract class IOneBotNetworkAdapter { constructor(name: string, config: C, ctx: NetworkAdapterContext) { this.name = name; - // Defensive copy so reload diffs never mutate the caller's object. this.config = structuredClone(config); this.ctx = ctx; } - /** Whether the adapter is currently accepting/relaying events. */ get isActive(): boolean { return this.isEnabled; } - /** Snapshot of the active config (read-only). */ get currentConfig(): Readonly { return this.config; } abstract open(): void | Promise; abstract close(): void | Promise; abstract reload(config: C): NetworkReloadType | Promise; - /** - * Receive one fully-shaped OneBot event for forwarding. Adapters that - * don't push events (e.g. HTTP request-response servers) override with a - * no-op. - */ abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise; } diff --git a/packages/onebot/src/network/http-server-adapter.ts b/packages/onebot/src/network/http-server-adapter.ts index 565a07b1..0ef8084b 100644 --- a/packages/onebot/src/network/http-server-adapter.ts +++ b/packages/onebot/src/network/http-server-adapter.ts @@ -1,10 +1,10 @@ +import { createLogger, type Logger } from '@snowluma/common/logger'; import { createServer, type IncomingMessage, type Server, type ServerResponse, } from 'http'; -import { createLogger, type Logger } from '@snowluma/common/logger'; import type { DispatchPayload } from '../event-filter'; import type { HttpServerNetwork, JsonObject, JsonValue } from '../types'; import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; @@ -23,8 +23,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter } override get isActive(): boolean { - // HTTP server never receives events — `isActive` purely tracks the - // bound listener so the network manager can skip dispatch cleanly. return this.isEnabled; } @@ -69,7 +67,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter return NetworkReloadType.Normal; } - // HTTP server only acts on inbound requests; it doesn't push events. onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ } private startServer(): void { @@ -95,12 +92,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter } private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise { - // Read `path` + `accessToken` fresh from `this.config` on every - // request so config hot-reloads (`reload()` overwrites `this.config` - // in place) take effect on the very next request without - // re-binding the listener. Matches the ws-server / http-post / - // ws-client adapters, which all read `this.config.accessToken` - // inline at the point of use. const expectedPath = normalizePath(this.config.path ?? '/'); const accessToken = this.config.accessToken ?? ''; const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1'); @@ -223,15 +214,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter } function bindingSignature(net: HttpServerNetwork): string { - // `accessToken` deliberately omitted: it's read per-request from - // `this.config`, so a token change doesn't need to re-bind the - // listener. Including it here would cause a `close()` + `listen()` - // round trip on every token edit — a needless port-rebind that, on - // some hosts, races with the OS releasing the port and lands the - // server in a half-broken state where the old token still - // authenticates because the EADDRINUSE-failing new server never - // replaced the old one. `host`/`port`/`path` still gate a restart - // because Node's HTTP `Server.listen()` binds the socket on those. return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`; } diff --git a/packages/onebot/src/network/network-manager.ts b/packages/onebot/src/network/network-manager.ts index 5100d86b..8edab3c5 100644 --- a/packages/onebot/src/network/network-manager.ts +++ b/packages/onebot/src/network/network-manager.ts @@ -13,10 +13,11 @@ export class OneBotNetworkManager { register(adapter: IOneBotNetworkAdapter): void { const existing = this.adapters.get(adapter.name); if (existing) { - // Replacing an adapter under the same name — close the previous one - // before storing the new instance to keep ports/sockets clean. log.info('replacing adapter [%s]', adapter.name); - void Promise.resolve(existing.close()).catch(() => { /* best-effort */ }); + Promise.resolve(existing.close()).catch(() => { + /* best-effort */ + // 应该该打个日志以便排查问题,但不应当让调用者感知到这个失败。 + }); } this.adapters.set(adapter.name, adapter as AnyAdapter); } @@ -68,14 +69,6 @@ export class OneBotNetworkManager { } } - /** - * Dispatch one canonical OneBot event to every active adapter in parallel. - * The dispatch payload is built once so each adapter pays only the cost - * of picking the right pre-serialized variant. - * - * Errors thrown inside an adapter are isolated — one bad adapter never - * blocks the others. - */ async emitEvent(event: JsonObject): Promise { if (!this.hasActiveAdapters()) return; const payload = buildDispatchPayload(event); diff --git a/packages/onebot/src/network/utils.ts b/packages/onebot/src/network/utils.ts index 197c53c8..c65c7c87 100644 --- a/packages/onebot/src/network/utils.ts +++ b/packages/onebot/src/network/utils.ts @@ -1,7 +1,6 @@ import type { WebSocket } from '@snowluma/websocket'; import type { IncomingMessage } from 'http'; -/** Validate a request's bearer token / `?access_token=` query against the configured token. */ export function isAuthorized(request: IncomingMessage, token: string): boolean { if (!token) return true; const auth = request.headers.authorization ?? ''; @@ -25,7 +24,6 @@ export function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBuffer return ''; } -/** Best-effort send: drops payload if the socket isn't OPEN, reports send errors. */ export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void { if (socket.readyState !== 1 /* WebSocket.OPEN */) return; socket.send(payload, (error?: Error | null) => { @@ -33,20 +31,17 @@ export function safeSend(socket: WebSocket, payload: string, onError?: (err: Err }); } -/** Best-effort close, treats already-closed sockets as a no-op. */ export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void { if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return; socket.close(code, reason); } -/** Normalize an HTTP/WS path to a comparable form (strip trailing slash, default to "/"). */ export function normalizePath(pathValue: string | undefined): string { const path = (pathValue ?? '/').trim() || '/'; if (path === '/') return '/'; return path.endsWith('/') ? path.slice(0, -1) : path; } -/** Parse the `pathname` from a (potentially relative) WebSocket request URL. */ export function parseRequestPath(urlValue: string): string { try { return new URL(urlValue, 'ws://127.0.0.1').pathname; diff --git a/packages/onebot/src/reaction-store.ts b/packages/onebot/src/reaction-store.ts new file mode 100644 index 00000000..c1e05c59 --- /dev/null +++ b/packages/onebot/src/reaction-store.ts @@ -0,0 +1,142 @@ +import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; +import fs from 'fs'; +import path from 'path'; + +export class ReactionStore { + private readonly db: DatabaseType; + private readonly stmtUpsert: Statement; + private readonly stmtRemove: Statement; + private readonly stmtList: Statement; + private readonly stmtCount: Statement; + private readonly stmtCountByEmoji: Statement; + + constructor(dbPath: string) { + const dir = path.dirname(dbPath); + fs.mkdirSync(dir, { recursive: true }); + this.db = new Database(dbPath); + this.db.pragma('journal_mode = WAL'); + this.db.pragma('synchronous = NORMAL'); + this.initSchema(); + + this.stmtUpsert = this.db.prepare( + `INSERT INTO reactions + (group_id, msg_seq, emoji_id, emoji_type, operator_uin, operator_uid, set_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(group_id, msg_seq, emoji_id, operator_uin) DO UPDATE SET + emoji_type = excluded.emoji_type, + operator_uid = excluded.operator_uid, + set_at = excluded.set_at`, + ); + + this.stmtRemove = this.db.prepare( + `DELETE FROM reactions + WHERE group_id = ? AND msg_seq = ? AND emoji_id = ? AND operator_uin = ?`, + ); + + this.stmtList = this.db.prepare( + `SELECT operator_uin, operator_uid, set_at + FROM reactions + WHERE group_id = ? AND msg_seq = ? AND emoji_id = ? + ORDER BY set_at ASC + LIMIT ? OFFSET ?`, + ); + + this.stmtCount = this.db.prepare( + `SELECT COUNT(*) AS n FROM reactions + WHERE group_id = ? AND msg_seq = ? AND emoji_id = ?`, + ); + + this.stmtCountByEmoji = this.db.prepare( + `SELECT emoji_id, emoji_type, COUNT(*) AS n, MAX(set_at) AS last_at + FROM reactions + WHERE group_id = ? AND msg_seq = ? + GROUP BY emoji_id`, + ); + } + + private initSchema(): void { + this.db.exec(` + CREATE TABLE IF NOT EXISTS reactions ( + group_id INTEGER NOT NULL, + msg_seq INTEGER NOT NULL, + emoji_id TEXT NOT NULL, + emoji_type INTEGER NOT NULL DEFAULT 1, + operator_uin INTEGER NOT NULL, + operator_uid TEXT NOT NULL DEFAULT '', + set_at INTEGER NOT NULL, + PRIMARY KEY (group_id, msg_seq, emoji_id, operator_uin) + ); + CREATE INDEX IF NOT EXISTS idx_reactions_msg_emoji + ON reactions (group_id, msg_seq, emoji_id, set_at); + `); + } + + recordAdd( + groupId: number, + msgSeq: number, + emojiId: string, + emojiType: number, + operatorUin: number, + operatorUid: string, + setAt: number, + ): void { + if (!groupId || !msgSeq || !emojiId || !operatorUin) return; + this.stmtUpsert.run(groupId, msgSeq, emojiId, emojiType, operatorUin, operatorUid, setAt); + } + + recordRemove( + groupId: number, + msgSeq: number, + emojiId: string, + operatorUin: number, + ): void { + if (!groupId || !msgSeq || !emojiId || !operatorUin) return; + this.stmtRemove.run(groupId, msgSeq, emojiId, operatorUin); + } + + listUsers( + groupId: number, + msgSeq: number, + emojiId: string, + limit = 20, + offset = 0, + ): Array<{ operatorUin: number; operatorUid: string; setAt: number }> { + const rows = this.stmtList.all( + groupId, + msgSeq, + emojiId, + Math.max(1, Math.min(limit, 500)), + Math.max(0, offset), + ) as Array<{ operator_uin: number; operator_uid: string; set_at: number }>; + return rows.map(r => ({ + operatorUin: r.operator_uin, + operatorUid: r.operator_uid, + setAt: r.set_at, + })); + } + + countUsers(groupId: number, msgSeq: number, emojiId: string): number { + const row = this.stmtCount.get(groupId, msgSeq, emojiId) as { n: number } | undefined; + return row?.n ?? 0; + } + + /** Summary of all cached reactions on a message, grouped by emoji. */ + summarizeMessage( + groupId: number, + msgSeq: number, + ): Array<{ emojiId: string; emojiType: number; count: number; lastSetAt: number }> { + const rows = this.stmtCountByEmoji.all(groupId, msgSeq) as Array<{ + emoji_id: string; emoji_type: number; n: number; last_at: number; + }>; + return rows.map(r => ({ + emojiId: r.emoji_id, + emojiType: r.emoji_type, + count: r.n, + lastSetAt: r.last_at, + })); + } + + close(): void { + this.db.close(); + } +} diff --git a/packages/onebot/src/types.ts b/packages/onebot/src/types.ts index adf3bfca..4235978b 100644 --- a/packages/onebot/src/types.ts +++ b/packages/onebot/src/types.ts @@ -1,9 +1,5 @@ -// Plain JSON types now live in @snowluma/common/json so @snowluma/bridge -// (event-format / receive parsers) can talk about JSON payloads without -// importing OneBot. Re-exported here so the legacy import shape stays -// supported — `import { JsonValue } from '<…>/onebot/types'` keeps working. -export type { JsonPrimitive, JsonValue, JsonObject, JsonArray } from '@snowluma/common/json'; -import type { JsonValue, JsonObject } from '@snowluma/common/json'; + +import type { JsonObject, JsonValue } from '@snowluma/common/json'; export interface ApiResponse { status: 'ok' | 'failed'; @@ -25,14 +21,6 @@ export type MessageFormat = 'array' | 'string'; export type NetworkKind = 'httpServers' | 'httpClients' | 'wsServers' | 'wsClients'; -/** - * Fields shared by every network adapter. `messageFormat` and - * `reportSelfMessage` live on the adapter itself — there is no global default - * fallback; each adapter is fully self-describing. - * - * The `name` is a free-form identifier scoped to the adapter's array; it is - * used for hot-reload bookkeeping and as a label in logs / WebUI. - */ export interface NetworkBase { name: string; /** When `false`, the adapter is configured but inactive. Defaults to `true`. */ @@ -68,10 +56,6 @@ export interface WsClientNetwork extends NetworkBase { reconnectIntervalMs?: number; } -/** - * Network adapters grouped by type. Each adapter is identified by `name` - * within its own array; hot-reload works on a per-(kind, name) basis. - */ export interface OneBotNetworks { httpServers: HttpServerNetwork[]; httpClients: HttpClientNetwork[]; @@ -119,3 +103,5 @@ export function failedResponse(retcode: number, wording: string): ApiResponse { wording, }; } +export type { JsonArray, JsonObject, JsonPrimitive, JsonValue } from '@snowluma/common/json'; + diff --git a/packages/onebot/tests/contact-actions.test.ts b/packages/onebot/tests/contact-actions.test.ts index a6f17597..4864d1ed 100644 --- a/packages/onebot/tests/contact-actions.test.ts +++ b/packages/onebot/tests/contact-actions.test.ts @@ -7,7 +7,7 @@ import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; import type { FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo, -} from '@snowluma/bridge/qq-info'; +} from '@snowluma/protocol/qq-info'; import { getFriendList, getGroupInfo, diff --git a/packages/onebot/tests/event-converter.test.ts b/packages/onebot/tests/event-converter.test.ts index 57a6f55f..5269da2b 100644 --- a/packages/onebot/tests/event-converter.test.ts +++ b/packages/onebot/tests/event-converter.test.ts @@ -16,7 +16,7 @@ import type { MessageElement, QQEventVariant, TempMessage, -} from '@snowluma/bridge/events'; +} from '@snowluma/protocol/events'; const SELF_ID = 10001; const PEER_UIN = 22222; diff --git a/packages/onebot/tests/event-pipeline.test.ts b/packages/onebot/tests/event-pipeline.test.ts index b4f09bec..9b765090 100644 --- a/packages/onebot/tests/event-pipeline.test.ts +++ b/packages/onebot/tests/event-pipeline.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest'; -import { BridgeEventBus } from '@snowluma/bridge/event-bus'; +import { BridgeEventBus } from '@snowluma/protocol/event-bus'; // Wrap convertEvent in a vi.fn that delegates to the real impl by // default, so one test can override it to return null without making @@ -18,7 +18,7 @@ import type { GroupMemberJoin, TempMessage, QQEventVariant, -} from '@snowluma/bridge/events'; +} from '@snowluma/protocol/events'; import type { JsonObject, MessageMeta } from '../src/types'; const SELF_UIN = '10001'; @@ -107,6 +107,14 @@ function makeContext(extra: Partial = {}): { bridge: fakeBridge as never, messageStore: {} as never, mediaStore: {} as never, + reactionStore: { + recordAdd: () => {}, + recordRemove: () => {}, + listUsers: () => [], + countUsers: () => 0, + summarizeMessage: () => [], + close: () => {}, + } as never, converterCtx, config: { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] } } as never, cacheMessageMeta: (id, meta) => { metaCalls.push({ id, meta }); }, diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index 13441786..1bd8f97a 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -7,7 +7,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { ApiHandler, type ApiActionContext } from '../src/api-handler'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; -import type { GroupRequestInfo } from '@snowluma/bridge/qq-info'; +import type { GroupRequestInfo } from '@snowluma/protocol/qq-info'; import type { MessageMeta } from '../src/types'; function fakeMeta(overrides: Partial = {}): MessageMeta { diff --git a/packages/onebot/tests/group-msg-emoji-like.test.ts b/packages/onebot/tests/group-msg-emoji-like.test.ts index e925ea1a..d1b18643 100644 --- a/packages/onebot/tests/group-msg-emoji-like.test.ts +++ b/packages/onebot/tests/group-msg-emoji-like.test.ts @@ -8,13 +8,13 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { protobuf_encode } from '@snowluma/proton'; import type { GroupReactNotify } from '@snowluma/proto-defs/notify'; -import { decodeEvent0x2DC } from '@snowluma/bridge/msg-push/decoders/event-0x2dc'; -import type { MsgPushContext } from '@snowluma/bridge/msg-push/context'; -import { IdentityService } from '@snowluma/bridge/identity-service'; -import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '@snowluma/bridge/events'; +import { decodeEvent0x2DC } from '@snowluma/protocol/msg-push/decoders/event-0x2dc'; +import type { MsgPushContext } from '@snowluma/protocol/msg-push/context'; +import { IdentityService } from '@snowluma/protocol/identity-service'; +import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '@snowluma/protocol/events'; import { convertGroupMsgEmojiLike } from '../src/event-converter/to-notice'; import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../src/message-id'; -import { formatEvent } from '@snowluma/bridge/format'; +import { formatEvent } from '@snowluma/protocol/format'; import { subscribeLogs, type LogEntry } from '@snowluma/common/logger'; const SELF_UIN = '10001'; diff --git a/packages/onebot/tests/media-indexer.test.ts b/packages/onebot/tests/media-indexer.test.ts index 1498c565..544c17ed 100644 --- a/packages/onebot/tests/media-indexer.test.ts +++ b/packages/onebot/tests/media-indexer.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi } from 'vitest'; import { MediaIndexer } from '../src/media-indexer'; -import type { MessageElement } from '@snowluma/bridge/events'; +import type { MessageElement } from '@snowluma/protocol/events'; function makeMediaStore() { return { diff --git a/packages/onebot/tests/media-store.test.ts b/packages/onebot/tests/media-store.test.ts index 29ce7794..bb471fc5 100644 --- a/packages/onebot/tests/media-store.test.ts +++ b/packages/onebot/tests/media-store.test.ts @@ -3,7 +3,7 @@ import fs from 'fs'; import path from 'path'; import { MediaStore } from '../src/media-store'; import { convertEvent, type ConverterContext } from '../src/event-converter'; -import type { GroupMessage, FriendMessage, MessageElement } from '@snowluma/bridge/events'; +import type { GroupMessage, FriendMessage, MessageElement } from '@snowluma/protocol/events'; const SELF_ID = 10001; const PEER_UIN = 22222; diff --git a/packages/onebot/tests/media-url-resolver.test.ts b/packages/onebot/tests/media-url-resolver.test.ts index 8c24da19..99e0544c 100644 --- a/packages/onebot/tests/media-url-resolver.test.ts +++ b/packages/onebot/tests/media-url-resolver.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { MediaUrlResolver } from '../src/media-url-resolver'; -import type { MessageElement } from '@snowluma/bridge/events'; +import type { MessageElement } from '@snowluma/protocol/events'; // Minimal stand-ins for the two collaborators. Each test wires whatever // subset of Bridge methods the element type exercises. diff --git a/packages/onebot/tests/message-parser.test.ts b/packages/onebot/tests/message-parser.test.ts index 6bcd8e45..6d1eccbe 100644 --- a/packages/onebot/tests/message-parser.test.ts +++ b/packages/onebot/tests/message-parser.test.ts @@ -4,7 +4,7 @@ import path from 'path'; import { describe, it, expect, vi } from 'vitest'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { parseMessage } from '../src/message-parser'; -import { buildSendElems } from '@snowluma/bridge/element-builder'; +import { buildSendElems } from '@snowluma/protocol/element-builder'; import type { MentionExtraSend } from '@snowluma/proto-defs/action'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway'; diff --git a/packages/onebot/tests/reaction-store.test.ts b/packages/onebot/tests/reaction-store.test.ts new file mode 100644 index 00000000..45b496e4 --- /dev/null +++ b/packages/onebot/tests/reaction-store.test.ts @@ -0,0 +1,89 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import fs from 'fs'; +import path from 'path'; +import { ReactionStore } from '../src/reaction-store'; + +describe('ReactionStore', () => { + const testDbPath = path.join('data', 'test', 'reactions-test.db'); + let store: ReactionStore; + + beforeEach(() => { + try { fs.unlinkSync(testDbPath); } catch { /* ignore */ } + try { fs.unlinkSync(testDbPath + '-wal'); } catch { /* ignore */ } + try { fs.unlinkSync(testDbPath + '-shm'); } catch { /* ignore */ } + store = new ReactionStore(testDbPath); + }); + + afterEach(() => { + store.close(); + try { fs.unlinkSync(testDbPath); } catch { /* ignore */ } + try { fs.unlinkSync(testDbPath + '-wal'); } catch { /* ignore */ } + try { fs.unlinkSync(testDbPath + '-shm'); } catch { /* ignore */ } + }); + + it('records an add and exposes it via listUsers / countUsers', () => { + store.recordAdd(100, 4001, '124', 1, 12345, 'u_abc', 1700000000); + const users = store.listUsers(100, 4001, '124'); + expect(users).toEqual([{ operatorUin: 12345, operatorUid: 'u_abc', setAt: 1700000000 }]); + expect(store.countUsers(100, 4001, '124')).toBe(1); + }); + + it('upserts on duplicate (group, msg, emoji, operator)', () => { + store.recordAdd(100, 4001, '124', 1, 12345, 'u_old', 1700000000); + store.recordAdd(100, 4001, '124', 1, 12345, 'u_new', 1700000500); + const users = store.listUsers(100, 4001, '124'); + expect(users).toHaveLength(1); + expect(users[0]?.operatorUid).toBe('u_new'); + expect(users[0]?.setAt).toBe(1700000500); + }); + + it('removes the right row only', () => { + store.recordAdd(100, 4001, '124', 1, 12345, 'u_a', 1700000000); + store.recordAdd(100, 4001, '124', 1, 67890, 'u_b', 1700000100); + store.recordRemove(100, 4001, '124', 12345); + const users = store.listUsers(100, 4001, '124'); + expect(users).toHaveLength(1); + expect(users[0]?.operatorUin).toBe(67890); + }); + + it('isolates by group / msg / emoji', () => { + store.recordAdd(100, 4001, '124', 1, 1, 'u', 1); + store.recordAdd(100, 4001, '76', 1, 1, 'u', 1); + store.recordAdd(100, 4002, '124', 1, 1, 'u', 1); + store.recordAdd(200, 4001, '124', 1, 1, 'u', 1); + expect(store.countUsers(100, 4001, '124')).toBe(1); + expect(store.countUsers(100, 4001, '76')).toBe(1); + expect(store.countUsers(100, 4002, '124')).toBe(1); + expect(store.countUsers(200, 4001, '124')).toBe(1); + expect(store.countUsers(100, 4001, '999')).toBe(0); + }); + + it('paginates listUsers via limit + offset, ordering by set_at ASC', () => { + for (let i = 0; i < 5; i++) { + store.recordAdd(100, 4001, '124', 1, 1000 + i, `u_${i}`, 1700000000 + i); + } + const page1 = store.listUsers(100, 4001, '124', 2, 0); + const page2 = store.listUsers(100, 4001, '124', 2, 2); + expect(page1.map(u => u.operatorUin)).toEqual([1000, 1001]); + expect(page2.map(u => u.operatorUin)).toEqual([1002, 1003]); + }); + + it('summarizeMessage groups by emoji_id', () => { + store.recordAdd(100, 4001, '124', 1, 1, 'u1', 1); + store.recordAdd(100, 4001, '124', 1, 2, 'u2', 2); + store.recordAdd(100, 4001, '76', 1, 3, 'u3', 10); + const summary = store.summarizeMessage(100, 4001).sort((a, b) => a.emojiId.localeCompare(b.emojiId)); + expect(summary).toEqual([ + { emojiId: '124', emojiType: 1, count: 2, lastSetAt: 2 }, + { emojiId: '76', emojiType: 1, count: 1, lastSetAt: 10 }, + ]); + }); + + it('ignores incomplete records (no-op instead of throwing)', () => { + store.recordAdd(0, 4001, '124', 1, 1, 'u', 1); // group 0 + store.recordAdd(100, 0, '124', 1, 1, 'u', 1); // msg 0 + store.recordAdd(100, 4001, '', 1, 1, 'u', 1); // empty emoji + store.recordAdd(100, 4001, '124', 1, 0, 'u', 1); // uin 0 + expect(store.countUsers(100, 4001, '124')).toBe(0); + }); +}); diff --git a/packages/onebot/tests/request-actions.test.ts b/packages/onebot/tests/request-actions.test.ts index 2dbcaa7b..e636503c 100644 --- a/packages/onebot/tests/request-actions.test.ts +++ b/packages/onebot/tests/request-actions.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest'; import { handleGroupAddRequest } from '../src/modules/request-actions'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; -import type { GroupRequestInfo } from '@snowluma/bridge/qq-info'; +import type { GroupRequestInfo } from '@snowluma/protocol/qq-info'; // See `contact-actions.test.ts` for the auto-promotion rationale. const APIS_ROUTING: Record = { diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 40457854..31e4eca2 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/proto-defs", - "version": "1.9.1", + "version": "1.9.2", "private": true, "type": "module", "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).", diff --git a/packages/proto-defs/src/oidb-actions/base.ts b/packages/proto-defs/src/oidb-actions/base.ts index 820da07b..560c3070 100644 --- a/packages/proto-defs/src/oidb-actions/base.ts +++ b/packages/proto-defs/src/oidb-actions/base.ts @@ -114,9 +114,18 @@ export interface OidbSpecialTitle { groupUin?: pb<1, uint_32>; body?: pb<2, OidbSpecialTitleBody>; } +// 0x7E5_104 (FriendLike) request body. Field numbers 11/12/13 (NOT +// 1/2/3) — the server reads `targetUid` from tag 11 and rejects with +// "被点赞 QQ 号非法" if it lands on the wrong tag. `sourceId = 71` is +// the fixed marker for the "profile card" 点赞 entry point. +// Mirrors Lagrange.Core's `OidbSvcTrpcTcp0x7E5_104`: +// dev/Lagrange.Core/.../Service/Oidb/Request/OidbSvcTrpcTcp0x7E5_104.cs:14-18 +// and NapCat's UserApi.like (`setBuddyProfileLike` → sourceId 71): +// dev/NapCatQQ/packages/napcat-core/apis/user.ts:63-70 export interface OidbLike { - targetUin?: pb<1, uint_32>; - count?: pb<2, uint_32>; + targetUid?: pb<11, string>; + sourceId?: pb<12, uint_32>; + count?: pb<13, uint_32>; } export interface OidbGroupRequestList { count?: pb<1, uint_32>; @@ -129,6 +138,15 @@ export interface OidbUserInfoRequest { uin?: pb<1, uint_32>; keys?: pb_repeated<3, OidbUserInfoKey>; } +// UID-form variant of OIDB 0xFE1_2 — same wire shape but field 1 is +// the uid string. Used by the stranger lookup path (group join +// requests / friend requests) because the push only carries a uid. +// Matches Lagrange's `OidbSvcTrpcTcp0xFE1_2Uid`: +// dev/Lagrange.Core/.../OidbSvcTrpcTcp0xFE1_2.cs:9-16 +export interface OidbUserInfoByUidRequest { + uid?: pb<1, string>; + keys?: pb_repeated<3, OidbUserInfoKey>; +} export interface OidbTwoNumber { number1?: pb<1, uint_32>; number2?: pb<2, uint_32>; @@ -512,11 +530,21 @@ export interface FaceroamOpResp { field3?: pb<3, uint_32>; item?: pb<4, FaceroamOpRespItem>; } +// 0x9083_1: fetch emoji-like user list. Field numbers must mirror the +// sibling 0x9082 reaction Req (OidbGroupReaction): field 4 = emoji_id +// (string), field 5 = emoji_type (uint). The pre-fix definition had +// these two swapped, which silently dropped both fields on the server +// side (wire type mismatch → protobuf decoder discards) and made every +// call return an empty list with no error. Cross-checked against +// Lagrange.Core V2 `Internal/Packets/Service/SetGroupReaction.cs`. export interface Oidb0x9083Req { groupId?: pb<2, uint_64>; - sequence?: pb<3, uint_32>; - emojiType?: pb<4, uint_32>; - emojiId?: pb<5, string>; + // ulong on LagrangeV2's `SetGroupReactionRequest`. wire-compatible + // with uint_32 for small seq values (which is what message sequences + // actually are today), but match the spec to be safe — costs nothing. + sequence?: pb<3, uint_64>; + emojiId?: pb<4, string>; + emojiType?: pb<5, uint_32>; cookie?: pb<6, bytes>; field7?: pb<7, uint_32>; count?: pb<8, uint_32>; @@ -527,13 +555,57 @@ export interface Oidb0x9083RespUserInfo { field3?: pb<3, uint_32>; } export interface Oidb0x9083RespInner { - userInfo?: pb<1, Oidb0x9083RespUserInfo>; + // The server returns one entry per liker — must be repeated. A single + // field collapses N wire entries into "last writer wins", so groups + // with multiple likers used to come back as a single user (or empty + // if the wire layout shifted). + userInfo?: pb_repeated<1, Oidb0x9083RespUserInfo>; field4?: pb<4, uint_32>; } export interface Oidb0x9083Resp { inner?: pb<4, Oidb0x9083RespInner>; cookie?: pb<5, bytes>; } + +// 0x9084_1: fetch reaction summary on a message. Returns one entry per +// emoji used + an "available reactions" catalog tail. Schema decoded +// from production wire dump: +// { 08 0A ← top-level field 1 (uint, meaning unclear: maybe +// "total reactions on msg" or a flag — empirically +// constant across messages) +// 12 0E 08 10 18 01 22 02 "76" ← entry 1 +// 12 07 18 01 22 03 "124" ← catalog +// ... } +// Used entries always carry field 1 (timestamp) and field 2 (count); +// catalog entries omit both. +export interface Oidb0x9084Req { + groupId?: pb<2, uint_64>; + sequence?: pb<3, uint_64>; + // Server returns the full per-emoji summary regardless of these, + // but we send them to mirror the working 0x9083_1 request shape. + emojiId?: pb<4, string>; + emojiType?: pb<5, uint_32>; + cookie?: pb<6, bytes>; + count?: pb<8, uint_32>; + field12?: pb<12, uint_32>; +} + +export interface Oidb0x9084RespEntry { + /** Unix epoch (seconds) of the last reaction. Omitted for catalog + * entries that have never been reacted with on this message. */ + lastReactionTime?: pb<1, uint_64>; + /** Number of reactors. Omitted for catalog entries. */ + count?: pb<2, uint_32>; + /** Emoji type. 1 for QQ-face / short id, 2 for unicode codepoint. */ + emojiType?: pb<3, uint_32>; + emojiId?: pb<4, string>; +} + +export interface Oidb0x9084Resp { + /** Top-level varint, observed value `10` constant; semantics unknown. */ + field1?: pb<1, uint_32>; + entries?: pb_repeated<2, Oidb0x9084RespEntry>; +} export interface Oidb0x8a0Req { groupId?: pb<1, uint_64>; targetUids?: pb_repeated<3, string>; diff --git a/packages/proto-defs/src/oidb.ts b/packages/proto-defs/src/oidb.ts index 9747a903..b636b441 100644 --- a/packages/proto-defs/src/oidb.ts +++ b/packages/proto-defs/src/oidb.ts @@ -23,6 +23,12 @@ export interface OidbBaseMeta { reserved?: pb<12, int_32>; } +/** Placeholder body for OIDB cmds whose successful response carries no + * payload (only the envelope's errorCode matters). Used as the + * TResp parameter in OidbCallSpec for fire-and-forget cmds — proton + * needs a real message interface here, not `void` or `never`. */ +export interface OidbEmpty {} + // Oidb.0xFD4_1 Friend list export interface OidbFriendProperty { code?: pb<1, uint_32>; diff --git a/packages/bridge/bench/recv.bench.ts b/packages/protocol/bench/recv.bench.ts similarity index 99% rename from packages/bridge/bench/recv.bench.ts rename to packages/protocol/bench/recv.bench.ts index 1ff63838..4e066881 100644 --- a/packages/bridge/bench/recv.bench.ts +++ b/packages/protocol/bench/recv.bench.ts @@ -7,7 +7,7 @@ // decode + decoder + handleSideEffects (identity-service SQLite // writes) + event emit through BridgeEventBus. // -// Run via: pnpm -F @snowluma/bridge bench +// Run via: pnpm -F @snowluma/protocol bench // // Output is `tinybench` ops/sec — vitest's built-in `bench()` is just a // thin wrapper. Run before AND after a perf commit; the delta is what diff --git a/packages/protocol/package.json b/packages/protocol/package.json new file mode 100644 index 00000000..c33f0aa3 --- /dev/null +++ b/packages/protocol/package.json @@ -0,0 +1,380 @@ +{ + "name": "@snowluma/protocol", + "version": "1.9.2", + "private": true, + "type": "module", + "description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/'` collapses to `import { … } from '@snowluma/protocol/'`.", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./events": { + "types": "./src/events.ts", + "default": "./src/events.ts" + }, + "./event-bus": { + "types": "./src/event-bus.ts", + "default": "./src/event-bus.ts" + }, + "./identity-service": { + "types": "./src/identity-service.ts", + "default": "./src/identity-service.ts" + }, + "./packet-pipeline": { + "types": "./src/packet-pipeline.ts", + "default": "./src/packet-pipeline.ts" + }, + "./element-builder": { + "types": "./src/element-builder.ts", + "default": "./src/element-builder.ts" + }, + "./bridge-oidb": { + "types": "./src/bridge-oidb.ts", + "default": "./src/bridge-oidb.ts" + }, + "./oidb-service": { + "types": "./src/oidb-service.ts", + "default": "./src/oidb-service.ts" + }, + "./oidb-services/reaction/set-reaction": { + "types": "./src/oidb-services/reaction/set-reaction.ts", + "default": "./src/oidb-services/reaction/set-reaction.ts" + }, + "./oidb-services/reaction/fetch-reaction-summary": { + "types": "./src/oidb-services/reaction/fetch-reaction-summary.ts", + "default": "./src/oidb-services/reaction/fetch-reaction-summary.ts" + }, + "./oidb-services/reaction/get-emoji-likes": { + "types": "./src/oidb-services/reaction/get-emoji-likes.ts", + "default": "./src/oidb-services/reaction/get-emoji-likes.ts" + }, + "./oidb-services/interaction/send-poke": { + "types": "./src/oidb-services/interaction/send-poke.ts", + "default": "./src/oidb-services/interaction/send-poke.ts" + }, + "./oidb-services/interaction/send-like": { + "types": "./src/oidb-services/interaction/send-like.ts", + "default": "./src/oidb-services/interaction/send-like.ts" + }, + "./oidb-services/interaction/set-essence": { + "types": "./src/oidb-services/interaction/set-essence.ts", + "default": "./src/oidb-services/interaction/set-essence.ts" + }, + "./oidb-services/profile/set-profile": { + "types": "./src/oidb-services/profile/set-profile.ts", + "default": "./src/oidb-services/profile/set-profile.ts" + }, + "./oidb-services/profile/set-self-long-nick": { + "types": "./src/oidb-services/profile/set-self-long-nick.ts", + "default": "./src/oidb-services/profile/set-self-long-nick.ts" + }, + "./oidb-services/profile/set-input-status": { + "types": "./src/oidb-services/profile/set-input-status.ts", + "default": "./src/oidb-services/profile/set-input-status.ts" + }, + "./oidb-services/profile/get-like": { + "types": "./src/oidb-services/profile/get-like.ts", + "default": "./src/oidb-services/profile/get-like.ts" + }, + "./oidb-services/profile/get-unidirectional-friend-list": { + "types": "./src/oidb-services/profile/get-unidirectional-friend-list.ts", + "default": "./src/oidb-services/profile/get-unidirectional-friend-list.ts" + }, + "./oidb-services/friend/handle-friend-request": { + "types": "./src/oidb-services/friend/handle-friend-request.ts", + "default": "./src/oidb-services/friend/handle-friend-request.ts" + }, + "./oidb-services/friend/delete-friend": { + "types": "./src/oidb-services/friend/delete-friend.ts", + "default": "./src/oidb-services/friend/delete-friend.ts" + }, + "./oidb-services/friend/set-friend-remark": { + "types": "./src/oidb-services/friend/set-friend-remark.ts", + "default": "./src/oidb-services/friend/set-friend-remark.ts" + }, + "./oidb-services/misc/translate-en-to-zh": { + "types": "./src/oidb-services/misc/translate-en-to-zh.ts", + "default": "./src/oidb-services/misc/translate-en-to-zh.ts" + }, + "./oidb-services/misc/click-inline-keyboard-button": { + "types": "./src/oidb-services/misc/click-inline-keyboard-button.ts", + "default": "./src/oidb-services/misc/click-inline-keyboard-button.ts" + }, + "./oidb-services/misc/send-group-sign": { + "types": "./src/oidb-services/misc/send-group-sign.ts", + "default": "./src/oidb-services/misc/send-group-sign.ts" + }, + "./oidb-services/web/force-fetch-client-key": { + "types": "./src/oidb-services/web/force-fetch-client-key.ts", + "default": "./src/oidb-services/web/force-fetch-client-key.ts" + }, + "./oidb-services/web/get-pskey": { + "types": "./src/oidb-services/web/get-pskey.ts", + "default": "./src/oidb-services/web/get-pskey.ts" + }, + "./oidb-services/extras/group-todo": { + "types": "./src/oidb-services/extras/group-todo.ts", + "default": "./src/oidb-services/extras/group-todo.ts" + }, + "./oidb-services/extras/get-stranger-status": { + "types": "./src/oidb-services/extras/get-stranger-status.ts", + "default": "./src/oidb-services/extras/get-stranger-status.ts" + }, + "./oidb-services/extras/fetch-ai-voice-list": { + "types": "./src/oidb-services/extras/fetch-ai-voice-list.ts", + "default": "./src/oidb-services/extras/fetch-ai-voice-list.ts" + }, + "./oidb-services/extras/fetch-ai-voice": { + "types": "./src/oidb-services/extras/fetch-ai-voice.ts", + "default": "./src/oidb-services/extras/fetch-ai-voice.ts" + }, + "./oidb-services/contacts/fetch-friend-list-page": { + "types": "./src/oidb-services/contacts/fetch-friend-list-page.ts", + "default": "./src/oidb-services/contacts/fetch-friend-list-page.ts" + }, + "./oidb-services/contacts/fetch-group-list": { + "types": "./src/oidb-services/contacts/fetch-group-list.ts", + "default": "./src/oidb-services/contacts/fetch-group-list.ts" + }, + "./oidb-services/contacts/fetch-group-member-list-page": { + "types": "./src/oidb-services/contacts/fetch-group-member-list-page.ts", + "default": "./src/oidb-services/contacts/fetch-group-member-list-page.ts" + }, + "./oidb-services/contacts/fetch-user-profile": { + "types": "./src/oidb-services/contacts/fetch-user-profile.ts", + "default": "./src/oidb-services/contacts/fetch-user-profile.ts" + }, + "./oidb-services/contacts/fetch-user-profile-by-uid": { + "types": "./src/oidb-services/contacts/fetch-user-profile-by-uid.ts", + "default": "./src/oidb-services/contacts/fetch-user-profile-by-uid.ts" + }, + "./oidb-services/contacts/fetch-group-requests": { + "types": "./src/oidb-services/contacts/fetch-group-requests.ts", + "default": "./src/oidb-services/contacts/fetch-group-requests.ts" + }, + "./oidb-services/contacts/fetch-download-rkeys": { + "types": "./src/oidb-services/contacts/fetch-download-rkeys.ts", + "default": "./src/oidb-services/contacts/fetch-download-rkeys.ts" + }, + "./oidb-services/group-admin/mute-member": { + "types": "./src/oidb-services/group-admin/mute-member.ts", + "default": "./src/oidb-services/group-admin/mute-member.ts" + }, + "./oidb-services/group-admin/mute-all": { + "types": "./src/oidb-services/group-admin/mute-all.ts", + "default": "./src/oidb-services/group-admin/mute-all.ts" + }, + "./oidb-services/group-admin/set-add-option": { + "types": "./src/oidb-services/group-admin/set-add-option.ts", + "default": "./src/oidb-services/group-admin/set-add-option.ts" + }, + "./oidb-services/group-admin/set-search": { + "types": "./src/oidb-services/group-admin/set-search.ts", + "default": "./src/oidb-services/group-admin/set-search.ts" + }, + "./oidb-services/group-admin/set-add-request": { + "types": "./src/oidb-services/group-admin/set-add-request.ts", + "default": "./src/oidb-services/group-admin/set-add-request.ts" + }, + "./oidb-services/group-admin/kick-member": { + "types": "./src/oidb-services/group-admin/kick-member.ts", + "default": "./src/oidb-services/group-admin/kick-member.ts" + }, + "./oidb-services/group-admin/kick-members": { + "types": "./src/oidb-services/group-admin/kick-members.ts", + "default": "./src/oidb-services/group-admin/kick-members.ts" + }, + "./oidb-services/group-admin/leave-group": { + "types": "./src/oidb-services/group-admin/leave-group.ts", + "default": "./src/oidb-services/group-admin/leave-group.ts" + }, + "./oidb-services/group-admin/set-admin": { + "types": "./src/oidb-services/group-admin/set-admin.ts", + "default": "./src/oidb-services/group-admin/set-admin.ts" + }, + "./oidb-services/group-admin/set-member-card": { + "types": "./src/oidb-services/group-admin/set-member-card.ts", + "default": "./src/oidb-services/group-admin/set-member-card.ts" + }, + "./oidb-services/group-admin/set-group-name": { + "types": "./src/oidb-services/group-admin/set-group-name.ts", + "default": "./src/oidb-services/group-admin/set-group-name.ts" + }, + "./oidb-services/group-admin/set-special-title": { + "types": "./src/oidb-services/group-admin/set-special-title.ts", + "default": "./src/oidb-services/group-admin/set-special-title.ts" + }, + "./oidb-services/group-admin/set-group-remark": { + "types": "./src/oidb-services/group-admin/set-group-remark.ts", + "default": "./src/oidb-services/group-admin/set-group-remark.ts" + }, + "./oidb-services/group-admin/get-at-all-remain": { + "types": "./src/oidb-services/group-admin/get-at-all-remain.ts", + "default": "./src/oidb-services/group-admin/get-at-all-remain.ts" + }, + "./oidb-services/shared": { + "types": "./src/oidb-services/shared.ts", + "default": "./src/oidb-services/shared.ts" + }, + "./oidb-services/group-file/publish-group-file": { + "types": "./src/oidb-services/group-file/publish-group-file.ts", + "default": "./src/oidb-services/group-file/publish-group-file.ts" + }, + "./oidb-services/group-file/get-group-file-count": { + "types": "./src/oidb-services/group-file/get-group-file-count.ts", + "default": "./src/oidb-services/group-file/get-group-file-count.ts" + }, + "./oidb-services/group-file/upload-group-file-request": { + "types": "./src/oidb-services/group-file/upload-group-file-request.ts", + "default": "./src/oidb-services/group-file/upload-group-file-request.ts" + }, + "./oidb-services/group-file/upload-private-file-request": { + "types": "./src/oidb-services/group-file/upload-private-file-request.ts", + "default": "./src/oidb-services/group-file/upload-private-file-request.ts" + }, + "./oidb-services/group-file/list-group-files-page": { + "types": "./src/oidb-services/group-file/list-group-files-page.ts", + "default": "./src/oidb-services/group-file/list-group-files-page.ts" + }, + "./oidb-services/group-file/get-group-file-url": { + "types": "./src/oidb-services/group-file/get-group-file-url.ts", + "default": "./src/oidb-services/group-file/get-group-file-url.ts" + }, + "./oidb-services/group-file/get-private-file-url": { + "types": "./src/oidb-services/group-file/get-private-file-url.ts", + "default": "./src/oidb-services/group-file/get-private-file-url.ts" + }, + "./oidb-services/group-file/delete-group-file": { + "types": "./src/oidb-services/group-file/delete-group-file.ts", + "default": "./src/oidb-services/group-file/delete-group-file.ts" + }, + "./oidb-services/group-file/move-group-file": { + "types": "./src/oidb-services/group-file/move-group-file.ts", + "default": "./src/oidb-services/group-file/move-group-file.ts" + }, + "./oidb-services/group-file/create-group-folder": { + "types": "./src/oidb-services/group-file/create-group-folder.ts", + "default": "./src/oidb-services/group-file/create-group-folder.ts" + }, + "./oidb-services/group-file/delete-group-folder": { + "types": "./src/oidb-services/group-file/delete-group-folder.ts", + "default": "./src/oidb-services/group-file/delete-group-folder.ts" + }, + "./oidb-services/group-file/rename-group-folder": { + "types": "./src/oidb-services/group-file/rename-group-folder.ts", + "default": "./src/oidb-services/group-file/rename-group-folder.ts" + }, + "./oidb-services/group-file/get-group-ptt-url": { + "types": "./src/oidb-services/group-file/get-group-ptt-url.ts", + "default": "./src/oidb-services/group-file/get-group-ptt-url.ts" + }, + "./oidb-services/group-file/get-private-ptt-url": { + "types": "./src/oidb-services/group-file/get-private-ptt-url.ts", + "default": "./src/oidb-services/group-file/get-private-ptt-url.ts" + }, + "./oidb-services/group-file/get-group-video-url": { + "types": "./src/oidb-services/group-file/get-group-video-url.ts", + "default": "./src/oidb-services/group-file/get-group-video-url.ts" + }, + "./oidb-services/group-file/get-private-video-url": { + "types": "./src/oidb-services/group-file/get-private-video-url.ts", + "default": "./src/oidb-services/group-file/get-private-video-url.ts" + }, + "./bridge-context": { + "types": "./src/bridge-context.ts", + "default": "./src/bridge-context.ts" + }, + "./qq-info": { + "types": "./src/qq-info.ts", + "default": "./src/qq-info.ts" + }, + "./format": { + "types": "./src/format.ts", + "default": "./src/format.ts" + }, + "./msg-push": { + "types": "./src/msg-push/index.ts", + "default": "./src/msg-push/index.ts" + }, + "./msg-push/registry": { + "types": "./src/msg-push/registry.ts", + "default": "./src/msg-push/registry.ts" + }, + "./msg-push/context": { + "types": "./src/msg-push/context.ts", + "default": "./src/msg-push/context.ts" + }, + "./msg-push/decoders/event-0x2dc": { + "types": "./src/msg-push/decoders/event-0x2dc.ts", + "default": "./src/msg-push/decoders/event-0x2dc.ts" + }, + "./highway": { + "types": "./src/highway/highway-client.ts", + "default": "./src/highway/highway-client.ts" + }, + "./highway/utils": { + "types": "./src/highway/utils.ts", + "default": "./src/highway/utils.ts" + }, + "./highway/pipeline": { + "types": "./src/highway/pipeline.ts", + "default": "./src/highway/pipeline.ts" + }, + "./highway/image-upload": { + "types": "./src/highway/image-upload.ts", + "default": "./src/highway/image-upload.ts" + }, + "./highway/ptt-upload": { + "types": "./src/highway/ptt-upload.ts", + "default": "./src/highway/ptt-upload.ts" + }, + "./highway/video-upload": { + "types": "./src/highway/video-upload.ts", + "default": "./src/highway/video-upload.ts" + }, + "./highway/ffmpeg-addon": { + "types": "./src/highway/ffmpeg-addon.ts", + "default": "./src/highway/ffmpeg-addon.ts" + }, + "./web/group-album": { + "types": "./src/web/group-album.ts", + "default": "./src/web/group-album.ts" + }, + "./web/group-essence": { + "types": "./src/web/group-essence.ts", + "default": "./src/web/group-essence.ts" + }, + "./web/group-honor": { + "types": "./src/web/group-honor.ts", + "default": "./src/web/group-honor.ts" + }, + "./web/group-notice": { + "types": "./src/web/group-notice.ts", + "default": "./src/web/group-notice.ts" + }, + "./web/request-util": { + "types": "./src/web/request-util.ts", + "default": "./src/web/request-util.ts" + } + }, + "scripts": { + "test": "vitest run", + "bench": "vitest bench --run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@snowluma/common": "workspace:*", + "@snowluma/proto-defs": "workspace:*", + "@snowluma/proton": "workspace:*", + "@snowluma/sqlite": "workspace:*" + }, + "devDependencies": { + "@types/node": "^24.12.2", + "typescript": "catalog:", + "vite": "catalog:", + "vitest": "^4.1.4" + } +} diff --git a/packages/bridge/src/bridge-context.ts b/packages/protocol/src/bridge-context.ts similarity index 94% rename from packages/bridge/src/bridge-context.ts rename to packages/protocol/src/bridge-context.ts index 63a371f7..f15e0053 100644 --- a/packages/bridge/src/bridge-context.ts +++ b/packages/protocol/src/bridge-context.ts @@ -1,9 +1,9 @@ // BridgeContext — the protocol-layer surface that anything inside -// @snowluma/bridge (highway uploaders, OIDB envelope helper, element +// @snowluma/protocol (highway uploaders, OIDB envelope helper, element // builder, msg-push parsers) accepts when it needs `bridge.identity` // or `bridge.sendRawPacket` plus the upload-metadata cache. // -// Deliberately apis-less: @snowluma/bridge knows nothing about the +// Deliberately apis-less: @snowluma/protocol knows nothing about the // `apis..method()` hub that lives in @snowluma/core, so the // type that bridge code accepts must NOT mention `ApiHub`. The api- // layer's own extended context (with `apis: ApiHub`) lives at @@ -23,7 +23,7 @@ import type { SendPacketResult } from '@snowluma/common/packet-sender'; * succeeds. Lets the OneBot send-message path reconstruct the full * payload when the caller only echoes the `file_id` back later. Lives * here (not on @snowluma/core's `bridge.ts`) so element-builder + the - * forward-builder — both inside @snowluma/bridge — can read the cache + * forward-builder — both inside @snowluma/protocol — can read the cache * without circular-importing @snowluma/core. */ export interface UploadedFileMeta { diff --git a/packages/bridge/src/bridge-oidb.ts b/packages/protocol/src/bridge-oidb.ts similarity index 85% rename from packages/bridge/src/bridge-oidb.ts rename to packages/protocol/src/bridge-oidb.ts index 7f618b8c..98961527 100644 --- a/packages/bridge/src/bridge-oidb.ts +++ b/packages/protocol/src/bridge-oidb.ts @@ -1,6 +1,9 @@ import { protobuf_decode } from '@snowluma/proton'; -import type { BridgeContext } from './bridge-context'; import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb'; +// Sender capability is the minimal interface needed by runOidb. The +// concrete BridgeContext (and the Bridge class extending it) is +// structurally a superset, so callers keep passing `bridge` unchanged. +import type { OidbSender } from './oidb-service'; /** * Build the OidbBase-shaped TS value. Pure helper, no protobuf @@ -45,12 +48,12 @@ export function makeOidbEnvelope( * packet carried no payload). */ export async function runOidb( - bridge: BridgeContext, + sender: OidbSender, cmd: string, envelopeBytes: Uint8Array, timeoutMs?: number, ): Promise { - const result = await bridge.sendRawPacket(cmd, envelopeBytes, timeoutMs); + const result = await sender.sendRawPacket(cmd, envelopeBytes, timeoutMs); if (!result.success) throw new Error(result.errorMessage || 'packet send failed'); if (!result.gotResponse) throw new Error(result.errorMessage || 'no response'); diff --git a/packages/bridge/src/element-builder.ts b/packages/protocol/src/element-builder.ts similarity index 87% rename from packages/bridge/src/element-builder.ts rename to packages/protocol/src/element-builder.ts index 8e39da2d..89a9defa 100644 --- a/packages/bridge/src/element-builder.ts +++ b/packages/protocol/src/element-builder.ts @@ -1,15 +1,17 @@ +import type { + MarkdownData, + MentionExtraSend, +} from '@snowluma/proto-defs/action'; +import type { Elem, GroupFileExtra } from '@snowluma/proto-defs/element'; import { protobuf_encode } from '@snowluma/proton'; +import { randomUUID } from 'crypto'; +import { deflateSync } from 'zlib'; import type { BridgeContext } from './bridge-context'; import type { MessageElement } from './events'; import { uploadImageMsgInfo } from './highway/image-upload'; import { hexToBytes } from './highway/pipeline'; import { uploadPttMsgInfo } from './highway/ptt-upload'; import { uploadVideoMsgInfo } from './highway/video-upload'; -import type { - MarkdownData, - MentionExtraSend, -} from '@snowluma/proto-defs/action'; -import type { Elem, GroupFileExtra } from '@snowluma/proto-defs/element'; type ProtoElem = Partial; @@ -33,13 +35,13 @@ export interface SendContext { function makeTextElem(text: string): ProtoElem { return { - text: { str: text } as any, + text: { str: text }, }; } function makeFaceElem(faceId: number): ProtoElem { return { - face: { index: faceId } as any, + face: { index: faceId }, }; } @@ -81,14 +83,14 @@ function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem text: { str, pbReserve: extra, - } as any, + }, }; } function makeReplyElem(element: MessageElement): ProtoElem { const seq = element.replySeq! & 0xFFFFFFFF; - const srcMsg: any = { + const srcMsg: NonNullable = { origSeqs: [seq], }; @@ -114,7 +116,7 @@ function makeJsonElem(element: MessageElement): ProtoElem { richMsg: { serviceId: 1, template1: payload, - } as any, + }, }; } @@ -129,7 +131,7 @@ function makeXmlElem(element: MessageElement): ProtoElem { richMsg: { serviceId: element.subType === 0 ? 35 : (element.subType ?? 35), template1: payload, - } as any, + }, }; } @@ -141,18 +143,10 @@ function makeMarkdownElem(element: MessageElement): ProtoElem { serviceType: 45, pbElem: data, businessType: 1, - } as any, + }, }; } -function escapeXml(value: string): string { - return value - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); -} function makeForwardElem(element: MessageElement): ProtoElem { const resId = (element.resId ?? '').trim(); @@ -160,10 +154,12 @@ function makeForwardElem(element: MessageElement): ProtoElem { throw new Error('forward resId is required'); } - // Multi-msg preview bubble — modelled on the go-cqhttp / NapCat XML. - // `source` becomes the bold header (e.g. "群聊的聊天记录"), `news` - // entries become per-line previews ("nick: text"), `summary` is the - // grey footer ("查看 N 条转发消息"), `prompt` is the chat-list brief. + // `uniseq` MUST round-trip between the preview JSON and the outer + // upload's piggyback `actionCommand` for nested forwards to resolve + // without an extra server hit. Generate one fresh if absent (flat + // forwards don't piggyback anyway, so the value is cosmetic there). + const uniseq = (element.forwardUuid ?? '').trim() || randomUUID(); + const source = element.forwardSource && element.forwardSource.length > 0 ? element.forwardSource : '聊天记录'; @@ -178,36 +174,49 @@ function makeForwardElem(element: MessageElement): ProtoElem { ? element.forwardTSum : Math.max(news.length, 1); - const newsTitles = news - .map(n => `${escapeXml(n.text ?? '')}`) - .join(''); + // LightApp / `com.tencent.multimsg` is the modern wire shape both + // QQ-NT, Lagrange.Core, and NapCat emit and decode. The older + // `richMsg serviceID=35 m_resid=…` XML still renders on mobile QQ + // but it doesn't carry `uniseq`, so nested forwards lose the link + // between the inner preview and the piggybacked actions on the + // outer's LongMsgResult — cross-checked against + // `dev/Lagrange.Core/.../Message/Entity/MultiMsgEntity.cs:43-115` + // and `dev/NapCatQQ/.../helper/forward-msg-builder.ts:52-122`. + const lightApp = { + app: 'com.tencent.multimsg', + config: { + autosize: 1, + forward: 1, + round: 1, + type: 'normal', + width: 300, + }, + desc: prompt, + extra: JSON.stringify({ filename: uniseq, tsum: tSum }), + meta: { + detail: { + news: news.map(n => ({ text: n.text ?? '' })), + resid: resId, + source, + summary, + uniseq, + }, + }, + prompt, + ver: '0.0.0.5', + view: 'contact', + }; - const resIdAttr = escapeXml(resId); - const xml = - `` + - `` + - `` + - `${escapeXml(source)}` + - newsTitles + - `` + - `${escapeXml(summary)}` + - `` + - `` + - ``; - - const encodedXml = new TextEncoder().encode(xml); - const payload = new Uint8Array(encodedXml.length + 1); - payload[0] = 0x00; - payload.set(encodedXml, 1); + const json = JSON.stringify(lightApp); + const deflated = deflateSync(Buffer.from(json, 'utf8')); + const payload = new Uint8Array(deflated.length + 1); + payload[0] = 0x01; // 0x01 prefix = deflated JSON (vs 0x00 = uncompressed XML) + payload.set(deflated, 1); return { - richMsg: { - serviceId: 35, - template1: payload, - } as any, + lightApp: { + data: payload, + }, }; } @@ -225,7 +234,7 @@ async function makeImageElem(ctx: SendContext, element: MessageElement): Promise serviceType: 48, pbElem: msgInfo, businessType: isGroup ? 20 : 10, - } as any, + }, }; } @@ -246,7 +255,7 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise

; forwardTSum?: number; + /** `uniseq` baked into the preview's LightApp JSON. For a nested + * forward, the *outer* upload uses this same uuid as the + * `actionCommand` for the piggyback entry carrying the inner + * layer's msgBody — so receivers (Mobile QQ / QQ-NT clients) can + * resolve the inner layer from the outer's single fetch instead of + * hitting the server again. Defaults to a fresh UUID on send when + * omitted (i.e. for non-nested forwards). */ + forwardUuid?: string; // Server-side fingerprints carried from receive side so a forward can do a // pure md5/sha1 fast-upload without re-downloading the original bytes. // Set together with `noByteFallback: true` to make the upload modules throw diff --git a/packages/bridge/src/format.ts b/packages/protocol/src/format.ts similarity index 100% rename from packages/bridge/src/format.ts rename to packages/protocol/src/format.ts diff --git a/packages/bridge/src/highway/ffmpeg-addon.ts b/packages/protocol/src/highway/ffmpeg-addon.ts similarity index 100% rename from packages/bridge/src/highway/ffmpeg-addon.ts rename to packages/protocol/src/highway/ffmpeg-addon.ts diff --git a/packages/bridge/src/highway/highway-client.ts b/packages/protocol/src/highway/highway-client.ts similarity index 89% rename from packages/bridge/src/highway/highway-client.ts rename to packages/protocol/src/highway/highway-client.ts index 963a92dd..34ef26a4 100644 --- a/packages/bridge/src/highway/highway-client.ts +++ b/packages/protocol/src/highway/highway-client.ts @@ -1,13 +1,16 @@ -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import net from 'net'; -import type { BridgeContext } from '../bridge-context'; import type { + HighwayMsgInfoBody, HttpConn0x6FF501Request, HttpConn0x6FF501Response, + NTV2IPv4, NTV2RichMediaHighwayExt, + NTV2UploadRespMsgInfo, ReqDataHighwayHead, RespDataHighwayHead, } from '@snowluma/proto-defs/highway'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import net from 'net'; +import type { BridgeContext } from '../bridge-context'; import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils'; const HIGHWAY_APP_ID = 1600001604; @@ -91,8 +94,8 @@ function makeHighwayHead( export function buildHighwayExtend( uKey: string, - msgInfo: any, - ipv4s: any[], + msgInfo: NTV2UploadRespMsgInfo, + ipv4s: NTV2IPv4[], sha1: Uint8Array | Uint8Array[], fileIndex = 0, ): Uint8Array { @@ -100,7 +103,7 @@ export function buildHighwayExtend( if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body'); const selected = msgInfoBody[fileIndex] ?? msgInfoBody[0]; - const networkIpv4s: any[] = []; + const networkIpv4s: NonNullable['ipv4s']> = []; for (const ipv4 of ipv4s ?? []) { const ip = ipv4.outIp ?? 0; const port = ipv4.outPort ?? 0; @@ -113,7 +116,7 @@ export function buildHighwayExtend( fileUuid: selected?.index?.fileUuid ?? '', uKey, network: { ipv4s: networkIpv4s }, - msgInfoBody: msgInfoBody.map((b: any) => ({ + msgInfoBody: msgInfoBody.map((b: HighwayMsgInfoBody) => ({ index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum, })), blockSize: HIGHWAY_BLOCK_SIZE, @@ -239,7 +242,20 @@ export async function uploadHighwayHttp( const { head: respHead } = unpackHighwayFrame(responseBody); const resp = protobuf_decode(respHead); if (resp?.errorCode && resp.errorCode !== 0) { - throw new Error(`highway upload error_code=${resp.errorCode}`); + // Surface every diagnostic the highway response carries so + // user reports of `error_code=921` and friends include the + // server-side context (segHead.retCode, chunk size, file md5) + // — without these we can't tell apart a malformed-payload + // reject, a session-ticket mismatch, or a per-account rate- + // limit. + const segRetCode = resp.msgSegHead?.retCode ?? 0; + const fileMd5Hex = Buffer.from(fileMd5).toString('hex'); + throw new Error( + `highway upload error_code=${resp.errorCode}` + + ` (cmdId=${commandId} chunk=${chunkSize}/${bytes.length}` + + ` offset=${offset} segRetCode=${segRetCode}` + + ` fileMd5=${fileMd5Hex.slice(0, 16)}…)`, + ); } offset += chunkSize; console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`); diff --git a/packages/bridge/src/highway/image-upload.ts b/packages/protocol/src/highway/image-upload.ts similarity index 89% rename from packages/bridge/src/highway/image-upload.ts rename to packages/protocol/src/highway/image-upload.ts index dbdba3d4..78ff7b17 100644 --- a/packages/bridge/src/highway/image-upload.ts +++ b/packages/protocol/src/highway/image-upload.ts @@ -46,7 +46,14 @@ function imageDataFromFingerprint(element: MessageElement): ImageData { sha1Hex: element.sha1Hex ?? '', fileName: element.fileName || `${element.md5Hex ?? 'image'}.jpg`, fileSize: element.fileSize ?? 0, - summary: element.summary || (element.subType === 0 ? '[image]' : '[sticker]'), + // QQ ecosystem convention — mobile QQ + Lagrange.Core + NapCat all + // surface these exact Chinese strings as the chat-list bubble + // preview text. English fallbacks would render `[image]` / + // `[sticker]` in QQ users' chat lists instead of the expected + // `[图片]` / `[动画表情]`. Cross-checked against: + // dev/NapCatQQ/.../packet/message/element.ts:367-371 + // dev/Lagrange.Core/.../Message/Entity/ImageEntity.cs:186-192 + summary: element.summary || (element.subType === 1 ? '[动画表情]' : '[图片]'), subType: element.subType ?? 0, width: element.width ?? 0, height: element.height ?? 0, @@ -89,7 +96,7 @@ async function loadImageFromSource(source: string, fileName: string, subType: nu sha1Hex: hashes.sha1Hex, fileName: finalName, fileSize: loaded.bytes.length, - summary: summary || (subType === 0 ? '[image]' : '[sticker]'), + summary: summary || (subType === 1 ? '[动画表情]' : '[图片]'), subType, width: fmt.width, height: fmt.height, diff --git a/packages/bridge/src/highway/pipeline.ts b/packages/protocol/src/highway/pipeline.ts similarity index 95% rename from packages/bridge/src/highway/pipeline.ts rename to packages/protocol/src/highway/pipeline.ts index 7eb0e551..af3ecc2c 100644 --- a/packages/bridge/src/highway/pipeline.ts +++ b/packages/protocol/src/highway/pipeline.ts @@ -1,14 +1,18 @@ -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import crypto from 'crypto'; import { createLogger } from '@snowluma/common/logger'; -import type { BridgeContext } from '../bridge-context'; -import { makeOidbEnvelope } from '../bridge-oidb'; import type { EncodableMediaMsgInfo, + HighwayMsgInfoBody, + NTV2ExtBizInfo, + NTV2UploadInfo, + NTV2UploadRespBody, NTV2UploadRichMediaReq, NTV2UploadRichMediaResp, } from '@snowluma/proto-defs/highway'; import { OidbBase } from '@snowluma/proto-defs/oidb'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import crypto from 'crypto'; +import type { BridgeContext } from '../bridge-context'; +import { makeOidbEnvelope } from '../bridge-oidb'; import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client'; const moduleLog = createLogger('Highway'); @@ -64,11 +68,11 @@ export interface NtV2UploadParams { /** `reqHead.scene.businessType` (1=image, 3=voice, 2=video). */ businessType: number; /** `upload.uploadInfo` array. Each entry is `{ fileInfo, subFileType }`. */ - uploadInfo: unknown[]; + uploadInfo: NTV2UploadInfo[]; /** `upload.compatQmsgSceneType`. */ compatQmsgSceneType: number; /** `upload.extBizInfo` — type-specific bytes/flags. */ - extBizInfo: unknown; + extBizInfo: NTV2ExtBizInfo; /** Sub-file Highway PUTs to perform after the OIDB response. */ uploads: MediaSubFileUpload[]; /** Used in error messages. Defaults to 'media'. */ @@ -107,7 +111,7 @@ export function hexToBytes(hex: string): Uint8Array { * Sessions are cached across sub-file uploads — video does two PUTs but * only fetches the Highway session once. */ -export async function runNtv2Upload(params: NtV2UploadParams): Promise { +export async function runNtv2Upload(params: NtV2UploadParams): Promise { const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params; const label = params.label ?? 'media'; const raw = bridge.identity?.uin; @@ -118,7 +122,7 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise { // Build the full body once. Pulling this in here means each format file // only specifies the seven fields that actually vary. - const body: any = { + const body: NTV2UploadRichMediaReq = { reqHead: { common: { requestId: params.requestId, command: 100 }, scene: { @@ -157,7 +161,7 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise { throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`); } - const uploadBody: any = resp.body; + const uploadBody = 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`); @@ -186,11 +190,13 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise { continue; } + if (!target) continue; + const extend = buildHighwayExtend( uKey, upload.msgInfo, target.ipv4s ?? [], - sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both + sub.sha1, sub.subFileIndex ?? 0, ); log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source)); @@ -218,16 +224,16 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise { * pic alone unless the server populates it. */ export function finalizeMediaMsgInfo( - upload: any, + upload: NTV2UploadRespBody, defaultPic?: { bizType: number; textSummary: string }, ): Uint8Array { if (!upload?.msgInfo) throw new Error('upload response missing msgInfo'); - const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: any) => ({ + const msgInfoBody = (upload.msgInfo.msgInfoBody ?? []).map((b: HighwayMsgInfoBody) => ({ index: b.index, picture: b.picture, fileExist: b.fileExist, hashSum: b.hashSum, })); - const extBizInfo: any = {}; + const extBizInfo: NonNullable = {}; if (upload.msgInfo.extBizInfo?.pic) { extBizInfo.pic = { ...upload.msgInfo.extBizInfo.pic }; if (defaultPic) { diff --git a/packages/bridge/src/highway/ptt-upload.ts b/packages/protocol/src/highway/ptt-upload.ts similarity index 100% rename from packages/bridge/src/highway/ptt-upload.ts rename to packages/protocol/src/highway/ptt-upload.ts diff --git a/packages/bridge/src/highway/utils.ts b/packages/protocol/src/highway/utils.ts similarity index 100% rename from packages/bridge/src/highway/utils.ts rename to packages/protocol/src/highway/utils.ts diff --git a/packages/bridge/src/highway/video-upload.ts b/packages/protocol/src/highway/video-upload.ts similarity index 100% rename from packages/bridge/src/highway/video-upload.ts rename to packages/protocol/src/highway/video-upload.ts diff --git a/packages/bridge/src/identity-service.ts b/packages/protocol/src/identity-service.ts similarity index 100% rename from packages/bridge/src/identity-service.ts rename to packages/protocol/src/identity-service.ts diff --git a/packages/bridge/src/msg-push/context.ts b/packages/protocol/src/msg-push/context.ts similarity index 100% rename from packages/bridge/src/msg-push/context.ts rename to packages/protocol/src/msg-push/context.ts diff --git a/packages/bridge/src/msg-push/decoders/event-0x210.ts b/packages/protocol/src/msg-push/decoders/event-0x210.ts similarity index 100% rename from packages/bridge/src/msg-push/decoders/event-0x210.ts rename to packages/protocol/src/msg-push/decoders/event-0x210.ts diff --git a/packages/bridge/src/msg-push/decoders/event-0x2dc.ts b/packages/protocol/src/msg-push/decoders/event-0x2dc.ts similarity index 100% rename from packages/bridge/src/msg-push/decoders/event-0x2dc.ts rename to packages/protocol/src/msg-push/decoders/event-0x2dc.ts diff --git a/packages/bridge/src/msg-push/decoders/friend-message.ts b/packages/protocol/src/msg-push/decoders/friend-message.ts similarity index 100% rename from packages/bridge/src/msg-push/decoders/friend-message.ts rename to packages/protocol/src/msg-push/decoders/friend-message.ts diff --git a/packages/bridge/src/msg-push/decoders/group-admin.ts b/packages/protocol/src/msg-push/decoders/group-admin.ts similarity index 100% rename from packages/bridge/src/msg-push/decoders/group-admin.ts rename to packages/protocol/src/msg-push/decoders/group-admin.ts diff --git a/packages/bridge/src/msg-push/decoders/group-join-request.ts b/packages/protocol/src/msg-push/decoders/group-join-request.ts similarity index 76% rename from packages/bridge/src/msg-push/decoders/group-join-request.ts rename to packages/protocol/src/msg-push/decoders/group-join-request.ts index 67d87aea..4ca79ed4 100644 --- a/packages/bridge/src/msg-push/decoders/group-join-request.ts +++ b/packages/protocol/src/msg-push/decoders/group-join-request.ts @@ -15,7 +15,15 @@ export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => { time: ctx.head.timestamp, selfUin: ctx.selfUin, groupId: join.groupUin ?? 0, - fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? '', ctx.fromUin), + // Strangers (not in our cache, not yet group members) won't resolve + // here — pass 0 instead of ctx.fromUin (which on a group-scoped push + // IS the group's own uin, so falling back to it produces a bogus + // `fromUin === groupId` collision). The packet-pipeline's pre- + // dispatch hook does an async UID-form FetchUserProfile lookup to + // fill in the uin + nickname before the event is emitted — same + // shape as Lagrange's flow at + // `dev/Lagrange.Core/.../MessagingLogic.cs:215-224`. + fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? '', 0), fromUid: join.targetUid ?? '', subType: 'add', message: '', @@ -33,7 +41,7 @@ export const decodeGroupInvitation: MsgPushDecoder = (ctx) => { time: ctx.head.timestamp, selfUin: ctx.selfUin, groupId: inner.groupUin ?? 0, - fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? '', ctx.fromUin), + fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? '', 0), fromUid: inner.invitorUid ?? '', subType: 'invite', message: '', @@ -50,7 +58,7 @@ export const decodeGroupInvite: MsgPushDecoder = (ctx) => { time: ctx.head.timestamp, selfUin: ctx.selfUin, groupId: invite.groupUin ?? 0, - fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? '', ctx.fromUin), + fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? '', 0), fromUid: invite.invitorUid ?? '', subType: 'invite', message: '', diff --git a/packages/bridge/src/msg-push/decoders/group-member-change.ts b/packages/protocol/src/msg-push/decoders/group-member-change.ts similarity index 100% rename from packages/bridge/src/msg-push/decoders/group-member-change.ts rename to packages/protocol/src/msg-push/decoders/group-member-change.ts diff --git a/packages/bridge/src/msg-push/decoders/group-message.ts b/packages/protocol/src/msg-push/decoders/group-message.ts similarity index 100% rename from packages/bridge/src/msg-push/decoders/group-message.ts rename to packages/protocol/src/msg-push/decoders/group-message.ts diff --git a/packages/bridge/src/msg-push/decoders/temp-message.ts b/packages/protocol/src/msg-push/decoders/temp-message.ts similarity index 100% rename from packages/bridge/src/msg-push/decoders/temp-message.ts rename to packages/protocol/src/msg-push/decoders/temp-message.ts diff --git a/packages/bridge/src/msg-push/enums.ts b/packages/protocol/src/msg-push/enums.ts similarity index 100% rename from packages/bridge/src/msg-push/enums.ts rename to packages/protocol/src/msg-push/enums.ts diff --git a/packages/bridge/src/msg-push/helpers.ts b/packages/protocol/src/msg-push/helpers.ts similarity index 100% rename from packages/bridge/src/msg-push/helpers.ts rename to packages/protocol/src/msg-push/helpers.ts diff --git a/packages/bridge/src/msg-push/index.ts b/packages/protocol/src/msg-push/index.ts similarity index 100% rename from packages/bridge/src/msg-push/index.ts rename to packages/protocol/src/msg-push/index.ts diff --git a/packages/bridge/src/msg-push/registry.ts b/packages/protocol/src/msg-push/registry.ts similarity index 100% rename from packages/bridge/src/msg-push/registry.ts rename to packages/protocol/src/msg-push/registry.ts diff --git a/packages/bridge/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts similarity index 89% rename from packages/bridge/src/msg-push/rich-body-decoder.ts rename to packages/protocol/src/msg-push/rich-body-decoder.ts index 2f1840e1..07fee1fe 100644 --- a/packages/bridge/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -97,7 +97,11 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { width: img.picWidth ?? 0, height: img.picHeight ?? 0, subType: img.pbRes?.subType ?? 0, - summary: img.pbRes?.summary ?? '[image]', + // `[图片]` / `[动画表情]` are the QQ-ecosystem default + // bubble texts; mobile QQ + Lagrange.Core + NapCat all + // expect these literal Chinese strings when the wire + // doesn't carry a per-image override. + summary: img.pbRes?.summary || (img.pbRes?.subType === 1 ? '[动画表情]' : '[图片]'), md5Hex: toHexUpper(img.picMd5), }); } @@ -115,7 +119,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { width: img.width ?? 0, height: img.height ?? 0, subType: img.pbRes?.subType ?? 0, - summary: img.pbRes?.summary ?? '[image]', + summary: img.pbRes?.summary || (img.pbRes?.subType === 1 ? '[动画表情]' : '[图片]'), md5Hex: toHexUpper(img.md5), }); } @@ -213,7 +217,33 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { const la = elem.lightApp; if (la.data && la.data.length > 0) { const content = decompressData(la.data); - if (content) result.push({ type: 'json', text: content }); + if (content) { + // `com.tencent.multimsg` is the multi-msg / forward preview + // LightApp (the modern replacement for the XML serviceID=35 + // shape). Parse out resid + uniseq so downstream callers can + // both render a `[聊天记录]` placeholder and walk into the + // forward chain via `fetch(resId)` — the uniseq is what links + // the inner layer to its piggybacked actions on the outer's + // LongMsgResult. Other LightApp messages fall through to the + // generic `{type: 'json'}` path. + try { + const parsed = JSON.parse(content); + if (parsed && parsed.app === 'com.tencent.multimsg') { + const detail = parsed.meta?.detail ?? {}; + const resId = typeof detail.resid === 'string' ? detail.resid : ''; + const uniseq = typeof detail.uniseq === 'string' ? detail.uniseq : ''; + if (resId) { + result.push({ + type: 'forward', + resId, + forwardUuid: uniseq || undefined, + }); + continue; + } + } + } catch { /* fall through to generic json element */ } + result.push({ type: 'json', text: content }); + } } } @@ -285,7 +315,8 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { if (fi.type?.picFormat) me.picFormat = fi.type.picFormat; if (info.extBizInfo?.pic) { me.subType = info.extBizInfo.pic.bizType ?? 0; - me.summary = info.extBizInfo.pic.textSummary || '[image]'; + me.summary = info.extBizInfo.pic.textSummary + || (me.subType === 1 ? '[动画表情]' : '[图片]'); } result.push(me); } else if (bizType === 12 || bizType === 22) { diff --git a/packages/protocol/src/oidb-service.ts b/packages/protocol/src/oidb-service.ts new file mode 100644 index 00000000..af01498d --- /dev/null +++ b/packages/protocol/src/oidb-service.ts @@ -0,0 +1,174 @@ +// OIDB service layer — the next architectural revision on top of the +// area-grouped Api facade pattern (InteractionApi / ProfileApi / …). +// +// Each OIDB cmd is modelled as a TypeScript namespace whose exported +// members ARE the `OidbCallSpec` shape (structural typing makes this +// implicit — no `implements` clause needed). The namespace also exports +// a thin `invoke()` that hands itself to `invokeOidb` for dispatch. +// +// Why namespace-as-spec instead of class: +// - stateless: no `new` overhead at the call site +// - no `this` binding, no implicit lifecycle +// - tree-shakes per-export (unused services drop out of the bundle) +// - spec ↔ code 1:1 (one file = one (cmd, subcmd) tuple) +// +// Why Pick-style minimal `Deps` per service: +// - Interface Segregation: a wire-only cmd doesn't see identity/events +// - tests mock only what's used (typically just `sendRawPacket`) +// - changes to BridgeContext don't bleed into services +// - the dep list IS the documentation of side-effects +// +// Why `ctx` threads into serialize/deserialize: +// - the namespace is then genuinely self-contained — "what does this +// cmd do on the wire + what state does it touch" lives in one file +// - earlier shape forced an `invoke = { ...Self, serialize: p => +// localSerialize(p, await ctx.resolveUserUid(...)) }` rewrite for +// every cmd that needed identity/uid resolution; ctx-aware +// serialize collapses that to a single async serialize. +// - serialize is now `TReq | Promise` so async lookups +// (resolveUserUid, identity reads) happen in place. + +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase, OidbBaseMeta } from '@snowluma/proto-defs/oidb'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { makeOidbEnvelope } from './bridge-oidb'; + +/** + * Capability narrow enough for any wire-only OIDB call. Anything that + * also needs identity / event bus / upload cache declares those via + * `Pick` and intersects with this. + */ +export interface OidbSender { + sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise; +} + +/** + * The shape every cmd namespace exports. Structural typing means a + * namespace whose top-level exports match these names + types IS an + * `OidbCallSpec` — no `implements` clause needed. + * + * `TCtx` is the namespace's capability surface — always at least + * `OidbSender` (so `invokeOidb` can dispatch through it) plus any + * `Pick` slices the cmd actually needs. + * + * One of `subCommand` (static) or `resolveSubCommand` (dynamic from + * params) must be present. `resolveSubCommand` wins if both are given. + */ +export interface OidbCallSpec { + command: number; + subCommand?: number; + resolveSubCommand?(params: TParams): number; + /** Set OIDB envelope `reserved = 1` (UIN-form variant, see makeOidbEnvelope's isUid). */ + uinForm?: boolean; + /** Override the default `OidbSvcTrpcTcp.0xNNNN_N` wire name. A few + * cmds route through different SSO names (e.g. 0xE17_0 lives at + * `MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0`); supply a function + * that takes the resolved `(cmd, subCmd)` and returns the actual + * wire name. Omit for the default scheme. */ + wireName?(command: number, subCommand: number): string; + /** Business params → wire-shaped request body. May be async (e.g. + * when ctx.resolveUserUid hits the cache or the network). */ + serialize(ctx: TCtx, params: TParams): TReq | Promise; + /** Wire-shaped response body → business result. */ + deserialize(ctx: TCtx, body: TResp): TResult; + /** Per-type protobuf encoder — concrete generic call so the Vite plugin can monomorphize. */ + encode(env: OidbBase): Uint8Array; + /** Per-type protobuf decoder. */ + decode(bytes: Uint8Array): OidbBase; +} + +export class OidbError extends Error { + constructor( + readonly code: number, + readonly serverMsg: string, + readonly command: number, + readonly subCommand: number, + ) { + super(`OIDB error ${code} on 0x${command.toString(16)}_${subCommand}: ${serverMsg}`); + this.name = 'OidbError'; + } +} + +/** + * Template method for every OIDB call. Builds the envelope, encodes it, + * sends through the ctx's `sendRawPacket`, validates the envelope's + * `errorCode`, decodes the body, and hands the wire-shaped response to + * the spec's `deserialize` for transformation into the business result. + * + * `ctx` is threaded into both `serialize` and `deserialize` so the + * namespace can do uid resolution / identity reads in-place rather + * than forcing the caller to pre-bake values into the params. + */ +export async function invokeOidb( + ctx: TCtx, + spec: OidbCallSpec, + params: TParams, + timeoutMs?: number, +): Promise { + const subCommand = spec.resolveSubCommand + ? spec.resolveSubCommand(params) + : spec.subCommand!; + const reqBody = await spec.serialize(ctx, params); + const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false); + const reqBytes = spec.encode(env); + const wireName = spec.wireName + ? spec.wireName(spec.command, subCommand) + : `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`; + + const result = await ctx.sendRawPacket(wireName, reqBytes, timeoutMs); + if (!result.success) throw new Error(result.errorMessage || 'packet send failed'); + if (!result.gotResponse) throw new Error(result.errorMessage || 'no response'); + + const respBytes = result.responseData ?? new Uint8Array(0); + if (respBytes.length > 0) { + const meta = protobuf_decode(respBytes); + const code = meta?.errorCode; + if (code && code !== 0) { + throw new OidbError(code, meta?.errorMsg ?? '', spec.command, subCommand); + } + } + + // Server may legitimately respond with an empty envelope (ack-only + // cmds like 0x9082_1 — the response carries only `errorCode = 0` + // and no body). Substitute an empty placeholder so `deserialize` + // always receives a defined object; specs that read fields off the + // body must already guard with `?? []` etc. + const respBody = spec.decode(respBytes).body ?? ({} as TResp); + return spec.deserialize(ctx, respBody); +} + +/** + * Build the request wire bytes for a spec without sending — useful for + * wire dump debugging, capability probing, and unit tests of the + * encode path. Threads `ctx` because `serialize` may want it (and + * because matching `invokeOidb`'s shape avoids two call patterns). + */ +export async function buildOidbRequest( + ctx: TCtx, + spec: OidbCallSpec, + params: TParams, +): Promise<{ wireName: string; bytes: Uint8Array }> { + const subCommand = spec.resolveSubCommand + ? spec.resolveSubCommand(params) + : spec.subCommand!; + const reqBody = await spec.serialize(ctx, params); + const env = makeOidbEnvelope(spec.command, subCommand, reqBody, spec.uinForm ?? false); + const bytes = spec.encode(env); + const wireName = spec.wireName + ? spec.wireName(spec.command, subCommand) + : `OidbSvcTrpcTcp.0x${spec.command.toString(16)}_${subCommand}`; + return { wireName, bytes }; +} + +/** + * Decode raw wire bytes into the business result via a spec's + * deserialize path — symmetric debug helper for buildOidbRequest. + */ +export function parseOidbResponse( + ctx: TCtx, + spec: OidbCallSpec, + bytes: Uint8Array, +): TResult { + return spec.deserialize(ctx, spec.decode(bytes).body ?? ({} as TResp)); +} diff --git a/packages/protocol/src/oidb-services/contacts/fetch-download-rkeys.ts b/packages/protocol/src/oidb-services/contacts/fetch-download-rkeys.ts new file mode 100644 index 00000000..ff3e2872 --- /dev/null +++ b/packages/protocol/src/oidb-services/contacts/fetch-download-rkeys.ts @@ -0,0 +1,53 @@ +// 0x9067_202 — fetch download-rkey tokens for private/group/fallback +// image scopes. The rkey is a server-issued signed download token used +// to authenticate every CDN GET against `gchat.qpic.cn` / similar +// endpoints. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +const PRIVATE_IMAGE = 10; +const GROUP_IMAGE = 20; +const FALLBACK_IMAGE = 2; + +export namespace FetchDownloadRkeys { + export const command = 0x9067; + export const subCommand = 202; + export const uinForm = true; + + export interface Params {} + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, _: Params): NTV2RichMediaReq => ({ + reqHead: { + common: { requestId: 1, command: 202 }, + scene: { requestType: 2, businessType: 1, sceneType: 0 }, + client: { agentType: 2 }, + }, + downloadRkey: { + types: [PRIVATE_IMAGE, GROUP_IMAGE, FALLBACK_IMAGE], + }, + }); + + export const deserialize = (_ctx: Deps, body: NTV2RichMediaResp): NTV2RichMediaResp => { + // Propagate server-side OIDB-equivalent error via the embedded + // respHead.retCode — bytes-level OIDB errorCode would already + // have thrown OidbError before deserialize was called. + if (body.respHead?.retCode && body.respHead.retCode !== 0) { + throw new Error(body.respHead.message ?? 'fetch download rkey failed'); + } + return body; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps): Promise => + invokeOidb(deps, FetchDownloadRkeys, {}); +} diff --git a/packages/protocol/src/oidb-services/contacts/fetch-friend-list-page.ts b/packages/protocol/src/oidb-services/contacts/fetch-friend-list-page.ts new file mode 100644 index 00000000..0c00ad3b --- /dev/null +++ b/packages/protocol/src/oidb-services/contacts/fetch-friend-list-page.ts @@ -0,0 +1,54 @@ +// 0xFD4_1 — single-page friend-roster fetch. +// +// QQ paginates the friend list with a wire-level cursor (`nextUin`). +// This namespace handles ONE round-trip — the facade drives the +// while-loop until the server stops emitting a next cursor and +// concatenates results into the public FriendInfo[] shape. + +import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb'; +import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace FetchFriendListPage { + export const command = 0xFD4; + export const subCommand = 1; + + export interface Params { + /** Cursor: `null` for the first page, otherwise the previous + * page's `nextUin`. */ + nextUin: number | null; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbFriendListRequest => { + const body: OidbFriendListRequest = { + friendCount: 300, + field4: 0, + field6: 1, + field7: 0x7FFFFFFF, + body: [ + { type: 1, number: { numbers: [103, 102, 20002, 27394] } }, + { type: 4, number: { numbers: [100, 101, 102] } }, + ], + field10002: [13578, 13579, 13573, 13572, 13568], + field10003: 4051, + }; + if (p.nextUin !== null) { + body.nextUin = { uin: p.nextUin }; + } + return body; + }; + + export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0xFD4_1Response): OidbSvcTrpcTcp0xFD4_1Response => body; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, FetchFriendListPage, params); +} diff --git a/packages/protocol/src/oidb-services/contacts/fetch-group-list.ts b/packages/protocol/src/oidb-services/contacts/fetch-group-list.ts new file mode 100644 index 00000000..3b26c1b3 --- /dev/null +++ b/packages/protocol/src/oidb-services/contacts/fetch-group-list.ts @@ -0,0 +1,57 @@ +// 0xFE5_2 — fetch the bot's joined-groups list with full per-group +// info. +// +// The verbose `config` blob in the request body asks QQ which +// per-group fields to include. Asking for everything blows the +// named-pipe write buffer on accounts with ~200+ groups (see #42), +// so we keep `config1.*` mostly on but turn off the costly +// `field5002`/`field5003` and entire `config2` block that never map +// back to a decoded field anyway. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbSvcTrpcTcp0xFE5_2Response } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupListRequest } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace FetchGroupList { + export const command = 0xFE5; + export const subCommand = 2; + export const uinForm = true; + + export interface Params {} + + export type Deps = OidbSender; + + const allTrue = true; + + export const serialize = (_ctx: Deps, _: Params): OidbGroupListRequest => ({ + config: { + config1: { + groupOwner: allTrue, field2: allTrue, memberMax: allTrue, memberCount: allTrue, + groupName: allTrue, field8: allTrue, field9: allTrue, field10: allTrue, + field11: allTrue, field12: allTrue, field13: allTrue, field14: allTrue, + field15: allTrue, field16: allTrue, field17: allTrue, field18: allTrue, + question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue, + field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue, + field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue, + field32: allTrue, field5001: allTrue, field5002: false, field5003: false, + }, + config2: { + field1: false, field2: false, field3: false, field4: false, + field5: false, field6: false, field7: false, field8: false, + }, + config3: { field5: allTrue, field6: allTrue }, + }, + }); + + export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0xFE5_2Response): OidbSvcTrpcTcp0xFE5_2Response => body; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps): Promise => + invokeOidb(deps, FetchGroupList, {}); +} diff --git a/packages/protocol/src/oidb-services/contacts/fetch-group-member-list-page.ts b/packages/protocol/src/oidb-services/contacts/fetch-group-member-list-page.ts new file mode 100644 index 00000000..1089b4c8 --- /dev/null +++ b/packages/protocol/src/oidb-services/contacts/fetch-group-member-list-page.ts @@ -0,0 +1,54 @@ +// 0xFE7_3 — single-page group-member-roster fetch. +// +// Pagination cursor is the server-issued `token` string. The facade +// drives the loop until `token` comes back empty; per-group caching +// + inflight coalescing also stays on the facade since both need +// state that's per-Bridge (and is what stops Tencent risk-control +// from banning the account on busy clients — see #42). + +import type { OidbBase, OidbSvcTrpcTcp0xFE7_3Response } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupMemberListRequest } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace FetchGroupMemberListPage { + export const command = 0xFE7; + export const subCommand = 3; + + export interface Params { + groupId: number; + /** Empty string for the first page; pass the previous response's + * `token` to fetch the next page. */ + token: string; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupMemberListRequest => { + const body: OidbGroupMemberListRequest = { + groupUin: p.groupId, + field2: 5, + field3: 2, + body: { + memberName: true, memberCard: true, level: true, field13: true, + field16: true, specialTitle: true, field18: true, field20: true, + field21: true, joinTimestamp: true, lastMsgTimestamp: true, + shutUpTimestamp: true, field103: true, field104: true, field105: true, + field106: true, permission: true, field200: true, field201: true, + }, + }; + if (p.token) body.token = p.token; + return body; + }; + + export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0xFE7_3Response): OidbSvcTrpcTcp0xFE7_3Response => body; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, FetchGroupMemberListPage, params); +} diff --git a/packages/protocol/src/oidb-services/contacts/fetch-group-requests.ts b/packages/protocol/src/oidb-services/contacts/fetch-group-requests.ts new file mode 100644 index 00000000..3126f688 --- /dev/null +++ b/packages/protocol/src/oidb-services/contacts/fetch-group-requests.ts @@ -0,0 +1,40 @@ +// 0x10C0 — fetch pending group-add requests. +// subCommand 1 = main inbox, 2 = filtered (low-priority) inbox +// +// Returns the wire shape verbatim — the facade does the GroupRequestInfo +// mapping because it also needs to thread the `filtered` flag onto +// each entry, which the wire doesn't carry. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbSvcTrpcTcp0x10C0Response } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupRequestList } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace FetchGroupRequests { + export const command = 0x10C0; + + export interface Params { + /** false → subCmd 1 (main inbox), true → subCmd 2 (filtered). */ + filtered: boolean; + } + + export type Deps = OidbSender; + + export const resolveSubCommand = (p: Params): number => p.filtered ? 2 : 1; + + export const serialize = (_ctx: Deps, _: Params): OidbGroupRequestList => ({ + count: 20, + field2: 0, + }); + + export const deserialize = (_ctx: Deps, body: OidbSvcTrpcTcp0x10C0Response): OidbSvcTrpcTcp0x10C0Response => body; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, FetchGroupRequests, params); +} diff --git a/packages/protocol/src/oidb-services/contacts/fetch-user-profile-by-uid.ts b/packages/protocol/src/oidb-services/contacts/fetch-user-profile-by-uid.ts new file mode 100644 index 00000000..2d046e9e --- /dev/null +++ b/packages/protocol/src/oidb-services/contacts/fetch-user-profile-by-uid.ts @@ -0,0 +1,99 @@ +// 0xFE1_2 (UID form) — fetch a user's profile when only the UID is +// known. Same OIDB cmd + subcmd as `FetchUserProfile` (by UIN) but +// the request body's field 1 is `uid: string` instead of `uin: +// uint32`, and `reserved` stays 0 (no `uinForm`). +// +// Why two namespaces for the same (cmd, subcmd): +// - Group join requests / invitations carry the stranger's UID +// only — we never get a UIN for someone who hasn't joined yet. +// - The Tencent server WILL reject a UIN-form request with a uid- +// shaped value or vice versa, so the two variants must encode +// to byte-different wires. +// - Matches Lagrange's `OidbSvcTrpcTcp0xFE1_2Uid` vs `…Uin` split +// at `dev/Lagrange.Core/.../OidbSvcTrpcTcp0xFE1_2.cs:9-26` +// and the dispatch at +// `dev/Lagrange.Core/.../FetchUserInfoService.cs:66-78`. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + AvatarInfo, + OidbUserInfoByUidRequest, + OidbUserInfoResponse, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { UserProfileInfo } from '../../qq-info'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +const REQUESTED_KEYS = [ + 20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, + 105, 27372, 27406, 20037, +]; + +export namespace FetchUserProfileByUid { + export const command = 0xFE1; + export const subCommand = 2; + // No `uinForm` — the UID variant uses the default `reserved=0` + // envelope, mirroring Lagrange's untagged constructor at + // `OidbSvcTrpcTcp0xFE1_2.cs:9` (isUid=false → Reserved=0). + + export interface Params { + uid: string; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbUserInfoByUidRequest => ({ + uid: p.uid, + keys: REQUESTED_KEYS.map(k => ({ key: k })), + }); + + export const deserialize = (_ctx: Deps, body: OidbUserInfoResponse): UserProfileInfo => { + if (!body.body) throw new Error('user info response body missing'); + + const info: UserProfileInfo = { + uin: body.body.uin ?? 0, + uid: body.body.uid ?? '', + nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0, + }; + + if (body.body.properties) { + const bytesMap = new Map(); + const numMap = new Map(); + for (const bp of body.body.properties.bytesProperties ?? []) { + bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0)); + } + for (const np of body.body.properties.numberProperties ?? []) { + numMap.set(np.number1 ?? 0, np.number2 ?? 0); + } + const getString = (code: number): string => { + const b = bytesMap.get(code); + return b ? Buffer.from(b).toString('utf8') : ''; + }; + info.nickname = getString(20002); + info.remark = getString(103); + info.qid = getString(27394); + info.sign = getString(102); + + const avatarBytes = bytesMap.get(101); + if (avatarBytes) { + const av = protobuf_decode(avatarBytes); + if (av?.url) info.avatar = av.url + '640'; + } + const sexNum = numMap.get(20009) ?? 0; + info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown'; + info.age = numMap.get(20037) ?? 0; + info.level = numMap.get(105) ?? 0; + } + + return info; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, FetchUserProfileByUid, params); +} diff --git a/packages/protocol/src/oidb-services/contacts/fetch-user-profile.ts b/packages/protocol/src/oidb-services/contacts/fetch-user-profile.ts new file mode 100644 index 00000000..ad682b3d --- /dev/null +++ b/packages/protocol/src/oidb-services/contacts/fetch-user-profile.ts @@ -0,0 +1,115 @@ +// 0xFE1_2 — fetch a user's profile (nickname / qid / sex / age / sign +// / avatar / QQ level). +// +// `uinForm` is set so the server takes the UIN-form validation path; +// without it newer NTQQ versions reject the request with +// `[oidb] one of uid/openid is invaild`. Matches Lagrange.Core's +// FetchStrangerByUin (Reserved = 1). +// +// Property key catalogue (cross-checked against LagrangeV2's +// FetchStrangerService.cs): +// 101 — avatar info (proto-encoded AvatarInfo) +// 102 — sign (signature) +// 103 — remark +// 105 — QQ level (numeric) +// 20002 — nickname +// 20009 — gender (1 male / 2 female / 255 unknown) +// 20037 — age +// 27394 — QID + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + AvatarInfo, + OidbUserInfoRequest, + OidbUserInfoResponse, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { UserProfileInfo } from '../../qq-info'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +const REQUESTED_KEYS = [ + 20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, + 105, 27372, 27406, 20037, +]; + +export namespace FetchUserProfile { + export const command = 0xFE1; + export const subCommand = 2; + export const uinForm = true; + + export interface Params { + uin: number; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbUserInfoRequest => ({ + uin: p.uin, + keys: REQUESTED_KEYS.map(k => ({ key: k })), + }); + + /** Defaults the response uin to `requestedUin` because the server + * sometimes elides its echo. `invoke` below binds `params.uin` via + * the spec override so the namespace's call surface still takes + * only `(ctx, body)`. */ + export const deserializeWithFallback = ( + body: OidbUserInfoResponse, requestedUin: number, + ): UserProfileInfo => { + if (!body.body) throw new Error('user info response body missing'); + + const info: UserProfileInfo = { + uin: body.body.uin ?? requestedUin, + uid: body.body.uid ?? '', + nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0, + }; + + if (body.body.properties) { + const bytesMap = new Map(); + const numMap = new Map(); + for (const bp of body.body.properties.bytesProperties ?? []) { + bytesMap.set(bp.code ?? 0, bp.value ?? new Uint8Array(0)); + } + for (const np of body.body.properties.numberProperties ?? []) { + numMap.set(np.number1 ?? 0, np.number2 ?? 0); + } + const getString = (code: number): string => { + const b = bytesMap.get(code); + return b ? Buffer.from(b).toString('utf8') : ''; + }; + info.nickname = getString(20002); + info.remark = getString(103); + info.qid = getString(27394); + info.sign = getString(102); + + const avatarBytes = bytesMap.get(101); + if (avatarBytes) { + const av = protobuf_decode(avatarBytes); + if (av?.url) info.avatar = av.url + '640'; + } + const sexNum = numMap.get(20009) ?? 0; + info.sex = sexNum === 1 ? 'male' : sexNum === 2 ? 'female' : 'unknown'; + info.age = numMap.get(20037) ?? 0; + info.level = numMap.get(105) ?? 0; + } + + return info; + }; + + // Default deserialize uses uin=0 fallback — invoke() rewires it to + // the requested uin via the per-call spec override below. Tests + // that call deserialize directly should use deserializeWithFallback. + export const deserialize = (_ctx: Deps, body: OidbUserInfoResponse): UserProfileInfo => + deserializeWithFallback(body, 0); + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, { + ...FetchUserProfile, + deserialize: (_ctx, body) => deserializeWithFallback(body, params.uin), + }, params); +} diff --git a/packages/protocol/src/oidb-services/extras/fetch-ai-voice-list.ts b/packages/protocol/src/oidb-services/extras/fetch-ai-voice-list.ts new file mode 100644 index 00000000..c86507c4 --- /dev/null +++ b/packages/protocol/src/oidb-services/extras/fetch-ai-voice-list.ts @@ -0,0 +1,50 @@ +// 0x929D_0 — fetch the catalog of AI voices available for synthesis +// in a given group, grouped by category. Returns the categories +// straight from the wire (caller already expects the wire shape). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbAiVoiceListReq, OidbAiVoiceListResp, +} from '@snowluma/proto-defs/oidb-actions/media'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export interface AiVoiceItem { + voiceId: string; + voiceDisplayName: string; + voiceExampleUrl: string; +} + +export interface AiVoiceCategory { + category: string; + voices: AiVoiceItem[]; +} + +export namespace FetchAiVoiceList { + export const command = 0x929D; + export const subCommand = 0; + + export interface Params { + groupId: number; + chatType: number; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbAiVoiceListReq => ({ + groupUin: p.groupId, + chatType: p.chatType, + }); + + export const deserialize = (_ctx: Deps, body: OidbAiVoiceListResp): AiVoiceCategory[] => + (body.content as AiVoiceCategory[] | undefined) ?? []; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, FetchAiVoiceList, params); +} diff --git a/packages/protocol/src/oidb-services/extras/fetch-ai-voice.ts b/packages/protocol/src/oidb-services/extras/fetch-ai-voice.ts new file mode 100644 index 00000000..dfb63b12 --- /dev/null +++ b/packages/protocol/src/oidb-services/extras/fetch-ai-voice.ts @@ -0,0 +1,68 @@ +// 0x929B_0 — kick off AI voice synthesis and poll until the rendered +// media is available. The server may return an empty msgInfo while +// the render is in-flight; the facade polls up to `maxRetries` times. +// +// `sessionId` is a random 32-bit value used by the server to +// de-duplicate retries of the same synthesis request. +// +// Each `invoke()` is a SINGLE poll — the retry loop lives on the +// facade so callers can plug their own back-off / cancellation in +// without forking the namespace. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbAiVoiceReq, OidbAiVoiceResp, +} from '@snowluma/proto-defs/oidb-actions/media'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +/** Subset of AiVoiceMediaIndex (defined in @snowluma/core/apis/shared) + * that the AI voice response payload populates. Kept inline here so + * the namespace stays self-contained against @snowluma/protocol — the + * facade casts back to the richer core-side type. */ +export interface AiVoiceMediaIndex { + info?: { fileSize?: number; fileName?: string; type?: { type?: number; voiceFormat?: number } }; + fileUuid?: string; + storeId?: number; + uploadTime?: number; + ttl?: number; + subType?: number; +} + +export namespace FetchAiVoice { + export const command = 0x929B; + export const subCommand = 0; + + export interface Params { + groupId: number; + voiceId: string; + text: string; + chatType: number; + /** Random 32-bit session id; server uses this to deduplicate polls. */ + sessionId: number; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbAiVoiceReq => ({ + groupUin: p.groupId, + voiceId: p.voiceId, + text: p.text, + chatType: p.chatType, + session: { sessionId: p.sessionId }, + }); + + export const deserialize = (_ctx: Deps, body: OidbAiVoiceResp): AiVoiceMediaIndex | null => { + const node = body.msgInfo?.msgInfoBody?.[0]?.index as AiVoiceMediaIndex | undefined; + return node ?? null; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, FetchAiVoice, params); +} diff --git a/packages/protocol/src/oidb-services/extras/get-stranger-status.ts b/packages/protocol/src/oidb-services/extras/get-stranger-status.ts new file mode 100644 index 00000000..ae51bf2e --- /dev/null +++ b/packages/protocol/src/oidb-services/extras/get-stranger-status.ts @@ -0,0 +1,60 @@ +// 0xFE1_2 — fetch the stranger's status (online / away / busy / +// invisible). Same OIDB cmd as fetchUserProfile but a different +// request shape (only key 27372 = status, no other property keys), +// and we decode the ext-bigint status word into napcat's +// (status × 10, ext_status) pair. +// +// `uinForm` is set so the server takes the UIN-form validation path; +// without it newer NTQQ rejects with `[oidb] one of uid/openid is +// invaild`. Same flag fetchUserProfile uses. +// +// On any transport / decode failure the deserialize step is bypassed +// — the facade swallows the namespace-level exception and surfaces +// `null` so callers get a clean retcode. + +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbStrangerStatusReq, OidbStrangerStatusResp } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export interface StrangerStatus { + status: number; + ext_status: number; +} + +export namespace GetStrangerStatus { + export const command = 0xFE1; + export const subCommand = 2; + export const uinForm = true; + + export interface Params { + uin: number; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbStrangerStatusReq => ({ + uin: p.uin, + key: [{ key: 27372 }], + }); + + export const deserialize = (_ctx: Deps, body: OidbStrangerStatusResp): StrangerStatus | null => { + const raw = body.data?.status?.value; + if (raw === undefined || raw === null) return null; + const extBig = typeof raw === 'bigint' ? raw : BigInt(raw); + if (extBig <= 10n) { + return { status: Number(extBig) * 10, ext_status: 0 }; + } + const status = Number((extBig & 0xff00n) + ((extBig >> 16n) & 0xffn)); + return { status: 10, ext_status: status }; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetStrangerStatus, params); +} diff --git a/packages/protocol/src/oidb-services/extras/group-todo.ts b/packages/protocol/src/oidb-services/extras/group-todo.ts new file mode 100644 index 00000000..bb1b754f --- /dev/null +++ b/packages/protocol/src/oidb-services/extras/group-todo.ts @@ -0,0 +1,48 @@ +// 0xF90 — group todo (群待办) CRUD. +// subCommand 1 = set, 2 = complete, 3 = cancel +// +// All three sub-cmds share the same request shape ((groupUin, msgSeq)) +// so they collapse into one namespace with a dynamic subcmd resolver. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupTodo } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export type GroupTodoAction = 'set' | 'complete' | 'cancel'; + +const ACTION_TO_SUBCMD: Record = { + set: 1, + complete: 2, + cancel: 3, +}; + +export namespace GroupTodo { + export const command = 0xF90; + + export interface Params { + groupId: number; + msgSeq: bigint; + action: GroupTodoAction; + } + + export type Deps = OidbSender; + + export const resolveSubCommand = (p: Params): number => ACTION_TO_SUBCMD[p.action]; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupTodo => ({ + groupUin: p.groupId, + msgSeq: p.msgSeq, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GroupTodo, params); +} diff --git a/packages/protocol/src/oidb-services/friend/delete-friend.ts b/packages/protocol/src/oidb-services/friend/delete-friend.ts new file mode 100644 index 00000000..d932112a --- /dev/null +++ b/packages/protocol/src/oidb-services/friend/delete-friend.ts @@ -0,0 +1,53 @@ +// 0x126B_0 — delete a friend (optionally with block flag). +// +// The deeply-nested field2 sub-message is a server-side discriminator +// that must be sent verbatim — the magic numbers (130 / 109 / 8/8/50) +// match the wire shape NTQQ's own client emits and aren't a SnowLuma +// invention. Server rejects the request if any of them is wrong. +// +// Cache invalidation (re-fetching the friend list after deletion) +// lives in the facade — keeps this namespace dependency-free of +// `apis.contacts` and the OneBot-side caches. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbDeleteFriend } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace DeleteFriend { + export const command = 0x126B; + export const subCommand = 0; + + export interface Params { + userId: number; + /** Also block (拉黑) the user. Default false. */ + block?: boolean; + } + + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => ({ + field1: { + targetUid: await ctx.resolveUserUid(p.userId), + field2: { + field1: 130, + field2: 109, + field3: { field1: 8, field2: 8, field3: 50 }, + }, + block: p.block ?? false, + field4: false, + }, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, DeleteFriend, params); +} diff --git a/packages/protocol/src/oidb-services/friend/handle-friend-request.ts b/packages/protocol/src/oidb-services/friend/handle-friend-request.ts new file mode 100644 index 00000000..d3e715d9 --- /dev/null +++ b/packages/protocol/src/oidb-services/friend/handle-friend-request.ts @@ -0,0 +1,47 @@ +// 0xB5D_44 — accept (3) / reject (5) an inbound friend request. +// +// Caller passes either a pre-resolved UID string or a numeric uin +// (encoded as a digit-only string); we detect the latter and resolve +// to UID first. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbFriendRequestAction } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace HandleFriendRequest { + export const command = 0xB5D; + export const subCommand = 44; + + export interface Params { + /** Pre-resolved UID, or a digit-only numeric uin to resolve on demand. */ + uidOrFlag: string; + approve: boolean; + } + + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => { + const targetUid = /^\d+$/.test(p.uidOrFlag) + ? await ctx.resolveUserUid(parseInt(p.uidOrFlag, 10)) + : p.uidOrFlag; + return { + // Server discriminator: 3 = accept, 5 = reject. Pre-fix values + // verified against current production behaviour. + accept: p.approve ? 3 : 5, + targetUid, + }; + }; + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, HandleFriendRequest, params); +} diff --git a/packages/protocol/src/oidb-services/friend/set-friend-remark.ts b/packages/protocol/src/oidb-services/friend/set-friend-remark.ts new file mode 100644 index 00000000..188985ea --- /dev/null +++ b/packages/protocol/src/oidb-services/friend/set-friend-remark.ts @@ -0,0 +1,36 @@ +// 0xB6E_2 — set the remark (备注) shown for a friend in the bot's +// own roster. Doesn't affect what the friend sees. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbSetFriendRemark } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SetFriendRemark { + export const command = 0xB6E; + export const subCommand = 2; + + export interface Params { + userId: number; + remark: string; + } + + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => ({ + targetUid: await ctx.resolveUserUid(p.userId), + remark: p.remark, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetFriendRemark, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/get-at-all-remain.ts b/packages/protocol/src/oidb-services/group-admin/get-at-all-remain.ts new file mode 100644 index 00000000..d7453b0e --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/get-at-all-remain.ts @@ -0,0 +1,58 @@ +// 0x8A7_0 — query "@everyone" remaining-use budget for the bot in +// the given group. Server returns two independent counters: a +// per-uin budget (the bot's daily allowance) and a per-group budget +// (the group's shared allowance). The OneBot action surfaces both +// alongside a single `can_at_all` boolean. +// +// The req's `basic{1,2,3}` triplet (1/2/1) is the wire-known +// validation cookie NTQQ emits; the server rejects requests with +// different values. `type = 0` means "query" (no other type seen). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x8a7Req, Oidb0x8a7Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export interface AtAllRemain { + can_at_all: boolean; + remain_at_all_count_for_group: number; + remain_at_all_count_for_uin: number; +} + +export namespace GetAtAllRemain { + export const command = 0x8A7; + export const subCommand = 0; + + export interface Params { groupId: number; } + + export type Deps = OidbSender & Pick; + + export const serialize = (ctx: Deps, p: Params): Oidb0x8a7Req => ({ + basic1: 1, + basic2: 2, + basic3: 1, + uin: BigInt(ctx.identity.uin), + groupId: BigInt(p.groupId), + type: 0, + }); + + export const deserialize = (_ctx: Deps, body: Oidb0x8a7Resp): AtAllRemain => { + // Cast numbers to plain Number: the OIDB layer may surface uint32 + // as BigInt and the WebUI JSON serializer chokes on those. + return { + can_at_all: !!body.canAtAll, + remain_at_all_count_for_group: Number(body.groupRemain ?? 0), + remain_at_all_count_for_uin: Number(body.uinRemain ?? 0), + }; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetAtAllRemain, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/kick-member.ts b/packages/protocol/src/oidb-services/group-admin/kick-member.ts new file mode 100644 index 00000000..3c23365f --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/kick-member.ts @@ -0,0 +1,42 @@ +// 0x8A0_1 — single-member kick. The batch variant (kickMembers) uses +// the same cmd but a different proto body shape; kept as a separate +// namespace because proton needs distinct types per call site. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbKickMember } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace KickMember { + export const command = 0x8A0; + export const subCommand = 1; + + export interface Params { + groupId: number; + userId: number; + /** Reject the kicked user's future join requests. */ + reject: boolean; + reason?: string; + } + + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => ({ + groupUin: p.groupId, + targetUid: await ctx.resolveUserUid(p.userId, p.groupId), + rejectAddRequest: p.reject, + reason: p.reason ?? '', + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, KickMember, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/kick-members.ts b/packages/protocol/src/oidb-services/group-admin/kick-members.ts new file mode 100644 index 00000000..e46cfa5b --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/kick-members.ts @@ -0,0 +1,41 @@ +// 0x8A0_1 — batch member kick (repeated targetUids). Same cmd+subcmd +// as KickMember (single) but a different proto body shape; separate +// namespace so proton can monomorphize independently. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x8a0Req } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace KickMembers { + export const command = 0x8A0; + export const subCommand = 1; + + export interface Params { + groupId: number; + userIds: number[]; + reject: boolean; + } + + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => ({ + groupId: BigInt(p.groupId), + targetUids: await Promise.all(p.userIds.map(uid => ctx.resolveUserUid(uid, p.groupId))), + rejectAddRequest: p.reject ? 1 : 0, + kickReason: new Uint8Array(0), + field12: 0, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, KickMembers, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/leave-group.ts b/packages/protocol/src/oidb-services/group-admin/leave-group.ts new file mode 100644 index 00000000..f32fab0c --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/leave-group.ts @@ -0,0 +1,23 @@ +// 0x1097_1 — leave a group (退群). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbLeaveGroup } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace LeaveGroup { + export const command = 0x1097; + export const subCommand = 1; + + export interface Params { groupId: number; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbLeaveGroup => ({ groupUin: p.groupId }); + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, LeaveGroup, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/mute-all.ts b/packages/protocol/src/oidb-services/group-admin/mute-all.ts new file mode 100644 index 00000000..f057421b --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/mute-all.ts @@ -0,0 +1,34 @@ +// 0x89A_0 — toggle group全员禁言. `state` is the duration multiplier +// (0xFFFFFFFF for permanent mute, 0 for unmute). Multiple OIDB cmds +// share the (0x89A, 0) tuple — see also SetAddOption / SetSearch / +// SetName — disambiguated by the body proto shape. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbMuteAll } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace MuteAll { + export const command = 0x89A; + export const subCommand = 0; + + export interface Params { groupId: number; enable: boolean; } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbMuteAll => ({ + groupUin: p.groupId, + muteState: { state: p.enable ? 0xFFFFFFFF : 0 }, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, MuteAll, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/mute-member.ts b/packages/protocol/src/oidb-services/group-admin/mute-member.ts new file mode 100644 index 00000000..5c983c80 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/mute-member.ts @@ -0,0 +1,36 @@ +// 0x1253_1 — mute a single group member for `duration` seconds. +// Server treats duration = 0 as "unmute now". + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbMuteMember } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace MuteMember { + export const command = 0x1253; + export const subCommand = 1; + + export interface Params { groupId: number; userId: number; duration: number; } + + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => ({ + groupUin: p.groupId, type: 1, + body: { + targetUid: await ctx.resolveUserUid(p.userId, p.groupId), + duration: p.duration, + }, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, MuteMember, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/set-add-option.ts b/packages/protocol/src/oidb-services/group-admin/set-add-option.ts new file mode 100644 index 00000000..3c36f1cb --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/set-add-option.ts @@ -0,0 +1,34 @@ +// 0x89A_0 — set group "how to join" option (anyone / verification / +// owner-only / etc). Same cmd+subcmd as MuteAll / SetSearch / SetName +// — disambiguated by the body proto shape. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x89a_0AddOption } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace SetAddOption { + export const command = 0x89A; + export const subCommand = 0; + + export interface Params { groupId: number; addType: number; } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): Oidb0x89a_0AddOption => ({ + groupUin: BigInt(p.groupId), + settings: { addType: p.addType }, + field12: 0, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetAddOption, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/set-add-request.ts b/packages/protocol/src/oidb-services/group-admin/set-add-request.ts new file mode 100644 index 00000000..98da863d --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/set-add-request.ts @@ -0,0 +1,49 @@ +// 0x10C8 — approve/reject a pending group join request. +// subCommand 1 = main inbox, 2 = filtered inbox +// +// `uinForm=true` matches the request shape NTQQ emits. `accept: 1` +// is the server discriminator for approve; `2` for reject. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupRequestAction } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace SetAddRequest { + export const command = 0x10C8; + export const uinForm = true; + + export interface Params { + groupId: number; + sequence: number; + eventType: number; + approve: boolean; + reason?: string; + filtered?: boolean; + } + + export type Deps = OidbSender; + + export const resolveSubCommand = (p: Params): number => p.filtered ? 2 : 1; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupRequestAction => ({ + accept: p.approve ? 1 : 2, + body: { + sequence: BigInt(p.sequence), + eventType: p.eventType, + groupUin: p.groupId, + message: p.reason ?? '', + }, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetAddRequest, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/set-admin.ts b/packages/protocol/src/oidb-services/group-admin/set-admin.ts new file mode 100644 index 00000000..9a0ff51d --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/set-admin.ts @@ -0,0 +1,30 @@ +// 0x1096_1 — promote / demote a member to/from group administrator. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbSetAdmin } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SetAdmin { + export const command = 0x1096; + export const subCommand = 1; + + export interface Params { groupId: number; userId: number; enable: boolean; } + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => ({ + groupUin: p.groupId, + uid: await ctx.resolveUserUid(p.userId, p.groupId), + isAdmin: p.enable, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetAdmin, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/set-group-name.ts b/packages/protocol/src/oidb-services/group-admin/set-group-name.ts new file mode 100644 index 00000000..774b81ac --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/set-group-name.ts @@ -0,0 +1,27 @@ +// 0x89A_15 — rename the group. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbRenameGroup } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace SetGroupName { + export const command = 0x89A; + export const subCommand = 15; + + export interface Params { groupId: number; name: string; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbRenameGroup => ({ + groupUin: p.groupId, body: { targetName: p.name }, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetGroupName, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/set-group-remark.ts b/packages/protocol/src/oidb-services/group-admin/set-group-remark.ts new file mode 100644 index 00000000..720fad54 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/set-group-remark.ts @@ -0,0 +1,29 @@ +// 0xF16_1 — set the bot's local-only label/remark for a group (only +// the bot sees this — the group's actual name is untouched). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { Oidb0xf16Req } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace SetGroupRemark { + export const command = 0xF16; + export const subCommand = 1; + + export interface Params { groupId: number; remark: string; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): Oidb0xf16Req => ({ + inner: { groupId: BigInt(p.groupId), remark: p.remark }, + field12: 0, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetGroupRemark, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/set-member-card.ts b/packages/protocol/src/oidb-services/group-admin/set-member-card.ts new file mode 100644 index 00000000..38436bb4 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/set-member-card.ts @@ -0,0 +1,32 @@ +// 0x8FC_3 — set a member's group-card (群名片). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbRenameMember } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SetMemberCard { + export const command = 0x8FC; + export const subCommand = 3; + + export interface Params { groupId: number; userId: number; card: string; } + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => ({ + groupUin: p.groupId, + body: { + targetUid: await ctx.resolveUserUid(p.userId, p.groupId), + targetName: p.card, + }, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetMemberCard, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/set-search.ts b/packages/protocol/src/oidb-services/group-admin/set-search.ts new file mode 100644 index 00000000..36352467 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/set-search.ts @@ -0,0 +1,33 @@ +// 0x89A_0 — toggle group "searchable" flag. Same cmd+subcmd shape as +// MuteAll / SetAddOption / SetName. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x89a_0Search } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace SetSearch { + export const command = 0x89A; + export const subCommand = 0; + + export interface Params { groupId: number; } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): Oidb0x89a_0Search => ({ + groupUin: BigInt(p.groupId), + settings: new Uint8Array(0), + field12: 0, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetSearch, params); +} diff --git a/packages/protocol/src/oidb-services/group-admin/set-special-title.ts b/packages/protocol/src/oidb-services/group-admin/set-special-title.ts new file mode 100644 index 00000000..b4ddf63e --- /dev/null +++ b/packages/protocol/src/oidb-services/group-admin/set-special-title.ts @@ -0,0 +1,34 @@ +// 0x8FC_2 — assign a member a "special title" (群头衔). `expireTime=-1` +// is the wire constant for "permanent". + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbSpecialTitle } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SetSpecialTitle { + export const command = 0x8FC; + export const subCommand = 2; + + export interface Params { groupId: number; userId: number; title: string; } + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => ({ + groupUin: p.groupId, + body: { + targetUid: await ctx.resolveUserUid(p.userId, p.groupId), + specialTitle: p.title, + expireTime: -1, + }, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetSpecialTitle, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/create-group-folder.ts b/packages/protocol/src/oidb-services/group-file/create-group-folder.ts new file mode 100644 index 00000000..d35f382b --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/create-group-folder.ts @@ -0,0 +1,42 @@ +// 0x6D7_0 — create a sub-folder under `parentId` in the group file +// hierarchy. parentId='/' is the root. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileFolderReq, OidbGroupFileFolderResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero } from '../shared'; + +export namespace CreateGroupFolder { + export const command = 0x6D7; + export const subCommand = 0; + export const uinForm = true; + + export interface Params { groupId: number; parentId: string; folderName: string; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupFileFolderReq => ({ + create: { + groupUin: p.groupId, + rootDirectory: p.parentId, + folderName: p.folderName, + }, + }); + + export const deserialize = (_ctx: Deps, body: OidbGroupFileFolderResp): void => { + const result = body.create; + if (!result) throw new Error('group folder create response missing'); + ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording); + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, CreateGroupFolder, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/delete-group-file.ts b/packages/protocol/src/oidb-services/group-file/delete-group-file.ts new file mode 100644 index 00000000..bc306329 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/delete-group-file.ts @@ -0,0 +1,41 @@ +// 0x6D6_3 — delete a single group file by id. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileReq, OidbGroupFileResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero } from '../shared'; + +export namespace DeleteGroupFile { + export const command = 0x6D6; + export const subCommand = 3; + export const uinForm = true; + + export interface Params { groupId: number; fileId: string; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupFileReq => ({ + delete: { + groupUin: p.groupId, + busId: 102, + fileId: p.fileId, + }, + }); + + export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): void => { + const result = body.delete; + if (!result) throw new Error('group file delete response missing'); + ensureRetCodeZero('group file delete', result.retCode, result.retMsg, result.clientWording); + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, DeleteGroupFile, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/delete-group-folder.ts b/packages/protocol/src/oidb-services/group-file/delete-group-folder.ts new file mode 100644 index 00000000..2416d5f4 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/delete-group-folder.ts @@ -0,0 +1,38 @@ +// 0x6D7_1 — delete a group folder by id (any files inside are +// orphaned; UI sometimes pre-empties first via per-file deletes). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileFolderReq, OidbGroupFileFolderResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero } from '../shared'; + +export namespace DeleteGroupFolder { + export const command = 0x6D7; + export const subCommand = 1; + export const uinForm = true; + + export interface Params { groupId: number; folderId: string; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupFileFolderReq => ({ + delete: { groupUin: p.groupId, folderId: p.folderId }, + }); + + export const deserialize = (_ctx: Deps, body: OidbGroupFileFolderResp): void => { + const result = body.delete; + if (!result) throw new Error('group folder delete response missing'); + ensureRetCodeZero('group folder delete', result.retcode, result.retMsg, result.clientWording); + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, DeleteGroupFolder, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/get-group-file-count.ts b/packages/protocol/src/oidb-services/group-file/get-group-file-count.ts new file mode 100644 index 00000000..5f48735b --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/get-group-file-count.ts @@ -0,0 +1,42 @@ +// 0x6D8_3 — fetch group file slot usage. Returns the current count +// alongside the server-side ceiling (NTQQ's `maxCount` default is +// 10000; we surface that fallback so the OneBot action can render +// the gauge without a second call when the server elides the field). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileCountViewReq, OidbGroupFileCountViewResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export interface GroupFileCount { + fileCount: number; + maxCount: number; +} + +export namespace GetGroupFileCount { + export const command = 0x6D8; + export const subCommand = 3; + + export interface Params { groupId: number; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupFileCountViewReq => ({ + count: { groupUin: p.groupId, appId: 7, busId: 0 }, + }); + + export const deserialize = (_ctx: Deps, body: OidbGroupFileCountViewResp): GroupFileCount => ({ + fileCount: Number(body.count?.fileCount ?? 0), + maxCount: Number(body.count?.maxCount ?? 10000), + }); + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetGroupFileCount, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/get-group-file-url.ts b/packages/protocol/src/oidb-services/group-file/get-group-file-url.ts new file mode 100644 index 00000000..30d271aa --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/get-group-file-url.ts @@ -0,0 +1,44 @@ +// 0x6D6_2 — resolve a group file_id → ftn_handler download URL. The +// server returns a `downloadUrl` blob (raw bytes that hex-encode the +// download key) and a `downloadDns` host. The facade composes the +// final `https:///ftn_handler//?fname=` string. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileReq, OidbGroupFileResp, OidbGroupFileDownloadResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace GetGroupFileUrl { + export const command = 0x6D6; + export const subCommand = 2; + export const uinForm = true; + + export interface Params { groupId: number; fileId: string; busId: number; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupFileReq => ({ + download: { + groupUin: p.groupId, + appId: 7, + busId: p.busId, + fileId: p.fileId, + }, + }); + + export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): OidbGroupFileDownloadResp => { + const download = body.download; + if (!download) throw new Error('group file url response missing'); + return download; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetGroupFileUrl, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/get-group-ptt-url.ts b/packages/protocol/src/oidb-services/group-file/get-group-ptt-url.ts new file mode 100644 index 00000000..01e493f7 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/get-group-ptt-url.ts @@ -0,0 +1,49 @@ +// 0x126E_200 — fetch a download URL for a group-scope rich-media node +// (voice in this case — busiType=3 means "ptt/voice", sceneType=2 +// means group). Pairs with the c2c-scope variant `GetPrivatePttUrl` +// (0x126D_200) which only differs in scene. + +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { + normalizeMediaNode, parseNtv2DownloadUrl, type NtMediaIndex, +} from './ntv2-download'; + +export namespace GetGroupPttUrl { + export const command = 0x126E; + export const subCommand = 200; + export const uinForm = true; + + export interface Params { groupId: number; node: NtMediaIndex; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): NTV2RichMediaReq => ({ + reqHead: { + common: { requestId: 4, command: 200 }, + scene: { + requestType: 1, + businessType: 3, + sceneType: 2, + group: { groupUin: p.groupId }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizeMediaNode(p.node), + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); + + export const deserialize = (_ctx: Deps, body: NTV2RichMediaResp): string => parseNtv2DownloadUrl(body); + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetGroupPttUrl, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/get-group-video-url.ts b/packages/protocol/src/oidb-services/group-file/get-group-video-url.ts new file mode 100644 index 00000000..98a64b37 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/get-group-video-url.ts @@ -0,0 +1,48 @@ +// 0x11EA_200 — video URL fetch, group scope. Same envelope shape as +// GetGroupPttUrl; `requestType=2 + businessType=2` swaps voice for +// video. The scene's `group` block carries the group uin. + +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { + normalizeMediaNode, parseNtv2DownloadUrl, type NtMediaIndex, +} from './ntv2-download'; + +export namespace GetGroupVideoUrl { + export const command = 0x11EA; + export const subCommand = 200; + export const uinForm = true; + + export interface Params { groupId: number; node: NtMediaIndex; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): NTV2RichMediaReq => ({ + reqHead: { + common: { requestId: 1, command: 200 }, + scene: { + requestType: 2, + businessType: 2, + sceneType: 2, + group: { groupUin: p.groupId }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizeMediaNode(p.node), + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); + + export const deserialize = (_ctx: Deps, body: NTV2RichMediaResp): string => parseNtv2DownloadUrl(body); + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetGroupVideoUrl, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/get-private-file-url.ts b/packages/protocol/src/oidb-services/group-file/get-private-file-url.ts new file mode 100644 index 00000000..50ea9750 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/get-private-file-url.ts @@ -0,0 +1,56 @@ +// 0xE37_1200 — resolve a private (c2c) file_id → http download URL. +// Carries an opaque 4-byte `field99999` magic the server's deserializer +// requires (Lagrange has the same constant). The facade composes the +// final `http://:&isthumb=0` string. +// +// 5s timeout matches the original facade — the server batches these +// at low priority and stalls past the default 30s. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbPrivateFileDownloadReq, OidbPrivateFileDownloadResp, + OidbPrivateFileDownloadRespResult, +} from '@snowluma/proto-defs/oidb-actions/media'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +const TIMEOUT_MS = 5000; + +export namespace GetPrivateFileUrl { + export const command = 0xE37; + export const subCommand = 1200; + + export interface Params { selfUid: string; fileId: string; fileHash: string; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbPrivateFileDownloadReq => ({ + subCommand: 1200, + field2: 1, + body: { + receiverUid: p.selfUid, + fileUuid: p.fileId, + type: 2, + fileHash: p.fileHash, + t2: 0, + }, + field101: 3, + field102: 103, + field200: 1, + field99999: new Uint8Array([0xC0, 0x85, 0x2C, 0x01]), + }); + + export const deserialize = (_ctx: Deps, body: OidbPrivateFileDownloadResp): OidbPrivateFileDownloadRespResult => { + const result = body.body?.result; + if (!result) throw new Error('private file url response invalid'); + return result; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetPrivateFileUrl, params, TIMEOUT_MS); +} diff --git a/packages/protocol/src/oidb-services/group-file/get-private-ptt-url.ts b/packages/protocol/src/oidb-services/group-file/get-private-ptt-url.ts new file mode 100644 index 00000000..bef732e5 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/get-private-ptt-url.ts @@ -0,0 +1,48 @@ +// 0x126D_200 — c2c-scope counterpart of GetGroupPttUrl. Same shape, +// `scene` is `c2c` rather than `group`. Needs the bot's own uid to +// fill the c2c.targetUid slot. + +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { + normalizeMediaNode, parseNtv2DownloadUrl, type NtMediaIndex, +} from './ntv2-download'; + +export namespace GetPrivatePttUrl { + export const command = 0x126D; + export const subCommand = 200; + export const uinForm = true; + + export interface Params { selfUid: string; node: NtMediaIndex; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): NTV2RichMediaReq => ({ + reqHead: { + common: { requestId: 1, command: 200 }, + scene: { + requestType: 1, + businessType: 3, + sceneType: 1, + c2c: { accountType: 2, targetUid: p.selfUid }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizeMediaNode(p.node), + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); + + export const deserialize = (_ctx: Deps, body: NTV2RichMediaResp): string => parseNtv2DownloadUrl(body); + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetPrivatePttUrl, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/get-private-video-url.ts b/packages/protocol/src/oidb-services/group-file/get-private-video-url.ts new file mode 100644 index 00000000..2ddd6bc2 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/get-private-video-url.ts @@ -0,0 +1,48 @@ +// 0x11E9_200 — c2c-scope video URL fetch (pair of GetGroupVideoUrl). +// `scene.c2c.targetUid` is the bot's own uid; the server uses it as +// the read-side identity for the asset lookup. + +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { + normalizeMediaNode, parseNtv2DownloadUrl, type NtMediaIndex, +} from './ntv2-download'; + +export namespace GetPrivateVideoUrl { + export const command = 0x11E9; + export const subCommand = 200; + export const uinForm = true; + + export interface Params { selfUid: string; node: NtMediaIndex; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): NTV2RichMediaReq => ({ + reqHead: { + common: { requestId: 1, command: 200 }, + scene: { + requestType: 2, + businessType: 2, + sceneType: 1, + c2c: { accountType: 2, targetUid: p.selfUid }, + }, + client: { agentType: 2 }, + }, + download: { + node: normalizeMediaNode(p.node), + download: { video: { busiType: 0, sceneType: 0 } }, + }, + }); + + export const deserialize = (_ctx: Deps, body: NTV2RichMediaResp): string => parseNtv2DownloadUrl(body); + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetPrivateVideoUrl, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/list-group-files-page.ts b/packages/protocol/src/oidb-services/group-file/list-group-files-page.ts new file mode 100644 index 00000000..9f8199ea --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/list-group-files-page.ts @@ -0,0 +1,55 @@ +// 0x6D8_1 — ONE page of the group-file listing under `targetDirectory`. +// Paginated; the facade loops this until `isEnd=true` or the page cap +// is hit. Each page yields a mix of files (`type=1`) and folders +// (`type=2`); the caller flattens them. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileViewReq, OidbGroupFileViewResp, OidbGroupFileListResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace ListGroupFilesPage { + export const command = 0x6D8; + export const subCommand = 1; + export const uinForm = true; + + export interface Params { + groupId: number; + targetDirectory: string; + startIndex: number; + pageSize: number; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupFileViewReq => ({ + list: { + groupUin: p.groupId, + appId: 7, + targetDirectory: p.targetDirectory, + fileCount: p.pageSize, + sortBy: 1, + startIndex: p.startIndex, + field17: 2, + field18: 0, + }, + }); + + /** Returns the list body directly so the facade can inspect + * `items`, `isEnd`, and `retCode` in one place. Returns null when + * the server elides the list entirely (end-of-stream sentinel). */ + export const deserialize = (_ctx: Deps, body: OidbGroupFileViewResp): OidbGroupFileListResp | null => { + return body.list ?? null; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, ListGroupFilesPage, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/move-group-file.ts b/packages/protocol/src/oidb-services/group-file/move-group-file.ts new file mode 100644 index 00000000..b3a80daf --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/move-group-file.ts @@ -0,0 +1,47 @@ +// 0x6D6_5 — move a group file between folders. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileReq, OidbGroupFileResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero } from '../shared'; + +export namespace MoveGroupFile { + export const command = 0x6D6; + export const subCommand = 5; + export const uinForm = true; + + export interface Params { + groupId: number; fileId: string; + parentDirectory: string; targetDirectory: string; + } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupFileReq => ({ + move: { + groupUin: p.groupId, + appId: 7, + busId: 102, + fileId: p.fileId, + parentDirectory: p.parentDirectory, + targetDirectory: p.targetDirectory, + }, + }); + + export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): void => { + const result = body.move; + if (!result) throw new Error('group file move response missing'); + ensureRetCodeZero('group file move', result.retCode, result.retMsg, result.clientWording); + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, MoveGroupFile, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/ntv2-download.ts b/packages/protocol/src/oidb-services/group-file/ntv2-download.ts new file mode 100644 index 00000000..f34a9be4 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/ntv2-download.ts @@ -0,0 +1,87 @@ +// Shared deserializer for the four NTV2-rich-media URL fetchers: +// - get-group-ptt-url (0x126E_200) +// - get-private-ptt-url (0x126D_200) +// - get-group-video-url (0x11EA_200) +// - get-private-video-url (0x11E9_200) +// +// All four hit the `MultiMedia.OidbSvc.0x...` family with the same +// `NTV2RichMediaReq` shape; only the `scene` block + the wire cmd +// differ. The response is parsed into a `domain + urlPath + +// rKeyParam` triple → composed into `https://`. + +import type { NTV2IndexNode, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; +import { ensureRetCodeZero } from '../shared'; + +export function parseNtv2DownloadUrl(body: NTV2RichMediaResp): string { + ensureRetCodeZero('ntv2 download', body.respHead?.retCode, body.respHead?.message, undefined); + const domain = typeof body.download?.info?.domain === 'string' ? body.download.info.domain : ''; + const path = typeof body.download?.info?.urlPath === 'string' ? body.download.info.urlPath : ''; + const rKeyParam = typeof body.download?.rKeyParam === 'string' ? body.download.rKeyParam : ''; + if (!domain || !path) throw new Error('ntv2 download response invalid'); + return `https://${domain}${path}${rKeyParam}`; +} + +/** Normalize a MediaIndexNode-shaped object into the wire-fields the + * NTV2RichMedia `download.node` slot expects: `info{...}` / + * `fileUuid` / `storeId` / `uploadTime` / `ttl` / `subType`. */ +export function normalizeMediaNode(node: NtMediaIndex): NTV2IndexNode { + const fileUuid = typeof node.fileUuid === 'string' ? node.fileUuid : ''; + if (!fileUuid) throw new Error('media node fileUuid is required'); + + const info = node.info ?? {}; + const type = info.type ?? {}; + + return { + info: { + fileSize: toInt(info.fileSize), + fileHash: typeof info.fileHash === 'string' ? info.fileHash : '', + fileSha1: typeof info.fileSha1 === 'string' ? info.fileSha1 : '', + fileName: typeof info.fileName === 'string' ? info.fileName : '', + type: { + type: toInt(type.type), + picFormat: toInt(type.picFormat), + videoFormat: toInt(type.videoFormat), + voiceFormat: toInt(type.voiceFormat), + }, + width: toInt(info.width), + height: toInt(info.height), + time: toInt(info.time), + original: toInt(info.original), + }, + fileUuid, + storeId: toInt(node.storeId), + uploadTime: toInt(node.uploadTime), + ttl: toInt(node.ttl), + subType: toInt(node.subType), + }; +} + +function toInt(value: unknown): number { + if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); + if (typeof value === 'bigint') return Number(value); + return 0; +} + +export interface NtMediaIndex { + info?: { + fileSize?: number; + fileHash?: string; + fileSha1?: string; + fileName?: string; + width?: number; + height?: number; + time?: number; + original?: number; + type?: { + type?: number; + picFormat?: number; + videoFormat?: number; + voiceFormat?: number; + }; + }; + fileUuid?: string; + storeId?: number; + uploadTime?: number; + ttl?: number; + subType?: number; +} diff --git a/packages/protocol/src/oidb-services/group-file/publish-group-file.ts b/packages/protocol/src/oidb-services/group-file/publish-group-file.ts new file mode 100644 index 00000000..e2f2b4e3 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/publish-group-file.ts @@ -0,0 +1,47 @@ +// 0x6D9_4 — publish a previously-uploaded group file as a chat +// message (the file-bubble in the group transcript). +// +// The QQ-NT server rejects the legacy `TransElem(elemType=24)` payload +// on outgoing send (`result=79`) so the file-publish path goes via a +// dedicated OIDB hop instead of `MessageSvc.PbSendMsg`. Mirror +// Lagrange.Core V2's `GroupSendFileService.cs`: +// - `info.field3` is a 31-bit random — Lagrange does `Random.Shared.Next()` +// - `info.field5 = true` is the discriminator the server's deserializer +// expects to recognise this branch. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupSendFileReq } from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace PublishGroupFile { + export const command = 0x6D9; + export const subCommand = 4; + + export interface Params { groupId: number; fileId: string; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupSendFileReq => ({ + body: { + groupUin: p.groupId, + type: 2, + info: { + busiType: 102, + fileId: p.fileId, + field3: Math.floor(Math.random() * 0x7fffffff) >>> 0, + field5: true, + }, + }, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, PublishGroupFile, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/rename-group-folder.ts b/packages/protocol/src/oidb-services/group-file/rename-group-folder.ts new file mode 100644 index 00000000..3ef38648 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/rename-group-folder.ts @@ -0,0 +1,43 @@ +// 0x6D7_2 — rename a group folder. Note the wire field is +// `newFolderName` (not `folderName`); the rename slot lives on the +// shared `OidbGroupFileFolderReq` envelope. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileFolderReq, OidbGroupFileFolderResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero } from '../shared'; + +export namespace RenameGroupFolder { + export const command = 0x6D7; + export const subCommand = 2; + export const uinForm = true; + + export interface Params { groupId: number; folderId: string; newFolderName: string; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupFileFolderReq => ({ + rename: { + groupUin: p.groupId, + folderId: p.folderId, + newFolderName: p.newFolderName, + }, + }); + + export const deserialize = (_ctx: Deps, body: OidbGroupFileFolderResp): void => { + const result = body.rename; + if (!result) throw new Error('group folder rename response missing'); + ensureRetCodeZero('group folder rename', result.retcode, result.retMsg, result.clientWording); + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, RenameGroupFolder, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/upload-group-file-request.ts b/packages/protocol/src/oidb-services/group-file/upload-group-file-request.ts new file mode 100644 index 00000000..5ffc1cd1 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/upload-group-file-request.ts @@ -0,0 +1,69 @@ +// 0x6D6_0 — group-file upload preflight. Hands the server the file +// metadata + hashes and gets back: +// - `boolFileExist` — if true, the bytes are already on the server +// and the highway step is skipped +// - `fileId` — the persistent id used by `publish` (0x6D9_4) and +// later download/delete/move calls +// - upload host/port + the `fileKey`/`checkKey` blob the highway +// PUT needs in its FileUploadExt envelope +// +// This namespace ONLY does the preflight; the highway PUT and the +// follow-on `publish` chat-message hop live on the facade because +// they're orchestration (highway client, ext blob composition) that +// doesn't fit a single OIDB call boundary. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileReq, OidbGroupFileResp, OidbGroupFileUploadResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace UploadGroupFileRequest { + export const command = 0x6D6; + export const subCommand = 0; + export const uinForm = true; + + export interface Params { + groupId: number; + fileName: string; + folderId: string; + fileSize: number; + fileSha1: Uint8Array; + fileMd5: Uint8Array; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupFileReq => ({ + file: { + groupUin: p.groupId, + appId: 4, + busId: 102, + entrance: 6, + targetDirectory: p.folderId, + fileName: p.fileName, + localDirectory: `/${p.fileName}`, + fileSize: BigInt(p.fileSize), + fileSha1: p.fileSha1, + fileSha3: new Uint8Array(0), + fileMd5: p.fileMd5, + field15: true, + }, + }); + + export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): OidbGroupFileUploadResp => { + const upload = body.upload; + if (!upload) throw new Error('group file upload response missing'); + return upload; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, UploadGroupFileRequest, params); +} diff --git a/packages/protocol/src/oidb-services/group-file/upload-private-file-request.ts b/packages/protocol/src/oidb-services/group-file/upload-private-file-request.ts new file mode 100644 index 00000000..4d1b4579 --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/upload-private-file-request.ts @@ -0,0 +1,70 @@ +// 0xE37_1700 — private (c2c) file upload preflight. Server returns +// the same shape of upload-host info as the group-file path but the +// fields are laid out differently (rtpMediaPlatformUploadAddress is +// the primary host source on current QQ-NT; legacy `uploadIp` / +// `uploadDomain` / `uploadIpList[]` are fallbacks). +// +// As with the group-file preflight, this namespace ONLY does the +// preflight; the highway PUT and the follow-on `sendC2cFile` chat +// hop live on the facade. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbPrivateFileUploadReq, OidbPrivateFileUploadResp, + OidbPrivateFileUploadRespBody, +} from '@snowluma/proto-defs/oidb-actions/media'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace UploadPrivateFileRequest { + export const command = 0xE37; + export const subCommand = 1700; + + export interface Params { + senderUid: string; + receiverUid: string; + fileName: string; + fileSize: number; + fileSha1: Uint8Array; + fileMd5: Uint8Array; + /** md5 over the first 10 MiB; caller passes this in because we + * can't redo the hash here without re-reading the source. */ + md510MCheckSum: Uint8Array; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbPrivateFileUploadReq => ({ + command: 1700, + seq: 0, + upload: { + senderUid: p.senderUid, + receiverUid: p.receiverUid, + fileSize: p.fileSize, + fileName: p.fileName, + md510MCheckSum: p.md510MCheckSum, + sha1CheckSum: p.fileSha1, + localPath: '/', + md5CheckSum: p.fileMd5, + sha3CheckSum: new Uint8Array(0), + }, + businessId: 3, + clientType: 1, + flagSupportMediaPlatform: 1, + }); + + export const deserialize = (_ctx: Deps, body: OidbPrivateFileUploadResp): OidbPrivateFileUploadRespBody => { + const upload = body.upload; + if (!upload) throw new Error('private file upload response missing'); + return upload; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, UploadPrivateFileRequest, params); +} diff --git a/packages/protocol/src/oidb-services/interaction/send-like.ts b/packages/protocol/src/oidb-services/interaction/send-like.ts new file mode 100644 index 00000000..278daa0c --- /dev/null +++ b/packages/protocol/src/oidb-services/interaction/send-like.ts @@ -0,0 +1,56 @@ +// 0x7E5_104 — send "thumbs up" (赞) to another user (profile-card 点赞). +// +// Wire shape lives at fields 11/12/13 with a uid (NOT uin) target and a +// fixed `sourceId = 71` marker for the profile-card entry point. The +// server rejects uin-form payloads with "被点赞 QQ 号非法", so we resolve +// uin → uid through the identity service before encoding. +// +// `count` is the number of likes in this single call (QQ allows 1–20 +// batched). Server caps daily quotas separately. +// +// Upstream parity: +// - Lagrange.Core `OidbSvcTrpcTcp0x7E5_104` (fields 11/12/13): +// dev/Lagrange.Core/.../Service/Oidb/Request/OidbSvcTrpcTcp0x7E5_104.cs:14-18 +// - Lagrange.Core `FriendLikeService` (always emits `Field2 = 71`): +// dev/Lagrange.Core/.../Service/Action/FriendLikeService.cs:18-23 +// - NapCat `UserApi.like` (`setBuddyProfileLike` with sourceId 71): +// dev/NapCatQQ/packages/napcat-core/apis/user.ts:63-70 + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbLike } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SendLike { + export const command = 0x7E5; + export const subCommand = 104; + + export interface Params { + userId: number; + count: number; + } + + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => { + const targetUid = await ctx.resolveUserUid(p.userId); + if (!targetUid) throw new Error(`failed to resolve uid for ${p.userId}`); + return { + targetUid, + sourceId: 71, + count: p.count, + }; + }; + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SendLike, params); +} diff --git a/packages/protocol/src/oidb-services/interaction/send-poke.ts b/packages/protocol/src/oidb-services/interaction/send-poke.ts new file mode 100644 index 00000000..bf0bf1b9 --- /dev/null +++ b/packages/protocol/src/oidb-services/interaction/send-poke.ts @@ -0,0 +1,48 @@ +// 0xED3_1 — group / friend poke (the "戳一戳" / "拍一拍" notice). +// +// Same envelope shape for both flavors; the discriminator is which of +// `groupUin` / `friendUin` is set: +// - group poke: groupUin = peer (the group), friendUin = 0, +// uin = targetUin (the member being poked) or peer +// - friend poke: groupUin = 0, friendUin = peer (the friend's uin), +// uin = targetUin or peer +// `ext` is always 0; QQ-NT uses it for "double-poke" / "shake" subtypes +// that SnowLuma hasn't exposed yet. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbPoke } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace SendPoke { + export const command = 0xED3; + export const subCommand = 1; + + export interface Params { + isGroup: boolean; + /** Group uin (if isGroup) or friend uin (otherwise). */ + peerUin: number; + /** Specific member to poke in a group; defaults to peer for friend pokes. */ + targetUin?: number; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbPoke => ({ + uin: p.targetUin ?? p.peerUin, + groupUin: p.isGroup ? p.peerUin : 0, + friendUin: p.isGroup ? 0 : p.peerUin, + ext: 0, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SendPoke, params); +} diff --git a/packages/protocol/src/oidb-services/interaction/set-essence.ts b/packages/protocol/src/oidb-services/interaction/set-essence.ts new file mode 100644 index 00000000..8e3b0f64 --- /dev/null +++ b/packages/protocol/src/oidb-services/interaction/set-essence.ts @@ -0,0 +1,44 @@ +// 0xEAC — set / unset a group "essence" message (群精华). +// subCommand 1 = mark as essence, 2 = remove from essence +// +// `random` is the message's wire-level random field (carried through +// from the original send so the server can resolve the canonical +// message identity). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbEssence } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace SetEssence { + export const command = 0xEAC; + + export interface Params { + groupId: number; + sequence: number; + random: number; + /** true = mark essence (subCmd 1), false = unmark (subCmd 2). */ + enable: boolean; + } + + export type Deps = OidbSender; + + export const resolveSubCommand = (p: Params): number => p.enable ? 1 : 2; + + export const serialize = (_ctx: Deps, p: Params): OidbEssence => ({ + groupUin: p.groupId, + sequence: p.sequence, + random: p.random, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetEssence, params); +} diff --git a/packages/protocol/src/oidb-services/misc/click-inline-keyboard-button.ts b/packages/protocol/src/oidb-services/misc/click-inline-keyboard-button.ts new file mode 100644 index 00000000..2df425b4 --- /dev/null +++ b/packages/protocol/src/oidb-services/misc/click-inline-keyboard-button.ts @@ -0,0 +1,61 @@ +// 0x112E_1 — relay an inline-keyboard-button click event to the bot +// owning the button (so the bot can react). All identity fields go on +// the wire as uint_64 → callers pass JS numbers and we widen here. + +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x112eReq, Oidb0x112eResp } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export interface InlineButtonClickResult { + [key: string]: import('@snowluma/common/json').JsonValue; + result: number; + errMsg: string; + status: 0; + promptText: string; + promptType: 0; + promptIcon: 0; +} + +export namespace ClickInlineKeyboardButton { + export const command = 0x112E; + export const subCommand = 1; + + export interface Params { + groupId: number; + botAppid: number; + buttonId: string; + callbackData: string; + msgSeq: number; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): Oidb0x112eReq => ({ + botAppid: BigInt(p.botAppid), + msgSeq: BigInt(p.msgSeq), + buttonId: String(p.buttonId), + callbackData: String(p.callbackData || ''), + unknown7: 0, + groupId: BigInt(p.groupId), + unknown9: 1, + }); + + export const deserialize = (_ctx: Deps, body: Oidb0x112eResp): InlineButtonClickResult => ({ + result: Number(body.result || 0), + errMsg: body.errMsg || '', + status: 0, + promptText: body.promptText || '', + promptType: 0, + promptIcon: 0, + }); + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, ClickInlineKeyboardButton, params); +} diff --git a/packages/protocol/src/oidb-services/misc/send-group-sign.ts b/packages/protocol/src/oidb-services/misc/send-group-sign.ts new file mode 100644 index 00000000..481d54a3 --- /dev/null +++ b/packages/protocol/src/oidb-services/misc/send-group-sign.ts @@ -0,0 +1,48 @@ +// 0xEB7_1 — group daily sign-in (群打卡). +// +// **Wire name case**: historically SnowLuma sent this cmd as +// `OidbSvcTrpcTcp.0xEB7_1` (uppercase EB7) while every other cmd uses +// lowercase. The server accepts either, but the refactor's hard rule +// is "wire-byte-equal to before", so we keep the uppercase via the +// `wireName` override. This is the ONLY cmd in the codebase with this +// quirk — every new cmd should use the default lowercase scheme. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0xeb7Req, Oidb0xeb7Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SendGroupSign { + export const command = 0xEB7; + export const subCommand = 1; + + /** Override the default lowercase wire-name to preserve the + * historic `OidbSvcTrpcTcp.0xEB7_1` byte-for-byte. */ + export const wireName = (): string => 'OidbSvcTrpcTcp.0xEB7_1'; + + export interface Params { + groupId: number; + } + + export type Deps = OidbSender & Pick; + + export const serialize = (ctx: Deps, p: Params): Oidb0xeb7Req => ({ + signInInfo: { + uin: String(ctx.identity.uin), + groupId: String(p.groupId), + version: '9.0.90', + }, + }); + + export const deserialize = (_ctx: Deps, _: Oidb0xeb7Resp): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SendGroupSign, params); +} diff --git a/packages/protocol/src/oidb-services/misc/translate-en-to-zh.ts b/packages/protocol/src/oidb-services/misc/translate-en-to-zh.ts new file mode 100644 index 00000000..0faeeb19 --- /dev/null +++ b/packages/protocol/src/oidb-services/misc/translate-en-to-zh.ts @@ -0,0 +1,45 @@ +// 0x990_2 — server-side English → Chinese translation. Returns the +// translated `dstWords` 1:1 paired with the input `words`. Magic +// constants `tag10=1` / `tag12=1` are documented as "always 1" in +// production traffic (purpose unknown). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x990Req, Oidb0x990Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace TranslateEnToZh { + export const command = 0x990; + export const subCommand = 2; + + export interface Params { + words: string[]; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): Oidb0x990Req => ({ + translateReq: { + srcLang: 'en', + dstLang: 'zh', + words: p.words, + }, + tag10: 1, + tag12: 1, + }); + + export const deserialize = (_ctx: Deps, body: Oidb0x990Resp): string[] => { + const resp = body.translateResp; + if (!resp) throw new Error('translate response empty'); + return resp.dstWords || []; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, TranslateEnToZh, params); +} diff --git a/packages/protocol/src/oidb-services/profile/get-like.ts b/packages/protocol/src/oidb-services/profile/get-like.ts new file mode 100644 index 00000000..ffa94118 --- /dev/null +++ b/packages/protocol/src/oidb-services/profile/get-like.ts @@ -0,0 +1,103 @@ +// 0x7ED_12 — fetch QQ "thumbs up" (赞) summary for self or another user. +// +// Self lookup needs the bot's own UID, hence the `identity` dependency. +// For other users we use `resolveUserUid` to translate the uin first. + +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x7edReq, Oidb0x7edResp } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { BridgeContext } from '../../bridge-context'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export interface LikeInfo { + [key: string]: import('@snowluma/common/json').JsonValue; + uid: string; + time: number; + favoriteInfo: { + [key: string]: import('@snowluma/common/json').JsonValue; + total_count: number; + last_time: number; + today_count: number; + userInfos: never[]; + }; + voteInfo: { + [key: string]: import('@snowluma/common/json').JsonValue; + total_count: number; + new_count: number; + new_nearby_count: number; + last_visit_time: number; + userInfos: never[]; + }; +} + +export namespace GetLike { + export const command = 0x7ED; + export const subCommand = 12; + + export interface Params { + /** Omit / 0 → query self. */ + userId?: number; + start?: number; + limit?: number; + } + + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => { + const targetUid = p.userId + ? await ctx.resolveUserUid(p.userId) + : await resolveSelf(ctx); + if (!targetUid) throw new Error('target uid not found'); + return { + targetUid, + basic: 1, + vote: 1, + favorite: 1, + start: p.start ?? 0, + limit: p.limit ?? 10, + }; + }; + + export const deserialize = (_ctx: Deps, body: Oidb0x7edResp): LikeInfo => { + const data = body.userLikeInfos?.[0]; + if (!data) throw new Error('get profile like info empty'); + return { + uid: data.uid ?? '', + time: Number(data.time ?? 0), + favoriteInfo: { + total_count: data.favoriteInfo?.totalCount || 0, + last_time: Number(data.favoriteInfo?.lastTime || 0), + today_count: data.favoriteInfo?.newCount || 0, + userInfos: [], + }, + voteInfo: { + total_count: data.voteInfo?.totalCount || 0, + new_count: data.voteInfo?.newCount || 0, + new_nearby_count: 0, + last_visit_time: Number(data.voteInfo?.lastTime || 0), + userInfos: [], + }, + }; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetLike, params); +} + +async function resolveSelf(deps: Pick): Promise { + // Mirrors `apis/shared.ts::resolveSelfUid` — kept inline here so the + // namespace is self-contained against just the BridgeContext slice. + const cached = deps.identity.selfUid; + if (cached) return cached; + const selfUin = Number(deps.identity.uin); + if (!Number.isFinite(selfUin) || selfUin <= 0) { + throw new Error('self uid is unavailable'); + } + return deps.resolveUserUid(selfUin); +} diff --git a/packages/protocol/src/oidb-services/profile/get-unidirectional-friend-list.ts b/packages/protocol/src/oidb-services/profile/get-unidirectional-friend-list.ts new file mode 100644 index 00000000..0d1db8dd --- /dev/null +++ b/packages/protocol/src/oidb-services/profile/get-unidirectional-friend-list.ts @@ -0,0 +1,56 @@ +// 0xE17_0 — fetch the unidirectional friend block list. Wire name is +// non-standard (`MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0`) — uses +// the `wireName` override to bypass the default +// `OidbSvcTrpcTcp.0xNNNN_N` scheme. +// +// Request and response carry a JSON-encoded string in a single +// protobuf field, so the namespace's `serialize` / `deserialize` do +// the JSON marshalling. + +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0xe17Req, Oidb0xe17Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { BridgeContext } from '../../bridge-context'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export interface UnidirectionalFriendEntry { + [key: string]: import('@snowluma/common/json').JsonValue; +} + +export namespace GetUnidirectionalFriendList { + export const command = 0xE17; + export const subCommand = 0; + + /** Wire name override — this cmd lives outside the standard + * `OidbSvcTrpcTcp.0xNNNN_N` namespace. */ + export const wireName = (): string => 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0'; + + export interface Params { } + + export type Deps = OidbSender & Pick; + + export const serialize = (ctx: Deps, _p: Params): Oidb0xe17Req => { + const reqObj = { + uint64_uin: String(ctx.identity.uin), + uint64_top: 0, + uint32_req_num: 99, + bytes_cookies: '', + }; + return { jsonBody: JSON.stringify(reqObj) }; + }; + + export const deserialize = (_ctx: Deps, body: Oidb0xe17Resp): UnidirectionalFriendEntry[] => { + if (!body || !body.jsonBody) throw new Error('get unidirectional friend list empty'); + const parsed = JSON.parse(body.jsonBody) as { rpt_block_list?: UnidirectionalFriendEntry[] }; + return parsed.rpt_block_list || []; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps): Promise => + invokeOidb(deps, GetUnidirectionalFriendList, {}); +} diff --git a/packages/protocol/src/oidb-services/profile/set-input-status.ts b/packages/protocol/src/oidb-services/profile/set-input-status.ts new file mode 100644 index 00000000..176fb96f --- /dev/null +++ b/packages/protocol/src/oidb-services/profile/set-input-status.ts @@ -0,0 +1,47 @@ +// 0xCD4_1 — set typing / recording / etc. "input status" indicator +// shown to a peer in a 1:1 chat. +// +// Resolves the target uin → uid via the identity service before +// building the body. `chatType: 0` is the wire constant for friend +// chats (the only flavor SnowLuma currently supports here). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0xcd4Req, Oidb0xcd4Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SetInputStatus { + export const command = 0xCD4; + export const subCommand = 1; + + export interface Params { + userId: number; + eventType: number; + } + + export type Deps = OidbSender & Pick; + + export const serialize = async (ctx: Deps, p: Params): Promise => { + const targetUid = await ctx.resolveUserUid(p.userId); + if (!targetUid) throw new Error('target uid not found'); + return { + reqBody: { + uid: targetUid, + chatType: 0, + eventType: p.eventType, + }, + }; + }; + + export const deserialize = (_ctx: Deps, _: Oidb0xcd4Resp): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetInputStatus, params); +} diff --git a/packages/protocol/src/oidb-services/profile/set-profile.ts b/packages/protocol/src/oidb-services/profile/set-profile.ts new file mode 100644 index 00000000..972fcdba --- /dev/null +++ b/packages/protocol/src/oidb-services/profile/set-profile.ts @@ -0,0 +1,50 @@ +// 0x112A_2 — write profile string/int field-value pairs. +// +// SnowLuma's facade currently exposes only nickname (field 20002) and +// personalNote (field 102) but the underlying wire supports arbitrary +// (fieldId, value) tuples. The `invoke` short-circuits when both +// inputs are undefined so the facade's historic no-op-on-no-input +// behaviour is preserved (no wasted SSO round-trip). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x112aResp, OidbSetProfile } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SetProfile { + export const command = 0x112A; + export const subCommand = 2; + + export interface Params { + nickname?: string; + personalNote?: string; + } + + /** Needs identity to read `uin` for the request body. */ + export type Deps = OidbSender & Pick; + + export const serialize = (ctx: Deps, p: Params): OidbSetProfile => { + const stringProfiles: { fieldId: number; value: string }[] = []; + if (p.nickname !== undefined) stringProfiles.push({ fieldId: 20002, value: p.nickname }); + if (p.personalNote !== undefined) stringProfiles.push({ fieldId: 102, value: p.personalNote }); + return { uin: BigInt(ctx.identity.uin), stringProfiles }; + }; + + export const deserialize = (_ctx: Deps, _: Oidb0x112aResp): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => { + // No-op when there's nothing to write — preserves the facade's + // historic short-circuit (avoid a wasted SSO round-trip). + if (params.nickname === undefined && params.personalNote === undefined) { + return Promise.resolve(); + } + return invokeOidb(deps, SetProfile, params); + }; +} diff --git a/packages/protocol/src/oidb-services/profile/set-self-long-nick.ts b/packages/protocol/src/oidb-services/profile/set-self-long-nick.ts new file mode 100644 index 00000000..26d498c4 --- /dev/null +++ b/packages/protocol/src/oidb-services/profile/set-self-long-nick.ts @@ -0,0 +1,39 @@ +// 0x112A_2 — set the self "long nick" / personal signature. Same cmd +// as SetProfile but a different request shape (uses the single +// `profile: { tag, value }` field instead of the repeated string +// profiles list). Kept separate because the wire body is structurally +// different — proton needs distinct types so the codec is correctly +// monomorphized per call site. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x112aReq, Oidb0x112aResp } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import type { BridgeContext } from '../../bridge-context'; + +export namespace SetSelfLongNick { + export const command = 0x112A; + export const subCommand = 2; + + export interface Params { + longNick: string; + } + + export type Deps = OidbSender & Pick; + + export const serialize = (ctx: Deps, p: Params): Oidb0x112aReq => ({ + uin: BigInt(ctx.identity.uin), + profile: { tag: 102, value: String(p.longNick) }, + }); + + export const deserialize = (_ctx: Deps, _: Oidb0x112aResp): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetSelfLongNick, params); +} diff --git a/packages/protocol/src/oidb-services/reaction/fetch-reaction-summary.ts b/packages/protocol/src/oidb-services/reaction/fetch-reaction-summary.ts new file mode 100644 index 00000000..7d445dcb --- /dev/null +++ b/packages/protocol/src/oidb-services/reaction/fetch-reaction-summary.ts @@ -0,0 +1,72 @@ +// 0x9084_1 — fetch per-emoji reaction summary on a group message. +// +// Server returns the full summary unconditionally; the emoji_id / +// emoji_type / count fields in the request body are ignored by the +// summary handler but kept to mirror the working 0x9083_1 request shape +// (same `Pick` of fields the wire format prefers). +// +// "Used" entries carry (lastReactionTime, count, emojiType, emojiId). +// Catalog-tail entries (available reactions the server suggests but +// nobody has reacted with) carry only emojiType + emojiId — filtered +// out here so callers see only the meaningful subset. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + Oidb0x9084Req, Oidb0x9084Resp, +} from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace FetchReactionSummary { + export const command = 0x9084; + export const subCommand = 1; + + export interface Params { + groupId: number; + sequence: number; + } + + export interface ReactionSummaryEntry { + emojiId: string; + emojiType: number; + count: number; + /** Unix epoch seconds of the most recent reaction. */ + lastReactionTime: number; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): Oidb0x9084Req => ({ + groupId: BigInt(p.groupId), + sequence: BigInt(p.sequence), + emojiId: '', + emojiType: 0, + cookie: new Uint8Array(0), + count: 0, + field12: 1, + }); + + export const deserialize = (_ctx: Deps, body: Oidb0x9084Resp): ReactionSummaryEntry[] => { + const out: ReactionSummaryEntry[] = []; + for (const e of body.entries ?? []) { + const count = e.count ?? 0; + if (count <= 0) continue; // skip catalog-tail entries + out.push({ + emojiId: e.emojiId ?? '', + emojiType: e.emojiType ?? 1, + count, + lastReactionTime: Number(e.lastReactionTime ?? 0n), + }); + } + return out; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, FetchReactionSummary, params); +} diff --git a/packages/protocol/src/oidb-services/reaction/get-emoji-likes.ts b/packages/protocol/src/oidb-services/reaction/get-emoji-likes.ts new file mode 100644 index 00000000..25ae06a0 --- /dev/null +++ b/packages/protocol/src/oidb-services/reaction/get-emoji-likes.ts @@ -0,0 +1,71 @@ +// 0x9083_1 — historic "fetch reactor user list" cmd. CONFIRMED to be +// a real server endpoint (errorCode=0, trace string echoes the cmd +// name), but its reply is always a 4-byte minimal ack `18 01 20 01` +// regardless of the message / emoji / whether the bot just set a +// reaction. The actual "who reacted" data is NOT served via SSO at +// all — NTQQ's own client uses a wrapper-internal cache. SnowLuma +// mirrors that with `ReactionStore` (fed from GroupMsgEmojiLikeEvent +// push) on the OneBot side. +// +// This namespace exists as a legacy stub so older callers don't crash +// — `invoke` always returns an empty user list. Newer code should +// query `ReactionStore` instead. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + Oidb0x9083Req, Oidb0x9083Resp, +} from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace GetEmojiLikes { + export const command = 0x9083; + export const subCommand = 1; + + export interface Params { + groupId: number; + sequence: number; + emojiId: string; + emojiType?: number; + count?: number; + /** Base64-encoded continuation cookie from a previous page. */ + cookie?: string; + } + + export interface Result { + users: Array<{ uin: number }>; + /** Base64 cookie for next page (empty when on last page). */ + cookie: string; + isLast: boolean; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): Oidb0x9083Req => ({ + groupId: BigInt(p.groupId), + sequence: BigInt(p.sequence), + emojiId: p.emojiId, + emojiType: p.emojiType ?? 1, + cookie: p.cookie ? Buffer.from(p.cookie, 'base64') : new Uint8Array(0), + field7: 0, + count: p.count ?? 10, + field12: 1, + }); + + export const deserialize = (_ctx: Deps, body: Oidb0x9083Resp): Result => { + const users: Array<{ uin: number }> = (body.inner?.userInfo ?? []) + .map(u => ({ uin: Number(u?.uin ?? 0) })) + .filter(u => u.uin > 0); + const cookie = body.cookie ? Buffer.from(body.cookie).toString('base64') : ''; + return { users, cookie, isLast: !cookie }; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetEmojiLikes, params); +} diff --git a/packages/protocol/src/oidb-services/reaction/set-reaction.ts b/packages/protocol/src/oidb-services/reaction/set-reaction.ts new file mode 100644 index 00000000..84e85ea3 --- /dev/null +++ b/packages/protocol/src/oidb-services/reaction/set-reaction.ts @@ -0,0 +1,54 @@ +// 0x9082 — set / unset emoji reaction on a group message. +// subCommand 1 = set, 2 = unset +// +// Cross-checked against LagrangeV2 +// `Internal/Packets/Service/SetGroupReaction.cs`: +// field 2 groupUin (long) +// field 3 sequence (ulong) +// field 4 code (string) ← emoji id +// field 5 type (ulong) ← 1 for QQ-face short id, 2 for unicode codepoint +// (Heuristic on `code.length > 3` matches Lagrange's +// `GroupAddReactionEvent.IsEmoji` discriminator.) + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupReaction } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace SetReaction { + export const command = 0x9082; + + export interface Params { + groupId: number; + sequence: number; + /** Emoji code. 1–3 digits → QQ face (type=1); longer → unicode (type=2). */ + code: string; + /** true = set reaction (subCommand 1), false = unset (subCommand 2). */ + isSet: boolean; + } + + /** Only the wire-send capability is needed. */ + export type Deps = OidbSender; + + export const resolveSubCommand = (p: Params): number => p.isSet ? 1 : 2; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupReaction => ({ + groupUin: p.groupId, + sequence: p.sequence, + code: p.code, + type: p.code.length > 3 ? 2 : 1, + field6: false, + field7: false, + }); + + export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {}; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, SetReaction, params); +} diff --git a/packages/protocol/src/oidb-services/shared.ts b/packages/protocol/src/oidb-services/shared.ts new file mode 100644 index 00000000..745e5004 --- /dev/null +++ b/packages/protocol/src/oidb-services/shared.ts @@ -0,0 +1,28 @@ +// Tiny helpers shared between OIDB namespaces — kept here instead of +// `@snowluma/core/bridge/apis/shared` to avoid a circular dep +// (services live in @snowluma/protocol, facades in @snowluma/core). + +/** Coerce numbers, strings, and bigints to a plain integer. */ +export function toInt(value: unknown): number { + if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); + if (typeof value === 'bigint') { + const n = Number(value); + return Number.isFinite(n) ? Math.trunc(n) : 0; + } + if (typeof value === 'string' && value.trim()) { + const n = Number(value); + return Number.isFinite(n) ? Math.trunc(n) : 0; + } + return 0; +} + +/** Standard OIDB sub-response check: throw a typed Error if retCode != 0. + * Prefers `wording` over `msg` for the human-facing message. */ +export function ensureRetCodeZero( + operation: string, code: unknown, msg: unknown, wording: unknown, +): void { + const retCode = toInt(code); + if (retCode === 0) return; + const text = (typeof wording === 'string' && wording) || (typeof msg === 'string' && msg) || 'unknown error'; + throw new Error(`${operation} failed: code=${retCode} msg=${text}`); +} diff --git a/packages/protocol/src/oidb-services/web/force-fetch-client-key.ts b/packages/protocol/src/oidb-services/web/force-fetch-client-key.ts new file mode 100644 index 00000000..cacfa26a --- /dev/null +++ b/packages/protocol/src/oidb-services/web/force-fetch-client-key.ts @@ -0,0 +1,43 @@ +// 0x102A_1 — fetch a fresh `clientKey` (consumed by the ptlogin2 jump +// URL flow that swaps it for cookie-jar entries on qq.com subdomains). +// +// The server's `keyIndex` field is occasionally empty in the wild; +// every NapCat-derived implementation falls back to the literal "19" +// in that case — origin unknown but the value works. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbClientKeyReq, OidbClientKeyResp } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export interface ClientKeyInfo { + clientKey: string; + keyIndex: string; + expireTime: string; +} + +export namespace ForceFetchClientKey { + export const command = 0x102A; + export const subCommand = 1; + + export interface Params {} + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, _: Params): OidbClientKeyReq => ({}); + + export const deserialize = (_ctx: Deps, body: OidbClientKeyResp): ClientKeyInfo => ({ + clientKey: body.clientKey || '', + keyIndex: String(body.keyIndex || '19'), + expireTime: String(body.expireTime || '1800'), + }); + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps): Promise => + invokeOidb(deps, ForceFetchClientKey, {}); +} diff --git a/packages/protocol/src/oidb-services/web/get-pskey.ts b/packages/protocol/src/oidb-services/web/get-pskey.ts new file mode 100644 index 00000000..2893b659 --- /dev/null +++ b/packages/protocol/src/oidb-services/web/get-pskey.ts @@ -0,0 +1,48 @@ +// 0x102A_0 — request p_skey cookies for a list of qq.com subdomains. +// Used as the fallback when ptlogin2 jump doesn't emit a p_skey on +// the cookie set (intermittent server behaviour). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbGetPskeyReq, OidbGetPskeyResp } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace GetPskey { + export const command = 0x102A; + export const subCommand = 0; + + export interface Params { + domainList: string[]; + } + + export interface Result { + domainPskeyMap: Map; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGetPskeyReq => ({ + domainList: p.domainList, + }); + + export const deserialize = (_ctx: Deps, body: OidbGetPskeyResp): Result => { + const domainPskeyMap = new Map(); + if (body.pskeyItems && Array.isArray(body.pskeyItems)) { + for (const item of body.pskeyItems) { + if (item.domain && item.pskey) { + domainPskeyMap.set(item.domain, item.pskey); + } + } + } + return { domainPskeyMap }; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, GetPskey, params); +} diff --git a/packages/bridge/src/packet-pipeline.ts b/packages/protocol/src/packet-pipeline.ts similarity index 62% rename from packages/bridge/src/packet-pipeline.ts rename to packages/protocol/src/packet-pipeline.ts index 89861ee3..cfac6fec 100644 --- a/packages/bridge/src/packet-pipeline.ts +++ b/packages/protocol/src/packet-pipeline.ts @@ -33,6 +33,30 @@ export interface PacketPipelineDeps { * and `refreshGroupList` was false). */ refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise; + /** + * Resolve a stranger profile by UID — used to fill in the requester's + * uin + nickname on group-join-request and friend-request events + * where the push only carries a uid. Mirrors Lagrange's + * `FetchUserInfoEvent.Create(targetUid)` path + * (`dev/Lagrange.Core/.../MessagingLogic.cs:215-224`). Returns null + * on lookup failure so the dispatch path can proceed with the bare + * uid-only event. + */ + resolveStrangerProfile(uid: string): Promise<{ uin: number; nickname: string } | null>; + /** + * Resolve the verify message ("postscript") + server sequence number + * for a pending group-join / group-invite. The OIDB push only + * carries the requester's UID + group uin — the actual verify text + * the user typed ("你们好" etc.) lives on the pending-request queue + * fetched via OIDB 0x10C0. NapCat surfaces this as + * `notify.postscript` from `nodeIKernelGroupService.getGroupNotifies`; + * we mirror that with an `fetchGroupRequests` lookup matched on + * `(groupId, uid, subType)`. Returns null when no matching pending + * request exists (e.g. it was already handled by another client). + */ + resolveGroupJoinRequest( + groupId: number, uid: string, subType: 'add' | 'invite', + ): Promise<{ comment: string; sequence: number } | null>; } export class IncomingPacketPipeline { @@ -74,6 +98,11 @@ export class IncomingPacketPipeline { this.log.warn('dispatchAfterIdentityRefresh failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); }); + } else if (this.needsStrangerResolve(event)) { + void this.dispatchAfterStrangerResolve(event).catch((err) => { + this.log.warn('dispatchAfterStrangerResolve failed: %s', + err instanceof Error ? (err.stack ?? err.message) : String(err)); + }); } else { this.handleSideEffects(event); printEvent(this.eventLog, this.deps.identity, event); @@ -96,6 +125,30 @@ export class IncomingPacketPipeline { return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid); } + /** Group join requests carry only the requester's UID (no UIN). We + * fire a UID-form FetchUserProfile to resolve UIN + nickname before + * dispatch so the OneBot layer's `user_id` field is populated and + * the consumer bot's follow-up `get_stranger_info` lookup succeeds. + * Mirrors Lagrange's `dev/Lagrange.Core/.../MessagingLogic.cs:215-224`. + * + * Also catches the legacy cache-pollution case: pre-fix builds + * stored ` → ` in the identity DB when + * the decoder's fallback was `ctx.fromUin` (= group's own uin on + * a group-scoped push). After upgrade, the decoder's + * `resolveUidToUin` hits that polluted mapping and returns the + * groupUin instead of 0, so the `fromUin <= 0` guard alone would + * silently skip the resolve and re-emit the bug. Treating + * `fromUin === groupId` as bogus forces the async resolve to + * overwrite the polluted entry on the next event. */ + private needsStrangerResolve(event: QQEventVariant): event is Extract { + if (event.kind !== 'group_invite' || !event.fromUid) return false; + if (event.fromUin <= 0) return true; + // Pollution signature — a real requester's uin would never equal + // the group's own uin. Force a re-resolve so the cache self-heals. + if (event.groupId > 0 && event.fromUin === event.groupId) return true; + return false; + } + private async dispatchAfterIdentityRefresh(event: Extract): Promise { let refreshed = false; try { @@ -110,6 +163,44 @@ export class IncomingPacketPipeline { this.emit(event); } + private async dispatchAfterStrangerResolve(event: Extract): Promise { + const uid = event.fromUid; + if (uid) { + // Fire profile + pending-request lookups in PARALLEL — they're + // independent OIDB calls (0xFE1_2 stranger profile + 0x10C0 + // pending request queue). Both `Promise.allSettled` so a flake + // on one path doesn't kill the other. + const subType = event.subType === 'invite' ? 'invite' : 'add'; + const [profileR, requestR] = await Promise.allSettled([ + this.deps.resolveStrangerProfile(uid), + this.deps.resolveGroupJoinRequest(event.groupId, uid, subType), + ]); + + if (profileR.status === 'fulfilled' && profileR.value && profileR.value.uin > 0) { + event.fromUin = profileR.value.uin; + } else if (profileR.status === 'rejected') { + this.log.warn('failed to resolve stranger profile: uid=%s err=%s', + uid, profileR.reason instanceof Error ? profileR.reason.message : String(profileR.reason)); + } + + if (requestR.status === 'fulfilled' && requestR.value) { + // NapCat surfaces the verify text as `comment` on the OneBot + // event (`postscript` server-side). Without this the bot's + // approval-prompt template renders an empty body line — see + // `dev/NapCatQQ/.../napcat-onebot/index.ts:496-498`. + event.message = requestR.value.comment; + } else if (requestR.status === 'rejected') { + this.log.warn('failed to resolve group join request: groupId=%d uid=%s err=%s', + event.groupId, uid, + requestR.reason instanceof Error ? requestR.reason.message : String(requestR.reason)); + } + } + + this.handleSideEffects(event); + printEvent(this.eventLog, this.deps.identity, event); + this.emit(event); + } + private async prepareGroupMemberJoinIdentity(event: Extract): Promise { this.resolveMemberIdentityFromCache(event); if (event.userUin > 0 || !event.userUid || event.groupId <= 0) return false; @@ -220,14 +311,22 @@ export class IncomingPacketPipeline { source: 'friend_request', }); break; - case 'group_invite': + case 'group_invite': { + // Defensive: never cache a uid→uin mapping where uin equals + // the group's own uin — that's the pollution signature the + // legacy decoder fallback produced. Pass 0 so `rememberUidUin` + // skips the map write (it short-circuits on uin <= 0) but the + // user row still gets upserted with the uid + group context. + const uinForCache = event.fromUin > 0 && event.fromUin !== event.groupId + ? event.fromUin : 0; this.deps.identity.rememberRequestIdentity({ groupId: event.groupId, uid: event.fromUid, - uin: event.fromUin, + uin: uinForCache, source: 'group_request', }); break; + } default: break; } diff --git a/packages/bridge/src/qq-info.ts b/packages/protocol/src/qq-info.ts similarity index 84% rename from packages/bridge/src/qq-info.ts rename to packages/protocol/src/qq-info.ts index e3302539..40ce2779 100644 --- a/packages/bridge/src/qq-info.ts +++ b/packages/protocol/src/qq-info.ts @@ -8,6 +8,10 @@ export interface UserProfileInfo { age: number; sign: string; avatar: string; + /** QQ 等级 — OIDB 0xFE1_2 number-property key 105. + * Already requested in `fetchUserProfile` keys[]; LagrangeV2 + * `FetchStrangerService.cs` confirms `// Level`. */ + level: number; } export interface FriendInfo { diff --git a/packages/bridge/src/web/group-album.ts b/packages/protocol/src/web/group-album.ts similarity index 96% rename from packages/bridge/src/web/group-album.ts rename to packages/protocol/src/web/group-album.ts index 830ec25e..dbc22785 100644 --- a/packages/bridge/src/web/group-album.ts +++ b/packages/protocol/src/web/group-album.ts @@ -1,8 +1,9 @@ -import { RequestUtil, cookieToString, getBknFromCookie } from './request-util'; +import type { JsonValue } from '@snowluma/common/json'; import { createHash } from 'crypto'; -import { statSync, createReadStream, writeFileSync, unlinkSync } from 'fs'; -import { basename, join } from 'path'; +import { createReadStream, statSync, unlinkSync, writeFileSync } from 'fs'; import { tmpdir } from 'os'; +import { basename, join } from 'path'; +import { RequestUtil, cookieToString, getBknFromCookie } from './request-util'; // 群相册信息 export interface GroupAlbumInfo { @@ -10,13 +11,13 @@ export interface GroupAlbumInfo { name: string; picNum: number; createTime: number; - [key: string]: any; + [key: string]: JsonValue; } // 获取群相册列表返回 export interface GroupAlbumListRet { album: GroupAlbumInfo[]; - [key: string]: any; + [key: string]: JsonValue | GroupAlbumInfo[]; } // 相册媒体信息 @@ -24,7 +25,7 @@ export interface AlbumMediaInfo { photoId: string; url: string; uploadTime: number; - [key: string]: any; + [key: string]: JsonValue; } /** @@ -150,7 +151,7 @@ async function uploadAlbumSlice( session: string, filePath: string, // 移除 offset 和 chunkSize 参数,改为在内部控制 - imgMd5: string, + _imgMd5: string, skey: string, pskey: string, uin: string diff --git a/packages/bridge/src/web/group-essence.ts b/packages/protocol/src/web/group-essence.ts similarity index 83% rename from packages/bridge/src/web/group-essence.ts rename to packages/protocol/src/web/group-essence.ts index cf46eff7..a6c01a9e 100644 --- a/packages/bridge/src/web/group-essence.ts +++ b/packages/protocol/src/web/group-essence.ts @@ -1,17 +1,18 @@ -import { RequestUtil, cookieToString, getBknFromCookie } from './request-util'; +import type { JsonObject } from '@snowluma/common/json'; import { createLogger } from '@snowluma/common/logger'; +import { RequestUtil, cookieToString, getBknFromCookie } from './request-util'; const log = createLogger('Bridge.Web'); // 定义接口返回类型 export interface GroupEssenceMsgRet { - retcode: number; - data: { - is_end: boolean; - msg_list: any[]; // 具体结构视需要补充 - [key: string]: any; - }; - [key: string]: any; + retcode: number; + data: { + is_end: boolean; + msg_list: JsonObject[]; // 具体结构视需要补充 + [key: string]: JsonObject[] | boolean | string | number | null; + }; + [key: string]: JsonObject | JsonObject[] | boolean | string | number | null; } @@ -68,4 +69,4 @@ export async function getGroupEssenceMsgAll( } return ret; -} \ No newline at end of file +} diff --git a/packages/bridge/src/web/group-honor.ts b/packages/protocol/src/web/group-honor.ts similarity index 55% rename from packages/bridge/src/web/group-honor.ts rename to packages/protocol/src/web/group-honor.ts index 133e4f9d..6cef4896 100644 --- a/packages/bridge/src/web/group-honor.ts +++ b/packages/protocol/src/web/group-honor.ts @@ -1,19 +1,39 @@ -import { RequestUtil, cookieToString } from './request-util'; import { createLogger } from '@snowluma/common/logger'; +import { RequestUtil, cookieToString } from './request-util'; const log = createLogger('Bridge.Web'); +export interface WebHonorItem { + [key: string]: import('@snowluma/common/json').JsonValue; + user_id: number | string | null; + nickname: string; + avatar: string; + description: string; +} + +interface RawHonorItem { + uin?: number | string; + name?: string; + avatar?: string; + desc?: string; +} + +interface HonorInitialState { + talkativeList?: RawHonorItem[]; + actorList?: RawHonorItem[]; +} + export enum WebHonorType { - TALKATIVE = 'talkative', - PERFORMER = 'performer', - LEGEND = 'legend', - EMOTION = 'emotion', - ALL = 'all', + TALKATIVE = 'talkative', + PERFORMER = 'performer', + LEGEND = 'legend', + EMOTION = 'emotion', + ALL = 'all', } -async function fetchHonorData(cookieObject: Record, groupCode: string, type: number) { - let resJson; +async function fetchHonorData(cookieObject: Record, groupCode: string, type: number): Promise { + let resJson: HonorInitialState | undefined; try { const res = await RequestUtil.HttpGetText( `https://qun.qq.com/interactive/honorlist?${new URLSearchParams({ @@ -26,7 +46,7 @@ async function fetchHonorData(cookieObject: Record, groupCode: s ); const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res); if (match?.[1]) { - resJson = JSON.parse(match[1].trim()); + resJson = JSON.parse(match[1].trim()) as HonorInitialState; } return type === 1 ? resJson?.talkativeList : resJson?.actorList; } catch (e) { @@ -34,20 +54,20 @@ async function fetchHonorData(cookieObject: Record, groupCode: s } } -export async function getHonorListWebAPI(cookieObject: Record, groupCode: string, type: number) { +export async function getHonorListWebAPI(cookieObject: Record, groupCode: string, type: number): Promise { try { const data = await fetchHonorData(cookieObject, groupCode, type); if (!data) return []; - return data.map((item: any) => ({ - user_id: item?.uin, - nickname: item?.name, - avatar: item?.avatar, - description: item?.desc, + return data.map((item) => ({ + user_id: item?.uin ?? null, + nickname: item?.name ?? '', + avatar: item?.avatar ?? '', + description: item?.desc ?? '', })); } catch (e) { log.warn('getHonorListWebAPI failed (group=%s type=%d): %s', groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e)); return []; } -} \ No newline at end of file +} diff --git a/packages/bridge/src/web/group-notice.ts b/packages/protocol/src/web/group-notice.ts similarity index 92% rename from packages/bridge/src/web/group-notice.ts rename to packages/protocol/src/web/group-notice.ts index 2fc3b8fa..00c41760 100644 --- a/packages/bridge/src/web/group-notice.ts +++ b/packages/protocol/src/web/group-notice.ts @@ -1,39 +1,40 @@ -import { RequestUtil, cookieToString } from './request-util'; -import https from 'node:https'; +import type { JsonValue } from '@snowluma/common/json'; import { createLogger } from '@snowluma/common/logger'; +import https from 'node:https'; +import { RequestUtil, cookieToString } from './request-util'; const log = createLogger('Bridge.Web'); export interface SetNoticeRetSuccess { - ec?: number; - em?: string; - [key: string]: any; + ec?: number; + em?: string; + [key: string]: JsonValue | undefined; } export interface UploadImageRetSuccess { - ec?: number; - id?: string; - [key: string]: any; + ec?: number; + id?: string; + [key: string]: JsonValue | undefined; } export interface WebApiGroupNoticeFeed { - fid: string; - u: number; - pubt: number; - msg: { - text: string; - pics?: Array<{ id: string; w: number; h: number }>; - }; - settings: any; - read_num: number; - [key: string]: any; + fid: string; + u: number; + pubt: number; + msg: { + text: string; + pics?: Array<{ id: string; w: number; h: number }>; + }; + settings: JsonValue; + read_num: number; + [key: string]: JsonValue; } export interface WebApiGroupNoticeRet { - ec: number; - em?: string; - feeds?: Record; - [key: string]: any; + ec: number; + em?: string; + feeds?: Record; + [key: string]: JsonValue | Record | undefined; } export function calculateBkn(key: string): string { @@ -173,7 +174,7 @@ export async function uploadGroupNoticeImage( imageBuffer: Buffer ): Promise<{ id: string; width: number; height: number } | undefined> { try { - const bkn = calculateBkn(cookieObject['skey']); + const bkn = calculateBkn(cookieObject['skey']); const boundary = `-----------------------------${Date.now()}`; const parts: Buffer[] = []; @@ -270,4 +271,4 @@ export async function deleteGroupNotice( log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e)); return false; } -} \ No newline at end of file +} diff --git a/packages/bridge/src/web/request-util.ts b/packages/protocol/src/web/request-util.ts similarity index 89% rename from packages/bridge/src/web/request-util.ts rename to packages/protocol/src/web/request-util.ts index 60f28d8f..92d3d39c 100644 --- a/packages/bridge/src/web/request-util.ts +++ b/packages/protocol/src/web/request-util.ts @@ -1,5 +1,7 @@ -import https from 'node:https'; import http from 'node:http'; +import https from 'node:https'; + +type RequestBody = string | Buffer | Uint8Array | Record | undefined; export class RequestUtil { static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> { @@ -50,9 +52,9 @@ export class RequestUtil { }); } - static async HttpGetJson(url: string, method: string = 'GET', data?: any, headers: { - [key: string]: string; - } = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise { + static async HttpGetJson(url: string, method: string = 'GET', data?: RequestBody, headers: { + [key: string]: string; + } = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise { const option = new URL(url); const protocol = url.startsWith('https://') ? https : http; const options = { @@ -91,8 +93,8 @@ export class RequestUtil { } else { reject(new Error(`Unexpected status code: ${res.statusCode}`)); } - } catch (parseError: any) { - reject(new Error(parseError.message)); + } catch (parseError: unknown) { + reject(new Error(parseError instanceof Error ? parseError.message : String(parseError))); } }); }); @@ -105,7 +107,7 @@ export class RequestUtil { }); } - static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) { + static async HttpGetText(url: string, method: string = 'GET', data?: RequestBody, headers: { [key: string]: string; } = {}) { return this.HttpGetJson(url, method, data, headers, false, false); } } diff --git a/packages/protocol/tests/msg-push/rich-body-decoder.test.ts b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts new file mode 100644 index 00000000..da981409 --- /dev/null +++ b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts @@ -0,0 +1,123 @@ +// Receive-side decode for `com.tencent.multimsg` LightApp — verifies +// the inverse of element-builder.makeForwardElem so a forward sent by +// SnowLuma (or any QQ-NT / Lagrange / NapCat client) round-trips +// back to `{type: 'forward', resId, forwardUuid}` on the receiver. +// +// Without this the receiver-side decoder sees `lightApp` and falls +// back to a generic `{type: 'json', text: }` element, which +// means the OneBot layer can't surface a forward bubble OR walk into +// the nested forward via fetch(resId). + +import { describe, expect, it } from 'vitest'; +import { deflateSync } from 'zlib'; +import { decodeRichBody } from '../../src/msg-push/rich-body-decoder'; +import type { MessageBody } from '@snowluma/proto-defs/message'; + +function lightAppBytes(json: unknown): Uint8Array { + const buf = deflateSync(Buffer.from(JSON.stringify(json), 'utf8')); + const out = new Uint8Array(buf.length + 1); + out[0] = 0x01; // deflate prefix + out.set(buf, 1); + return out; +} + +describe('decodeRichBody / forward LightApp', () => { + it('emits {type:"forward", resId, forwardUuid} for com.tencent.multimsg', () => { + const body: MessageBody = { + richText: { + elems: [ + { + lightApp: { + data: lightAppBytes({ + app: 'com.tencent.multimsg', + meta: { detail: { resid: 'inner-res-1', uniseq: 'uuid-1' } }, + }), + }, + } as any, + ], + }, + }; + const out = decodeRichBody(body, true); + expect(out).toEqual([{ type: 'forward', resId: 'inner-res-1', forwardUuid: 'uuid-1' }]); + }); + + it('omits forwardUuid when the sender did not set uniseq (XML-era forwards)', () => { + const body: MessageBody = { + richText: { + elems: [ + { + lightApp: { + data: lightAppBytes({ + app: 'com.tencent.multimsg', + meta: { detail: { resid: 'only-resid' } }, + }), + }, + } as any, + ], + }, + }; + const out = decodeRichBody(body, true); + expect(out).toEqual([{ type: 'forward', resId: 'only-resid' }]); + }); + + it('falls back to {type:"json"} for non-multimsg LightApp (e.g. mini-app card)', () => { + const body: MessageBody = { + richText: { + elems: [ + { + lightApp: { + data: lightAppBytes({ app: 'com.tencent.miniapp_01', meta: {} }), + }, + } as any, + ], + }, + }; + const out = decodeRichBody(body, true); + expect(out).toHaveLength(1); + expect(out[0]!.type).toBe('json'); + expect(typeof (out[0] as any).text).toBe('string'); + }); + + it('falls back to {type:"json"} when com.tencent.multimsg is missing resid (malformed)', () => { + const body: MessageBody = { + richText: { + elems: [ + { + lightApp: { + data: lightAppBytes({ + app: 'com.tencent.multimsg', + meta: { detail: {} }, + }), + }, + } as any, + ], + }, + }; + const out = decodeRichBody(body, true); + expect(out).toHaveLength(1); + expect(out[0]!.type).toBe('json'); + }); + + it('still decodes the legacy richMsg serviceID=35 path (backward compat with mobile QQ)', () => { + // Older clients (and some bridges) still emit the m_resid XML + // shape. The decoder must keep treating it as a forward element + // so SnowLuma can fetch the resid downstream. + const xml = ''; + const xmlBuf = new Uint8Array(xml.length + 1); + xmlBuf[0] = 0x00; + xmlBuf.set(new TextEncoder().encode(xml), 1); + + const body: MessageBody = { + richText: { + elems: [ + { + richMsg: { serviceId: 35, template1: xmlBuf }, + } as any, + ], + }, + }; + const out = decodeRichBody(body, true); + expect(out).toHaveLength(1); + expect(out[0]).toMatchObject({ type: 'forward', resId: 'legacy-res' }); + }); +}); diff --git a/packages/protocol/tests/oidb-service.test.ts b/packages/protocol/tests/oidb-service.test.ts new file mode 100644 index 00000000..d24f8044 --- /dev/null +++ b/packages/protocol/tests/oidb-service.test.ts @@ -0,0 +1,291 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupReaction } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { + buildOidbRequest, + invokeOidb, + OidbError, + parseOidbResponse, + type OidbCallSpec, + type OidbSender, +} from '../src/oidb-service'; + +// Reused minimal spec — encodes a group-reaction-shaped request and +// reads back a void result. Exercises every spec branch. +const reactionSpec: OidbCallSpec< + OidbSender, OidbGroupReaction, OidbEmpty, + { groupId: number; sequence: number; code: string; isSet: boolean }, void +> = { + command: 0x9082, + resolveSubCommand: p => p.isSet ? 1 : 2, + serialize: (_ctx, p) => ({ + groupUin: p.groupId, + sequence: p.sequence, + code: p.code, + type: p.code.length > 3 ? 2 : 1, + field6: false, + field7: false, + }), + deserialize: () => {}, + encode: env => protobuf_encode>(env), + decode: bytes => protobuf_decode>(bytes), +}; + +// Static-subCommand variant for the branch test. +const staticSubSpec: OidbCallSpec = { + command: 0xEAC, + subCommand: 1, + serialize: (_ctx, p) => ({ groupUin: p.groupId, sequence: 0, code: '', type: 1, field6: false, field7: false }), + deserialize: () => {}, + encode: env => protobuf_encode>(env), + decode: bytes => protobuf_decode>(bytes), +}; + +function makeSender(resp: Partial = {}): OidbSender & { sendRawPacket: ReturnType } { + const defaultResp: SendPacketResult = { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.alloc(0), + }; + return { + sendRawPacket: vi.fn(async () => ({ ...defaultResp, ...resp })), + }; +} + +describe('invokeOidb', () => { + it('uses resolveSubCommand when present and computes the wire name', async () => { + const sender = makeSender(); + await invokeOidb(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '76', isSet: true }); + expect(sender.sendRawPacket).toHaveBeenCalledOnce(); + const [wireName] = sender.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0x9082_1'); + }); + + it('flips wire name when resolveSubCommand returns a different subcmd', async () => { + const sender = makeSender(); + await invokeOidb(sender, reactionSpec, { groupId: 1, sequence: 1, code: '76', isSet: false }); + const [wireName] = sender.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0x9082_2'); + }); + + it('uses static subCommand when resolveSubCommand is absent', async () => { + const sender = makeSender(); + await invokeOidb(sender, staticSubSpec, { groupId: 12345 }); + const [wireName] = sender.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0xeac_1'); + }); + + it('encodes serialize() output into an OIDB envelope (cmd + subcmd land in fields 1/2)', async () => { + const sender = makeSender(); + await invokeOidb(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '76', isSet: true }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0x9082); + expect(env.subCommand).toBe(1); + expect(env.body).toMatchObject({ + groupUin: 12345, sequence: 99, code: '76', type: 1, + }); + }); + + it('passes the body through deserialize for transformation', async () => { + type Echo = { tag: number }; + const spec: OidbCallSpec = { + command: 0x9082, + subCommand: 1, + serialize: (_ctx, p) => ({ code: p.code }), + deserialize: (_ctx, b) => ({ tag: b.type ?? 99 }), + encode: env => protobuf_encode>(env), + decode: bytes => protobuf_decode>(bytes), + }; + const responseEnvelope = protobuf_encode>({ + command: 0x9082, subCommand: 1, + body: { type: 5 } as OidbGroupReaction, + }); + const sender = makeSender({ responseData: Buffer.from(responseEnvelope) }); + const result = await invokeOidb(sender, spec, { code: 'x' }); + expect(result).toEqual({ tag: 5 }); + }); + + it('substitutes an empty body when the envelope has no field 4', async () => { + const envBytes = protobuf_encode>({ command: 0x9082, subCommand: 1 }); + const sender = makeSender({ responseData: Buffer.from(envBytes) }); + const deserialize = vi.fn(() => undefined); + const spec: OidbCallSpec = { + command: 0x9082, subCommand: 1, + serialize: (_ctx, p) => ({ code: p.code }), + deserialize, + encode: env => protobuf_encode>(env), + decode: bytes => protobuf_decode>(bytes), + }; + await invokeOidb(sender, spec, { code: 'x' }); + expect(deserialize).toHaveBeenCalledOnce(); + // deserialize now receives (ctx, body) — body is the second arg. + expect(deserialize.mock.calls[0]![1]).toEqual({}); + }); + + it('awaits async serialize before sending', async () => { + // ctx-aware serialize may need to resolve a uid first; invokeOidb + // must await it before encoding the envelope. + const sender = makeSender(); + const spec: OidbCallSpec = { + command: 0x9082, subCommand: 1, + serialize: async (_ctx, p) => { + await new Promise(r => setTimeout(r, 5)); + return { code: p.code, sequence: 42 }; + }, + deserialize: () => {}, + encode: env => protobuf_encode>(env), + decode: bytes => protobuf_decode>(bytes), + }; + await invokeOidb(sender, spec, { code: 'async' }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.code).toBe('async'); + expect(env.body?.sequence).toBe(42); + }); + + it('threads ctx into serialize so namespaces can read identity / resolve uids in place', async () => { + const sender = makeSender(); + // Extend the ctx with an arbitrary capability the spec uses. + type Ctx = OidbSender & { tag: string }; + const ctx: Ctx = { ...sender, tag: 'from-ctx' }; + const spec: OidbCallSpec = { + command: 0x9082, subCommand: 1, + serialize: (c, p) => ({ code: `${c.tag}/${p.code}` }), + deserialize: () => {}, + encode: env => protobuf_encode>(env), + decode: bytes => protobuf_decode>(bytes), + }; + await invokeOidb(ctx, spec, { code: 'x' }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.code).toBe('from-ctx/x'); + }); + + it('propagates timeoutMs to sendRawPacket', async () => { + const sender = makeSender(); + await invokeOidb(sender, staticSubSpec, { groupId: 1 }, 5000); + expect(sender.sendRawPacket.mock.calls[0]![2]).toBe(5000); + }); + + it('rethrows the sender errorMessage when success=false', async () => { + const sender = makeSender({ success: false, errorMessage: 'boom' }); + await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('boom'); + }); + + it('falls back to "packet send failed" when success=false and errorMessage is empty', async () => { + const sender = makeSender({ success: false, errorMessage: '' }); + await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('packet send failed'); + }); + + it('rethrows when sender returns success=true but gotResponse=false', async () => { + const sender = makeSender({ success: true, gotResponse: false, errorMessage: 'timeout' }); + await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('timeout'); + }); + + it('falls back to "no response" when gotResponse=false and errorMessage is empty', async () => { + const sender = makeSender({ success: true, gotResponse: false, errorMessage: '' }); + await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).rejects.toThrow('no response'); + }); + + it('raises OidbError when envelope errorCode != 0', async () => { + const errBytes = protobuf_encode>({ + command: 0x9082, subCommand: 1, errorCode: 42, errorMsg: 'no privilege', + }); + const sender = makeSender({ responseData: Buffer.from(errBytes) }); + let caught: unknown; + try { await invokeOidb(sender, staticSubSpec, { groupId: 1 }); } + catch (e) { caught = e; } + expect(caught).toBeInstanceOf(OidbError); + expect((caught as OidbError).code).toBe(42); + expect((caught as OidbError).serverMsg).toBe('no privilege'); + expect((caught as OidbError).command).toBe(0xEAC); + expect((caught as OidbError).subCommand).toBe(1); + expect((caught as OidbError).message).toContain('OIDB error 42'); + expect((caught as OidbError).message).toContain('0xeac_1'); + }); + + it('skips OidbError check when response payload is empty', async () => { + const sender = makeSender({ responseData: Buffer.alloc(0) }); + await expect(invokeOidb(sender, staticSubSpec, { groupId: 1 })).resolves.toBeUndefined(); + }); + + it('honours uinForm=true by flipping OIDB envelope reserved to 1', async () => { + const spec: OidbCallSpec = { + ...staticSubSpec, + uinForm: true, + }; + const sender = makeSender(); + await invokeOidb(sender, spec, { groupId: 1 }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.reserved).toBe(1); + }); + + it('uses uinForm=false by default (envelope reserved=0)', async () => { + const sender = makeSender(); + await invokeOidb(sender, staticSubSpec, { groupId: 1 }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.reserved ?? 0).toBe(0); + }); +}); + +describe('buildOidbRequest', () => { + it('returns the same wire name + bytes that invokeOidb would send', async () => { + const sender = makeSender(); + await invokeOidb(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '128516', isSet: true }); + const sentBytes = sender.sendRawPacket.mock.calls[0]![1]; + + const built = await buildOidbRequest(sender, reactionSpec, { groupId: 12345, sequence: 99, code: '128516', isSet: true }); + expect(built.wireName).toBe('OidbSvcTrpcTcp.0x9082_1'); + expect(Buffer.from(built.bytes).equals(Buffer.from(sentBytes))).toBe(true); + }); + + it('uses static subCommand when resolveSubCommand is absent', async () => { + const sender = makeSender(); + const built = await buildOidbRequest(sender, staticSubSpec, { groupId: 1 }); + expect(built.wireName).toBe('OidbSvcTrpcTcp.0xeac_1'); + }); +}); + +describe('parseOidbResponse', () => { + it('decodes wire bytes via spec.decode and runs spec.deserialize on the body', () => { + const sender = makeSender(); + const envBytes = protobuf_encode>({ + command: 0x9082, subCommand: 1, body: { type: 7 } as OidbGroupReaction, + }); + type Echo = { type: number }; + const spec: OidbCallSpec = { + command: 0x9082, subCommand: 1, + serialize: () => ({} as OidbGroupReaction), + deserialize: (_ctx, b) => ({ type: b.type ?? 0 }), + encode: env => protobuf_encode>(env), + decode: bytes => protobuf_decode>(bytes), + }; + expect(parseOidbResponse(sender, spec, envBytes)).toEqual({ type: 7 }); + }); + + it('substitutes empty body when the envelope lacks one', () => { + const sender = makeSender(); + const envBytes = protobuf_encode>({ command: 0x9082, subCommand: 1 }); + const deserialize = vi.fn(() => ({ ok: true })); + parseOidbResponse(sender, { ...staticSubSpec, deserialize } as any, envBytes); + // deserialize now receives (ctx, body) — body is the second arg. + expect(deserialize.mock.calls[0]![1]).toEqual({}); + }); +}); + +describe('OidbError', () => { + it('formats message with hex cmd and decimal subcmd', () => { + const e = new OidbError(123, 'denied', 0x9084, 2); + expect(e.message).toBe('OIDB error 123 on 0x9084_2: denied'); + expect(e.name).toBe('OidbError'); + expect(e.code).toBe(123); + expect(e.serverMsg).toBe('denied'); + expect(e.command).toBe(0x9084); + expect(e.subCommand).toBe(2); + }); +}); diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-download-rkeys.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-download-rkeys.test.ts new file mode 100644 index 00000000..cdd9e3ec --- /dev/null +++ b/packages/protocol/tests/oidb-services/contacts/fetch-download-rkeys.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { FetchDownloadRkeys } from '../../../src/oidb-services/contacts/fetch-download-rkeys'; + +function makeSender(body?: NTV2RichMediaResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('FetchDownloadRkeys namespace', () => { + it('declares 0x9067_202 with uinForm=true', () => { + expect(FetchDownloadRkeys.command).toBe(0x9067); + expect(FetchDownloadRkeys.subCommand).toBe(202); + expect(FetchDownloadRkeys.uinForm).toBe(true); + }); + + describe('serialize', () => { + it('requests the (private=10, group=20, fallback=2) image scopes', () => { + const out = FetchDownloadRkeys.serialize({} as any, {}); + expect(out.downloadRkey?.types).toEqual([10, 20, 2]); + }); + + it('packages the fixed reqHead { common, scene, client }', () => { + const out = FetchDownloadRkeys.serialize({} as any, {}); + expect(out.reqHead).toEqual({ + common: { requestId: 1, command: 202 }, + scene: { requestType: 2, businessType: 1, sceneType: 0 }, + client: { agentType: 2 }, + }); + }); + }); + + describe('deserialize', () => { + it('throws when respHead.retCode is non-zero', () => { + expect(() => FetchDownloadRkeys.deserialize({} as any, { + respHead: { retCode: 42, message: 'bad' }, + } as any)).toThrow('bad'); + }); + + it('passes through on retCode = 0', () => { + const body = { respHead: { retCode: 0 }, downloadRkey: { rkeys: [] } }; + expect(FetchDownloadRkeys.deserialize({} as any, body as any)).toBe(body); + }); + + it('falls back to a generic message when none is provided', () => { + expect(() => FetchDownloadRkeys.deserialize({} as any, { + respHead: { retCode: 1 }, + } as any)).toThrow('fetch download rkey failed'); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0x9067_202 with reserved=1', async () => { + const sender = makeSender({ respHead: { retCode: 0 }, downloadRkey: { rkeys: [] } } as any); + await FetchDownloadRkeys.invoke(sender); + const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0x9067_202'); + const env = protobuf_decode>(bytes); + expect(env.reserved).toBe(1); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-friend-list-page.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-friend-list-page.test.ts new file mode 100644 index 00000000..46d82b41 --- /dev/null +++ b/packages/protocol/tests/oidb-services/contacts/fetch-friend-list-page.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase, OidbSvcTrpcTcp0xFD4_1Response } from '@snowluma/proto-defs/oidb'; +import type { OidbFriendListRequest } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { FetchFriendListPage } from '../../../src/oidb-services/contacts/fetch-friend-list-page'; + +function makeSender(body?: OidbSvcTrpcTcp0xFD4_1Response) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('FetchFriendListPage namespace', () => { + it('declares 0xFD4_1', () => { + expect(FetchFriendListPage.command).toBe(0xFD4); + expect(FetchFriendListPage.subCommand).toBe(1); + }); + + describe('serialize', () => { + it('omits nextUin on the first page', () => { + const out = FetchFriendListPage.serialize({} as any, { nextUin: null }) as any; + expect(out.nextUin).toBeUndefined(); + expect(out.friendCount).toBe(300); + expect(out.field4).toBe(0); + }); + + it('includes nextUin sub-message on follow-up pages', () => { + const out = FetchFriendListPage.serialize({} as any, { nextUin: 10001 }) as any; + expect(out.nextUin).toEqual({ uin: 10001 }); + }); + + it('emits the verbatim property request list (codes 100/101/102/103/20002/27394)', () => { + const out = FetchFriendListPage.serialize({} as any, { nextUin: null }) as any; + expect(out.body).toEqual([ + { type: 1, number: { numbers: [103, 102, 20002, 27394] } }, + { type: 4, number: { numbers: [100, 101, 102] } }, + ]); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0xfd4_1', async () => { + const sender = makeSender({ friends: [] }); + await FetchFriendListPage.invoke(sender, { nextUin: null }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xfd4_1'); + }); + + it('returns the wire body verbatim (facade does the FriendInfo mapping)', async () => { + const body = { friends: [{ uin: 10001, uid: 'u', additional: [] }], next: { uin: 0 } }; + const sender = makeSender(body as any); + const out = await FetchFriendListPage.invoke(sender, { nextUin: null }); + expect(out.friends).toBeDefined(); + expect(out.next?.uin ?? 0).toBe(0); + }); + + it('encodes envelope body correctly', async () => { + const sender = makeSender({ friends: [] }); + await FetchFriendListPage.invoke(sender, { nextUin: 10001 }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.nextUin).toEqual({ uin: 10001 }); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-group-list.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-group-list.test.ts new file mode 100644 index 00000000..ac2f1832 --- /dev/null +++ b/packages/protocol/tests/oidb-services/contacts/fetch-group-list.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupListRequest } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { FetchGroupList } from '../../../src/oidb-services/contacts/fetch-group-list'; + +function makeSender() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('FetchGroupList namespace', () => { + it('declares 0xFE5_2 with uinForm=true', () => { + expect(FetchGroupList.command).toBe(0xFE5); + expect(FetchGroupList.subCommand).toBe(2); + expect(FetchGroupList.uinForm).toBe(true); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0xfe5_2 with envelope reserved=1', async () => { + const sender = makeSender(); + await FetchGroupList.invoke(sender); + const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0xfe5_2'); + const env = protobuf_decode>(bytes); + expect(env.reserved).toBe(1); + }); + + it('sends the verbatim config blob (field5002/5003 OFF to avoid EPIPE on big rosters)', async () => { + const sender = makeSender(); + await FetchGroupList.invoke(sender); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.config?.config1?.groupName).toBe(true); + expect(env.body?.config?.config1?.memberCount).toBe(true); + // proto3 default false — omitted on wire, decoded as null. + expect(env.body?.config?.config1?.field5002 ?? false).toBe(false); + expect(env.body?.config?.config1?.field5003 ?? false).toBe(false); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-group-member-list-page.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-group-member-list-page.test.ts new file mode 100644 index 00000000..6241feed --- /dev/null +++ b/packages/protocol/tests/oidb-services/contacts/fetch-group-member-list-page.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupMemberListRequest } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { FetchGroupMemberListPage } from '../../../src/oidb-services/contacts/fetch-group-member-list-page'; + +function makeSender() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('FetchGroupMemberListPage namespace', () => { + it('declares 0xFE7_3', () => { + expect(FetchGroupMemberListPage.command).toBe(0xFE7); + expect(FetchGroupMemberListPage.subCommand).toBe(3); + }); + + describe('serialize', () => { + it('omits the token on the first page', () => { + const out = FetchGroupMemberListPage.serialize({} as any, { groupId: 12345, token: '' }) as any; + expect(out.token).toBeUndefined(); + expect(out.groupUin).toBe(12345); + }); + + it('threads the server-issued token into follow-up pages', () => { + const out = FetchGroupMemberListPage.serialize({} as any, { groupId: 12345, token: 'next-cursor' }) as any; + expect(out.token).toBe('next-cursor'); + }); + + it('always requests the full member-field projection', () => { + const out = FetchGroupMemberListPage.serialize({} as any, { groupId: 1, token: '' }) as any; + expect(out.body).toMatchObject({ + memberName: true, memberCard: true, level: true, + joinTimestamp: true, lastMsgTimestamp: true, shutUpTimestamp: true, + permission: true, + }); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0xfe7_3', async () => { + const sender = makeSender(); + await FetchGroupMemberListPage.invoke(sender, { groupId: 1, token: '' }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xfe7_3'); + }); + + it('encodes envelope body with the groupId', async () => { + const sender = makeSender(); + await FetchGroupMemberListPage.invoke(sender, { groupId: 12345, token: '' }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.groupUin).toBe(12345); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-group-requests.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-group-requests.test.ts new file mode 100644 index 00000000..d45232e7 --- /dev/null +++ b/packages/protocol/tests/oidb-services/contacts/fetch-group-requests.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupRequestList } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { FetchGroupRequests } from '../../../src/oidb-services/contacts/fetch-group-requests'; + +function makeSender() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('FetchGroupRequests namespace', () => { + it('declares 0x10C0', () => { + expect(FetchGroupRequests.command).toBe(0x10C0); + }); + + describe('resolveSubCommand', () => { + it('returns 1 when filtered=false (main inbox)', () => { + expect(FetchGroupRequests.resolveSubCommand({ filtered: false })).toBe(1); + }); + it('returns 2 when filtered=true (low-priority inbox)', () => { + expect(FetchGroupRequests.resolveSubCommand({ filtered: true })).toBe(2); + }); + }); + + describe('serialize', () => { + it('always sends count=20 / field2=0', () => { + expect(FetchGroupRequests.serialize({} as any, { filtered: false })).toEqual({ count: 20, field2: 0 }); + expect(FetchGroupRequests.serialize({} as any, { filtered: true })).toEqual({ count: 20, field2: 0 }); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to 0x10c0_1 for the main inbox', async () => { + const sender = makeSender(); + await FetchGroupRequests.invoke(sender, { filtered: false }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x10c0_1'); + }); + + it('routes to 0x10c0_2 for the filtered inbox', async () => { + const sender = makeSender(); + await FetchGroupRequests.invoke(sender, { filtered: true }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x10c0_2'); + }); + + it('encodes envelope body with count=20', async () => { + const sender = makeSender(); + await FetchGroupRequests.invoke(sender, { filtered: false }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.count).toBe(20); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-user-profile-by-uid.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-user-profile-by-uid.test.ts new file mode 100644 index 00000000..3100d552 --- /dev/null +++ b/packages/protocol/tests/oidb-services/contacts/fetch-user-profile-by-uid.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbUserInfoByUidRequest, OidbUserInfoResponse, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { FetchUserProfileByUid } from '../../../src/oidb-services/contacts/fetch-user-profile-by-uid'; + +function makeSender(body?: OidbUserInfoResponse) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('FetchUserProfileByUid namespace (UID form)', () => { + it('declares 0xFE1_2 WITHOUT uinForm (reserved stays 0)', () => { + expect(FetchUserProfileByUid.command).toBe(0xFE1); + expect(FetchUserProfileByUid.subCommand).toBe(2); + // No `uinForm` exposed — matches Lagrange's isUid=false path on + // the UID variant. Important because the server distinguishes + // UIN vs UID requests via the envelope's `reserved` field. + expect((FetchUserProfileByUid as any).uinForm).toBeUndefined(); + }); + + it('packages the uid as field 1 (string), routes to OidbSvcTrpcTcp.0xfe1_2', async () => { + const sender = makeSender({ body: { uin: 950929451, uid: 'u_abc' } as any }); + await FetchUserProfileByUid.invoke(sender, { uid: 'u_abc' }); + const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2'); + const env = protobuf_decode>(bytes); + expect(env.body?.uid).toBe('u_abc'); + // reserved=0 (default, omitted on wire) because this is the UID + // variant — Lagrange's `OidbSvcTrpcTcp0xFE1_2.cs:9` does the same. + expect(env.reserved ?? 0).toBe(0); + }); + + it('requests the same property key catalogue as the UIN variant', async () => { + const sender = makeSender({ body: { uin: 1, uid: 'u' } as any }); + await FetchUserProfileByUid.invoke(sender, { uid: 'u' }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + const keys = env.body?.keys?.map(k => k.key); + expect(keys).toContain(20002); // nickname — the whole point + expect(keys).toContain(105); // QQ level + }); + + it('decodes nickname + uin from the response so the pipeline can fill them into the event', async () => { + // This is the actual point of the namespace — the stranger's + // nickname + uin lands here so the pipeline can patch them onto + // the in-flight group_invite event. + const enc = (s: string) => new TextEncoder().encode(s); + const sender = makeSender({ + body: { + uin: 950929451, uid: 'u_abc', + properties: { + bytesProperties: [{ code: 20002, value: enc('小明') }], + numberProperties: [], + }, + } as any, + }); + const out = await FetchUserProfileByUid.invoke(sender, { uid: 'u_abc' }); + expect(out.uin).toBe(950929451); + expect(out.nickname).toBe('小明'); + }); + + it('throws when the response body is missing entirely', async () => { + const sender = makeSender({}); + await expect(FetchUserProfileByUid.invoke(sender, { uid: 'u_abc' })) + .rejects.toThrow('user info response body missing'); + }); +}); diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-user-profile.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-user-profile.test.ts new file mode 100644 index 00000000..61432189 --- /dev/null +++ b/packages/protocol/tests/oidb-services/contacts/fetch-user-profile.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + AvatarInfo, OidbUserInfoRequest, OidbUserInfoResponse, +} from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { FetchUserProfile } from '../../../src/oidb-services/contacts/fetch-user-profile'; + +function makeSender(body?: OidbUserInfoResponse) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('FetchUserProfile namespace', () => { + it('declares 0xFE1_2 with uinForm=true', () => { + expect(FetchUserProfile.command).toBe(0xFE1); + expect(FetchUserProfile.subCommand).toBe(2); + expect(FetchUserProfile.uinForm).toBe(true); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0xfe1_2 with reserved=1', async () => { + const sender = makeSender({ body: { uin: 10001, uid: 'u' } as any }); + await FetchUserProfile.invoke(sender, { uin: 10001 }); + const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2'); + const env = protobuf_decode>(bytes); + expect(env.reserved).toBe(1); + }); + + it('requests every property key in the catalogue (nickname, level, …)', async () => { + const sender = makeSender({ body: { uin: 10001, uid: 'u' } as any }); + await FetchUserProfile.invoke(sender, { uin: 10001 }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + const keys = env.body?.keys?.map(k => k.key); + expect(keys).toContain(20002); // nickname + expect(keys).toContain(105); // level + expect(keys).toContain(101); // avatar + expect(keys).toContain(102); // sign + expect(keys).toContain(103); // remark + }); + + it('decodes nickname / remark / qid / sign from bytes-properties', async () => { + const enc = (s: string) => new TextEncoder().encode(s); + const sender = makeSender({ + body: { + uin: 10001, uid: 'u', + properties: { + bytesProperties: [ + { code: 20002, value: enc('Nick') }, + { code: 103, value: enc('Bestie') }, + { code: 27394, value: enc('myqid') }, + { code: 102, value: enc('Hello') }, + ], + numberProperties: [], + }, + } as any, + }); + const out = await FetchUserProfile.invoke(sender, { uin: 10001 }); + expect(out.nickname).toBe('Nick'); + expect(out.remark).toBe('Bestie'); + expect(out.qid).toBe('myqid'); + expect(out.sign).toBe('Hello'); + }); + + it('decodes sex / age / level from number-properties (sex enum)', async () => { + const cases: Array<[number, string]> = [ + [1, 'male'], [2, 'female'], [255, 'unknown'], [0, 'unknown'], + ]; + for (const [sexNum, expected] of cases) { + const sender = makeSender({ + body: { + uin: 1, uid: 'u', + properties: { + bytesProperties: [], + numberProperties: [ + { number1: 20009, number2: sexNum }, + { number1: 20037, number2: 25 }, + { number1: 105, number2: 7 }, + ], + }, + } as any, + }); + const out = await FetchUserProfile.invoke(sender, { uin: 1 }); + expect(out.sex).toBe(expected); + expect(out.age).toBe(25); + expect(out.level).toBe(7); + } + }); + + it('decodes the avatar URL with the "640" size suffix appended', async () => { + const avatarBytes = protobuf_encode({ url: 'https://q.qlogo.cn/abc/' }); + const sender = makeSender({ + body: { + uin: 10001, uid: 'u', + properties: { + bytesProperties: [{ code: 101, value: avatarBytes }], + numberProperties: [], + }, + } as any, + }); + const out = await FetchUserProfile.invoke(sender, { uin: 10001 }); + expect(out.avatar).toBe('https://q.qlogo.cn/abc/640'); + }); + + it('defaults uin to the requested value when the server omits its echo', async () => { + const sender = makeSender({ body: { uid: 'u' } as any }); + const out = await FetchUserProfile.invoke(sender, { uin: 99999 }); + expect(out.uin).toBe(99999); + }); + + it('throws when body is entirely missing from the envelope', async () => { + const sender = makeSender({}); + await expect(FetchUserProfile.invoke(sender, { uin: 1 })) + .rejects.toThrow('user info response body missing'); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/extras/fetch-ai-voice-list.test.ts b/packages/protocol/tests/oidb-services/extras/fetch-ai-voice-list.test.ts new file mode 100644 index 00000000..8cc14ad3 --- /dev/null +++ b/packages/protocol/tests/oidb-services/extras/fetch-ai-voice-list.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbAiVoiceListReq, OidbAiVoiceListResp } from '@snowluma/proto-defs/oidb-actions/media'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { FetchAiVoiceList } from '../../../src/oidb-services/extras/fetch-ai-voice-list'; + +function makeSender(body?: OidbAiVoiceListResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('FetchAiVoiceList namespace', () => { + it('declares 0x929D_0', () => { + expect(FetchAiVoiceList.command).toBe(0x929D); + expect(FetchAiVoiceList.subCommand).toBe(0); + }); + + describe('serialize', () => { + it('passes groupUin / chatType verbatim', () => { + expect(FetchAiVoiceList.serialize({} as any, { groupId: 4242, chatType: 1 })).toEqual({ + groupUin: 4242, chatType: 1, + }); + }); + }); + + describe('deserialize', () => { + it('returns content array verbatim', () => { + const out = FetchAiVoiceList.deserialize({} as any, { + content: [ + { category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] }, + ], + }); + expect(out).toEqual([ + { category: 'cute', voices: [{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://x' }] }, + ]); + }); + + it('returns [] when content is omitted', () => { + expect(FetchAiVoiceList.deserialize({} as any, {})).toEqual([]); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0x929d_0', async () => { + const sender = makeSender({ content: [] }); + await FetchAiVoiceList.invoke(sender, { groupId: 100, chatType: 1 }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x929d_0'); + }); + + it('encodes envelope body correctly', async () => { + const sender = makeSender({ content: [] }); + await FetchAiVoiceList.invoke(sender, { groupId: 4242, chatType: 2 }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ groupUin: 4242, chatType: 2 }); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/extras/fetch-ai-voice.test.ts b/packages/protocol/tests/oidb-services/extras/fetch-ai-voice.test.ts new file mode 100644 index 00000000..69e0dd25 --- /dev/null +++ b/packages/protocol/tests/oidb-services/extras/fetch-ai-voice.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbAiVoiceReq, OidbAiVoiceResp } from '@snowluma/proto-defs/oidb-actions/media'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { FetchAiVoice } from '../../../src/oidb-services/extras/fetch-ai-voice'; + +function makeSender(body?: OidbAiVoiceResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('FetchAiVoice namespace', () => { + it('declares 0x929B_0', () => { + expect(FetchAiVoice.command).toBe(0x929B); + expect(FetchAiVoice.subCommand).toBe(0); + }); + + describe('serialize', () => { + it('packages every field including sessionId into session sub-message', () => { + const out = FetchAiVoice.serialize({} as any, { + groupId: 100, voiceId: 'v', text: 'hi', chatType: 1, sessionId: 0xCAFE, + }); + expect(out).toEqual({ + groupUin: 100, voiceId: 'v', text: 'hi', chatType: 1, + session: { sessionId: 0xCAFE }, + }); + }); + }); + + describe('deserialize', () => { + it('returns the first msgInfoBody index when present', () => { + const node = { fileUuid: 'uuid', subType: 1 }; + expect(FetchAiVoice.deserialize({} as any, { + msgInfo: { msgInfoBody: [{ index: node }] }, + } as any)).toMatchObject(node); + }); + + it('returns null when msgInfo is empty / missing', () => { + expect(FetchAiVoice.deserialize({} as any, {} as any)).toBeNull(); + expect(FetchAiVoice.deserialize({} as any, { msgInfo: {} } as any)).toBeNull(); + expect(FetchAiVoice.deserialize({} as any, { msgInfo: { msgInfoBody: [] } } as any)).toBeNull(); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0x929b_0', async () => { + const sender = makeSender({ msgInfo: { msgInfoBody: [{ index: { fileUuid: 'u' } }] } } as any); + await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 1 }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x929b_0'); + }); + + it('returns the parsed index node', async () => { + const node = { fileUuid: 'uuid', subType: 1 }; + const sender = makeSender({ msgInfo: { msgInfoBody: [{ index: node }] } } as any); + const out = await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 1 }); + expect(out).toMatchObject(node); + }); + + it('returns null when server polls back empty msgInfo (in-flight)', async () => { + const sender = makeSender({} as any); + const out = await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 1 }); + expect(out).toBeNull(); + }); + + it('passes the sessionId through to the wire envelope verbatim', async () => { + const sender = makeSender({} as any); + await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 0xCAFEBABE }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.session?.sessionId).toBe(0xCAFEBABE); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/extras/get-stranger-status.test.ts b/packages/protocol/tests/oidb-services/extras/get-stranger-status.test.ts new file mode 100644 index 00000000..83575105 --- /dev/null +++ b/packages/protocol/tests/oidb-services/extras/get-stranger-status.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbStrangerStatusReq, OidbStrangerStatusResp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetStrangerStatus } from '../../../src/oidb-services/extras/get-stranger-status'; + +function makeSender(body?: OidbStrangerStatusResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('GetStrangerStatus namespace', () => { + it('declares 0xFE1_2 with uinForm=true', () => { + expect(GetStrangerStatus.command).toBe(0xFE1); + expect(GetStrangerStatus.subCommand).toBe(2); + expect(GetStrangerStatus.uinForm).toBe(true); + }); + + describe('serialize', () => { + it('always queries only key 27372 (status property)', () => { + const out = GetStrangerStatus.serialize({} as any, { uin: 100200 }); + expect(out).toEqual({ uin: 100200, key: [{ key: 27372 }] }); + }); + }); + + describe('deserialize', () => { + it('low-band (≤10) values map to (value*10, 0)', () => { + expect(GetStrangerStatus.deserialize({} as any, { data: { status: { value: 7n } } })).toEqual({ status: 70, ext_status: 0 }); + expect(GetStrangerStatus.deserialize({} as any, { data: { status: { value: 10n } } })).toEqual({ status: 100, ext_status: 0 }); + }); + + it('high-band values decompose into (0xff00 + (>>16 & 0xff)) ext_status', () => { + // 0x42F100 → bits 8..15 = 0xF1<<8 = 0xF100, bits 16..23 = 0x42 → 0xF142 + expect(GetStrangerStatus.deserialize({} as any, { data: { status: { value: 0x42F100n } } })) + .toEqual({ status: 10, ext_status: 0xF142 }); + }); + + it('returns null when status field is missing', () => { + expect(GetStrangerStatus.deserialize({} as any, {})).toBeNull(); + expect(GetStrangerStatus.deserialize({} as any, { data: {} })).toBeNull(); + expect(GetStrangerStatus.deserialize({} as any, { data: { status: {} } })).toBeNull(); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0xfe1_2 with uinForm=true (envelope reserved=1)', async () => { + const sender = makeSender({ data: { status: { value: 5n } } }); + await GetStrangerStatus.invoke(sender, { uin: 100200 }); + const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0xfe1_2'); + const env = protobuf_decode>(bytes); + expect(env.reserved).toBe(1); + }); + + it('returns the decoded status object', async () => { + const sender = makeSender({ data: { status: { value: 5n } } }); + const out = await GetStrangerStatus.invoke(sender, { uin: 1 }); + expect(out).toEqual({ status: 50, ext_status: 0 }); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/extras/group-todo.test.ts b/packages/protocol/tests/oidb-services/extras/group-todo.test.ts new file mode 100644 index 00000000..90098106 --- /dev/null +++ b/packages/protocol/tests/oidb-services/extras/group-todo.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupTodo } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GroupTodo } from '../../../src/oidb-services/extras/group-todo'; + +function makeSender() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('GroupTodo namespace', () => { + it('declares 0xF90', () => { + expect(GroupTodo.command).toBe(0xF90); + }); + + describe('resolveSubCommand', () => { + it('maps set → 1', () => { + expect(GroupTodo.resolveSubCommand({ groupId: 1, msgSeq: 1n, action: 'set' })).toBe(1); + }); + it('maps complete → 2', () => { + expect(GroupTodo.resolveSubCommand({ groupId: 1, msgSeq: 1n, action: 'complete' })).toBe(2); + }); + it('maps cancel → 3', () => { + expect(GroupTodo.resolveSubCommand({ groupId: 1, msgSeq: 1n, action: 'cancel' })).toBe(3); + }); + }); + + describe('serialize', () => { + it('packages groupUin + msgSeq verbatim regardless of action', () => { + for (const action of ['set', 'complete', 'cancel'] as const) { + const out = GroupTodo.serialize({} as any, { groupId: 12345, msgSeq: 9876543210n, action }); + expect(out).toEqual({ groupUin: 12345, msgSeq: 9876543210n }); + } + }); + }); + + describe('invoke (e2e)', () => { + it.each([ + ['set', 'OidbSvcTrpcTcp.0xf90_1'] as const, + ['complete', 'OidbSvcTrpcTcp.0xf90_2'] as const, + ['cancel', 'OidbSvcTrpcTcp.0xf90_3'] as const, + ])('action %s routes to %s', async (action, expectedWire) => { + const sender = makeSender(); + await GroupTodo.invoke(sender, { groupId: 12345, msgSeq: 100n, action }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe(expectedWire); + }); + + it('encodes envelope body correctly', async () => { + const sender = makeSender(); + await GroupTodo.invoke(sender, { groupId: 100, msgSeq: 999n, action: 'set' }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body).toEqual({ groupUin: 100, msgSeq: 999n }); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/friend/delete-friend.test.ts b/packages/protocol/tests/oidb-services/friend/delete-friend.test.ts new file mode 100644 index 00000000..af8d17d3 --- /dev/null +++ b/packages/protocol/tests/oidb-services/friend/delete-friend.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbDeleteFriend } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { DeleteFriend } from '../../../src/oidb-services/friend/delete-friend'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + resolveUserUid: vi.fn(async () => 'resolved-uid'), + }; +} + +describe('DeleteFriend namespace', () => { + it('declares 0x126B_0', () => { + expect(DeleteFriend.command).toBe(0x126B); + expect(DeleteFriend.subCommand).toBe(0); + }); + + describe('invoke', () => { + it('routes to OidbSvcTrpcTcp.0x126b_0', async () => { + const deps = makeDeps(); + await DeleteFriend.invoke(deps, { userId: 10001 }); + expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x126b_0'); + }); + + it('resolves the target uid before encoding', async () => { + const deps = makeDeps(); + await DeleteFriend.invoke(deps, { userId: 10001 }); + expect(deps.resolveUserUid).toHaveBeenCalledWith(10001); + }); + + it('packages the nested envelope with verbatim magic constants', async () => { + const deps = makeDeps(); + await DeleteFriend.invoke(deps, { userId: 10001, block: true }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.field1).toMatchObject({ + targetUid: 'resolved-uid', + block: true, + field2: { + field1: 130, + field2: 109, + field3: { field1: 8, field2: 8, field3: 50 }, + }, + }); + }); + + it('defaults block to false (no block flag)', async () => { + const deps = makeDeps(); + await DeleteFriend.invoke(deps, { userId: 10001 }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + // proto3 false omitted on wire — decoded as null/undefined. + expect(env.body?.field1?.block ?? false).toBe(false); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/friend/handle-friend-request.test.ts b/packages/protocol/tests/oidb-services/friend/handle-friend-request.test.ts new file mode 100644 index 00000000..443214f4 --- /dev/null +++ b/packages/protocol/tests/oidb-services/friend/handle-friend-request.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbFriendRequestAction } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { HandleFriendRequest } from '../../../src/oidb-services/friend/handle-friend-request'; + +function makeDeps(resolvedUid = 'resolved-uid') { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + resolveUserUid: vi.fn(async () => resolvedUid), + }; +} + +describe('HandleFriendRequest namespace', () => { + it('declares 0xB5D_44', () => { + expect(HandleFriendRequest.command).toBe(0xB5D); + expect(HandleFriendRequest.subCommand).toBe(44); + }); + + describe('invoke', () => { + it('routes to OidbSvcTrpcTcp.0xb5d_44', async () => { + const deps = makeDeps(); + await HandleFriendRequest.invoke(deps, { uidOrFlag: 'uid', approve: true }); + expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xb5d_44'); + }); + + it('detects digit-only flag → resolves via resolveUserUid', async () => { + const deps = makeDeps('resolved-from-uin'); + await HandleFriendRequest.invoke(deps, { uidOrFlag: '10001', approve: true }); + expect(deps.resolveUserUid).toHaveBeenCalledWith(10001); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.targetUid).toBe('resolved-from-uin'); + }); + + it('passes non-numeric flag through verbatim (no resolveUserUid call)', async () => { + const deps = makeDeps(); + await HandleFriendRequest.invoke(deps, { uidOrFlag: 'flag-abc', approve: false }); + expect(deps.resolveUserUid).not.toHaveBeenCalled(); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.targetUid).toBe('flag-abc'); + }); + + it('encodes accept=3 when approve=true', async () => { + const deps = makeDeps(); + await HandleFriendRequest.invoke(deps, { uidOrFlag: 'u', approve: true }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.accept).toBe(3); + }); + + it('encodes accept=5 when approve=false', async () => { + const deps = makeDeps(); + await HandleFriendRequest.invoke(deps, { uidOrFlag: 'u', approve: false }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.accept).toBe(5); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/friend/set-friend-remark.test.ts b/packages/protocol/tests/oidb-services/friend/set-friend-remark.test.ts new file mode 100644 index 00000000..9ff62512 --- /dev/null +++ b/packages/protocol/tests/oidb-services/friend/set-friend-remark.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbSetFriendRemark } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetFriendRemark } from '../../../src/oidb-services/friend/set-friend-remark'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + resolveUserUid: vi.fn(async () => 'resolved-uid'), + }; +} + +describe('SetFriendRemark namespace', () => { + it('declares 0xB6E_2', () => { + expect(SetFriendRemark.command).toBe(0xB6E); + expect(SetFriendRemark.subCommand).toBe(2); + }); + + describe('invoke', () => { + it('routes to OidbSvcTrpcTcp.0xb6e_2', async () => { + const deps = makeDeps(); + await SetFriendRemark.invoke(deps, { userId: 10001, remark: 'x' }); + expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xb6e_2'); + }); + + it('resolves the target uid before encoding', async () => { + const deps = makeDeps(); + await SetFriendRemark.invoke(deps, { userId: 10001, remark: 'best-friend' }); + expect(deps.resolveUserUid).toHaveBeenCalledWith(10001); + }); + + it('packages uid + remark in body', async () => { + const deps = makeDeps(); + await SetFriendRemark.invoke(deps, { userId: 10001, remark: 'best-friend' }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ targetUid: 'resolved-uid', remark: 'best-friend' }); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/get-at-all-remain.test.ts b/packages/protocol/tests/oidb-services/group-admin/get-at-all-remain.test.ts new file mode 100644 index 00000000..43546823 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/get-at-all-remain.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x8a7Req, Oidb0x8a7Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetAtAllRemain } from '../../../src/oidb-services/group-admin/get-at-all-remain'; + +function makeDeps(body?: Oidb0x8a7Resp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { + sendRawPacket: vi.fn(async () => r), + identity: { uin: '10001' } as any, + }; +} + +describe('GetAtAllRemain namespace', () => { + it('declares 0x8A7_0', () => { + expect(GetAtAllRemain.command).toBe(0x8A7); + expect(GetAtAllRemain.subCommand).toBe(0); + }); + + it('emits the basic{1,2,3}=1,2,1 cookie + bot uin + groupId, routes to 0x8a7_0', async () => { + const deps = makeDeps({ canAtAll: true, groupRemain: 12, uinRemain: 5 }); + await GetAtAllRemain.invoke(deps, { groupId: 12345 }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x8a7_0'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ + basic1: 1, basic2: 2, basic3: 1, + uin: 10001n, + groupId: 12345n, + }); + }); + + it('decodes canAtAll + groupRemain + uinRemain as plain numbers / boolean', async () => { + const deps = makeDeps({ canAtAll: true, groupRemain: 12, uinRemain: 5 }); + const out = await GetAtAllRemain.invoke(deps, { groupId: 12345 }); + expect(out).toEqual({ + can_at_all: true, + remain_at_all_count_for_group: 12, + remain_at_all_count_for_uin: 5, + }); + }); + + it('falls back to false / 0 when the response body is empty', async () => { + const deps = makeDeps({} as any); + const out = await GetAtAllRemain.invoke(deps, { groupId: 1 }); + expect(out).toEqual({ + can_at_all: false, + remain_at_all_count_for_group: 0, + remain_at_all_count_for_uin: 0, + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/kick-member.test.ts b/packages/protocol/tests/oidb-services/group-admin/kick-member.test.ts new file mode 100644 index 00000000..5b2bf030 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/kick-member.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbKickMember } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { KickMember } from '../../../src/oidb-services/group-admin/kick-member'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + resolveUserUid: vi.fn(async () => 'resolved-uid'), + }; +} + +describe('KickMember namespace', () => { + it('declares 0x8A0_1', () => { + expect(KickMember.command).toBe(0x8A0); + expect(KickMember.subCommand).toBe(1); + }); + + it('resolves uid per-group and forwards reject + reason', async () => { + const deps = makeDeps(); + await KickMember.invoke(deps, { groupId: 12345, userId: 67890, reject: true, reason: 'bye' }); + expect(deps.resolveUserUid).toHaveBeenCalledWith(67890, 12345); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x8a0_1'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ + groupUin: 12345, targetUid: 'resolved-uid', rejectAddRequest: true, reason: 'bye', + }); + }); + + it('defaults reason to empty string', async () => { + const deps = makeDeps(); + await KickMember.invoke(deps, { groupId: 1, userId: 2, reject: false }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.reason ?? '').toBe(''); + expect(env.body?.rejectAddRequest ?? false).toBe(false); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/kick-members.test.ts b/packages/protocol/tests/oidb-services/group-admin/kick-members.test.ts new file mode 100644 index 00000000..1c979adf --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/kick-members.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x8a0Req } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { KickMembers } from '../../../src/oidb-services/group-admin/kick-members'; + +function makeDeps(resolveSequence: string[] = ['uid-a', 'uid-b']) { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + const resolveUserUid = vi.fn(); + for (const uid of resolveSequence) resolveUserUid.mockResolvedValueOnce(uid); + return { + sendRawPacket: vi.fn(async () => r), + resolveUserUid, + }; +} + +describe('KickMembers namespace', () => { + it('declares 0x8A0_1 (same as KickMember; disambiguated by proto body)', () => { + expect(KickMembers.command).toBe(0x8A0); + expect(KickMembers.subCommand).toBe(1); + }); + + it('resolves each uid in parallel and packages targetUids[]', async () => { + const deps = makeDeps(['uid-a', 'uid-b']); + await KickMembers.invoke(deps, { groupId: 12345, userIds: [11, 22], reject: false }); + expect(deps.resolveUserUid).toHaveBeenCalledTimes(2); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x8a0_1'); + const env = protobuf_decode>(bytes); + expect(env.body?.targetUids).toEqual(['uid-a', 'uid-b']); + expect(env.body?.groupId).toBe(12345n); + expect(env.body?.rejectAddRequest ?? 0).toBe(0); + }); + + it('reject=true => rejectAddRequest=1', async () => { + const deps = makeDeps(['u']); + await KickMembers.invoke(deps, { groupId: 1, userIds: [2], reject: true }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.rejectAddRequest).toBe(1); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/leave-group.test.ts b/packages/protocol/tests/oidb-services/group-admin/leave-group.test.ts new file mode 100644 index 00000000..900321df --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/leave-group.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbLeaveGroup } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { LeaveGroup } from '../../../src/oidb-services/group-admin/leave-group'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('LeaveGroup namespace', () => { + it('declares 0x1097_1', () => { + expect(LeaveGroup.command).toBe(0x1097); + expect(LeaveGroup.subCommand).toBe(1); + }); + + it('routes to 0x1097_1 with groupUin only', async () => { + const deps = makeDeps(); + await LeaveGroup.invoke(deps, { groupId: 12345 }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x1097_1'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ groupUin: 12345 }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/mute-all.test.ts b/packages/protocol/tests/oidb-services/group-admin/mute-all.test.ts new file mode 100644 index 00000000..18f9d2b0 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/mute-all.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbMuteAll } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { MuteAll } from '../../../src/oidb-services/group-admin/mute-all'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('MuteAll namespace', () => { + it('declares 0x89A_0', () => { + expect(MuteAll.command).toBe(0x89A); + expect(MuteAll.subCommand).toBe(0); + }); + + it('enable=true emits the 0xFFFFFFFF "permanent" state', async () => { + const deps = makeDeps(); + await MuteAll.invoke(deps, { groupId: 12345, enable: true }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x89a_0'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ groupUin: 12345, muteState: { state: 0xFFFFFFFF } }); + }); + + it('enable=false emits state=0', async () => { + const deps = makeDeps(); + await MuteAll.invoke(deps, { groupId: 12345, enable: false }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + // proto3 default 0 fields are omitted on the wire. + expect(env.body?.muteState?.state ?? 0).toBe(0); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/mute-member.test.ts b/packages/protocol/tests/oidb-services/group-admin/mute-member.test.ts new file mode 100644 index 00000000..01ffb304 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/mute-member.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbMuteMember } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { MuteMember } from '../../../src/oidb-services/group-admin/mute-member'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + resolveUserUid: vi.fn(async () => 'resolved-uid'), + }; +} + +describe('MuteMember namespace', () => { + it('declares 0x1253_1', () => { + expect(MuteMember.command).toBe(0x1253); + expect(MuteMember.subCommand).toBe(1); + }); + + it('resolves uid before encoding and routes to 0x1253_1', async () => { + const deps = makeDeps(); + await MuteMember.invoke(deps, { groupId: 12345, userId: 67890, duration: 600 }); + expect(deps.resolveUserUid).toHaveBeenCalledWith(67890, 12345); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x1253_1'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ + groupUin: 12345, type: 1, + body: { targetUid: 'resolved-uid', duration: 600 }, + }); + }); + + it('duration = 0 acts as unmute', async () => { + const deps = makeDeps(); + await MuteMember.invoke(deps, { groupId: 1, userId: 2, duration: 0 }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + // duration=0 is the proto3 default and is omitted on the wire. + expect(env.body?.body?.duration ?? 0).toBe(0); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/set-add-option.test.ts b/packages/protocol/tests/oidb-services/group-admin/set-add-option.test.ts new file mode 100644 index 00000000..0a774eef --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/set-add-option.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x89a_0AddOption } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetAddOption } from '../../../src/oidb-services/group-admin/set-add-option'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('SetAddOption namespace', () => { + it('declares 0x89A_0 (shared cmd with MuteAll / SetSearch / SetGroupName)', () => { + expect(SetAddOption.command).toBe(0x89A); + expect(SetAddOption.subCommand).toBe(0); + }); + + it('packages settings.addType and routes to 0x89a_0', async () => { + const deps = makeDeps(); + await SetAddOption.invoke(deps, { groupId: 12345, addType: 2 }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x89a_0'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ groupUin: 12345n, settings: { addType: 2 } }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/set-add-request.test.ts b/packages/protocol/tests/oidb-services/group-admin/set-add-request.test.ts new file mode 100644 index 00000000..582146ac --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/set-add-request.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupRequestAction } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetAddRequest } from '../../../src/oidb-services/group-admin/set-add-request'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('SetAddRequest namespace', () => { + it('declares 0x10C8 with uinForm=true and dynamic subCommand', () => { + expect(SetAddRequest.command).toBe(0x10C8); + expect(SetAddRequest.uinForm).toBe(true); + expect(SetAddRequest.resolveSubCommand({ groupId: 1, sequence: 1, eventType: 0, approve: true, filtered: false })).toBe(1); + expect(SetAddRequest.resolveSubCommand({ groupId: 1, sequence: 1, eventType: 0, approve: true, filtered: true })).toBe(2); + }); + + it('approve=true => accept=1, filtered=false => 0x10c8_1, reserved=1 (uinForm)', async () => { + const deps = makeDeps(); + await SetAddRequest.invoke(deps, { groupId: 12345, sequence: 5, eventType: 1, approve: true, reason: 'ok' }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x10c8_1'); + const env = protobuf_decode>(bytes); + expect(env.reserved).toBe(1); + expect(env.body?.accept).toBe(1); + expect(env.body?.body).toMatchObject({ + sequence: 5n, eventType: 1, groupUin: 12345, message: 'ok', + }); + }); + + it('approve=false + filtered=true => accept=2, 0x10c8_2', async () => { + const deps = makeDeps(); + await SetAddRequest.invoke(deps, { groupId: 12345, sequence: 5, eventType: 1, approve: false, reason: 'no', filtered: true }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x10c8_2'); + const env = protobuf_decode>(bytes); + expect(env.body?.accept).toBe(2); + }); + + it('defaults reason to empty string', async () => { + const deps = makeDeps(); + await SetAddRequest.invoke(deps, { groupId: 1, sequence: 1, eventType: 0, approve: true }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + // proto3 empty string omitted on the wire. + expect(env.body?.body?.message ?? '').toBe(''); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/set-admin.test.ts b/packages/protocol/tests/oidb-services/group-admin/set-admin.test.ts new file mode 100644 index 00000000..d769b093 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/set-admin.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbSetAdmin } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetAdmin } from '../../../src/oidb-services/group-admin/set-admin'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + resolveUserUid: vi.fn(async () => 'resolved-uid'), + }; +} + +describe('SetAdmin namespace', () => { + it('declares 0x1096_1', () => { + expect(SetAdmin.command).toBe(0x1096); + expect(SetAdmin.subCommand).toBe(1); + }); + + it('enable=true promotes (isAdmin=true)', async () => { + const deps = makeDeps(); + await SetAdmin.invoke(deps, { groupId: 12345, userId: 67890, enable: true }); + expect(deps.resolveUserUid).toHaveBeenCalledWith(67890, 12345); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x1096_1'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ groupUin: 12345, uid: 'resolved-uid', isAdmin: true }); + }); + + it('enable=false demotes (isAdmin omitted on the wire)', async () => { + const deps = makeDeps(); + await SetAdmin.invoke(deps, { groupId: 1, userId: 2, enable: false }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.isAdmin ?? false).toBe(false); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/set-group-name.test.ts b/packages/protocol/tests/oidb-services/group-admin/set-group-name.test.ts new file mode 100644 index 00000000..26c8d530 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/set-group-name.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbRenameGroup } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetGroupName } from '../../../src/oidb-services/group-admin/set-group-name'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('SetGroupName namespace', () => { + it('declares 0x89A_15', () => { + expect(SetGroupName.command).toBe(0x89A); + expect(SetGroupName.subCommand).toBe(15); + }); + + it('routes to 0x89a_15 with the new name', async () => { + const deps = makeDeps(); + await SetGroupName.invoke(deps, { groupId: 12345, name: 'newName' }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x89a_15'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ groupUin: 12345, body: { targetName: 'newName' } }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/set-group-remark.test.ts b/packages/protocol/tests/oidb-services/group-admin/set-group-remark.test.ts new file mode 100644 index 00000000..26ba8a82 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/set-group-remark.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0xf16Req } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetGroupRemark } from '../../../src/oidb-services/group-admin/set-group-remark'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('SetGroupRemark namespace', () => { + it('declares 0xF16_1', () => { + expect(SetGroupRemark.command).toBe(0xF16); + expect(SetGroupRemark.subCommand).toBe(1); + }); + + it('routes to 0xf16_1 with groupId + remark wrapped in inner', async () => { + const deps = makeDeps(); + await SetGroupRemark.invoke(deps, { groupId: 12345, remark: 'my group' }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0xf16_1'); + const env = protobuf_decode>(bytes); + expect(env.body?.inner).toMatchObject({ groupId: 12345n, remark: 'my group' }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/set-member-card.test.ts b/packages/protocol/tests/oidb-services/group-admin/set-member-card.test.ts new file mode 100644 index 00000000..87df196d --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/set-member-card.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbRenameMember } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetMemberCard } from '../../../src/oidb-services/group-admin/set-member-card'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + resolveUserUid: vi.fn(async () => 'resolved-uid'), + }; +} + +describe('SetMemberCard namespace', () => { + it('declares 0x8FC_3', () => { + expect(SetMemberCard.command).toBe(0x8FC); + expect(SetMemberCard.subCommand).toBe(3); + }); + + it('routes to 0x8fc_3 with targetUid + targetName', async () => { + const deps = makeDeps(); + await SetMemberCard.invoke(deps, { groupId: 12345, userId: 67890, card: 'newCard' }); + expect(deps.resolveUserUid).toHaveBeenCalledWith(67890, 12345); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x8fc_3'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ + groupUin: 12345, + body: { targetUid: 'resolved-uid', targetName: 'newCard' }, + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/set-search.test.ts b/packages/protocol/tests/oidb-services/group-admin/set-search.test.ts new file mode 100644 index 00000000..a191acf2 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/set-search.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x89a_0Search } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetSearch } from '../../../src/oidb-services/group-admin/set-search'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('SetSearch namespace', () => { + it('declares 0x89A_0 (shared cmd shape with other 0x89a_0 cmds)', () => { + expect(SetSearch.command).toBe(0x89A); + expect(SetSearch.subCommand).toBe(0); + }); + + it('emits an empty settings byte string and routes to 0x89a_0', async () => { + const deps = makeDeps(); + await SetSearch.invoke(deps, { groupId: 12345 }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x89a_0'); + const env = protobuf_decode>(bytes); + expect(env.body?.groupUin).toBe(12345n); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/set-special-title.test.ts b/packages/protocol/tests/oidb-services/group-admin/set-special-title.test.ts new file mode 100644 index 00000000..7ba68a9e --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-admin/set-special-title.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbSpecialTitle } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetSpecialTitle } from '../../../src/oidb-services/group-admin/set-special-title'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + resolveUserUid: vi.fn(async () => 'resolved-uid'), + }; +} + +describe('SetSpecialTitle namespace', () => { + it('declares 0x8FC_2', () => { + expect(SetSpecialTitle.command).toBe(0x8FC); + expect(SetSpecialTitle.subCommand).toBe(2); + }); + + it('routes to 0x8fc_2 with -1 (permanent) expireTime sentinel', async () => { + const deps = makeDeps(); + await SetSpecialTitle.invoke(deps, { groupId: 12345, userId: 67890, title: 'crown' }); + expect(deps.resolveUserUid).toHaveBeenCalledWith(67890, 12345); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x8fc_2'); + const env = protobuf_decode>(bytes); + expect(env.body?.groupUin).toBe(12345); + expect(env.body?.body?.targetUid).toBe('resolved-uid'); + expect(env.body?.body?.specialTitle).toBe('crown'); + // -1 (int_32) round-trips as 0xFFFFFFFF after the proton decoder reinterprets. + expect(env.body?.body?.expireTime).toBe(0xFFFFFFFF); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/create-group-folder.test.ts b/packages/protocol/tests/oidb-services/group-file/create-group-folder.test.ts new file mode 100644 index 00000000..62668888 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/create-group-folder.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileFolderReq, OidbGroupFileFolderResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { CreateGroupFolder } from '../../../src/oidb-services/group-file/create-group-folder'; + +function makeDeps(body?: OidbGroupFileFolderResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('CreateGroupFolder namespace', () => { + it('declares 0x6D7_0 with uinForm=true', () => { + expect(CreateGroupFolder.command).toBe(0x6D7); + expect(CreateGroupFolder.subCommand).toBe(0); + expect(CreateGroupFolder.uinForm).toBe(true); + }); + + it('packages create.{groupUin, rootDirectory, folderName}', async () => { + const deps = makeDeps({ create: {} as any }); + await CreateGroupFolder.invoke(deps, { groupId: 12345, parentId: '/', folderName: 'docs' }); + const env = protobuf_decode>(deps.sendRawPacket.mock.calls[0]![1]); + expect(env.body?.create).toMatchObject({ + groupUin: 12345, rootDirectory: '/', folderName: 'docs', + }); + }); + + it('throws on retcode != 0 (note: lower-case retcode in this proto)', async () => { + const deps = makeDeps({ create: { retcode: 7, retMsg: 'denied' } as any }); + await expect(CreateGroupFolder.invoke(deps, { groupId: 1, parentId: '/', folderName: 'f' })) + .rejects.toThrow(/code=7/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/delete-group-file.test.ts b/packages/protocol/tests/oidb-services/group-file/delete-group-file.test.ts new file mode 100644 index 00000000..1a6d8f09 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/delete-group-file.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileReq, OidbGroupFileResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { DeleteGroupFile } from '../../../src/oidb-services/group-file/delete-group-file'; + +function makeDeps(body?: OidbGroupFileResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('DeleteGroupFile namespace', () => { + it('declares 0x6D6_3 with uinForm=true', () => { + expect(DeleteGroupFile.command).toBe(0x6D6); + expect(DeleteGroupFile.subCommand).toBe(3); + expect(DeleteGroupFile.uinForm).toBe(true); + }); + + it('packages busId=102 and routes to 0x6d6_3', async () => { + const deps = makeDeps({ delete: {} as any }); + await DeleteGroupFile.invoke(deps, { groupId: 12345, fileId: 'fid' }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x6d6_3'); + const env = protobuf_decode>(bytes); + expect(env.body?.delete).toMatchObject({ groupUin: 12345, busId: 102, fileId: 'fid' }); + }); + + it('throws on missing delete sub-message', async () => { + const deps = makeDeps({}); + await expect(DeleteGroupFile.invoke(deps, { groupId: 1, fileId: 'f' })) + .rejects.toThrow(/delete response missing/); + }); + + it('throws on non-zero retCode', async () => { + const deps = makeDeps({ delete: { retCode: 5, retMsg: 'no perms' } as any }); + await expect(DeleteGroupFile.invoke(deps, { groupId: 1, fileId: 'f' })) + .rejects.toThrow(/code=5/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/delete-group-folder.test.ts b/packages/protocol/tests/oidb-services/group-file/delete-group-folder.test.ts new file mode 100644 index 00000000..6ff8a7d0 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/delete-group-folder.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileFolderReq, OidbGroupFileFolderResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { DeleteGroupFolder } from '../../../src/oidb-services/group-file/delete-group-folder'; + +function makeDeps(body?: OidbGroupFileFolderResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('DeleteGroupFolder namespace', () => { + it('declares 0x6D7_1 with uinForm=true', () => { + expect(DeleteGroupFolder.command).toBe(0x6D7); + expect(DeleteGroupFolder.subCommand).toBe(1); + expect(DeleteGroupFolder.uinForm).toBe(true); + }); + + it('packages delete.{groupUin, folderId}', async () => { + const deps = makeDeps({ delete: {} as any }); + await DeleteGroupFolder.invoke(deps, { groupId: 12345, folderId: 'fid' }); + const env = protobuf_decode>(deps.sendRawPacket.mock.calls[0]![1]); + expect(env.body?.delete).toMatchObject({ groupUin: 12345, folderId: 'fid' }); + }); + + it('throws on missing delete sub-message', async () => { + const deps = makeDeps({}); + await expect(DeleteGroupFolder.invoke(deps, { groupId: 1, folderId: 'f' })) + .rejects.toThrow(/folder delete response missing/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/get-group-file-count.test.ts b/packages/protocol/tests/oidb-services/group-file/get-group-file-count.test.ts new file mode 100644 index 00000000..3f45ac3b --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/get-group-file-count.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileCountViewReq, OidbGroupFileCountViewResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetGroupFileCount } from '../../../src/oidb-services/group-file/get-group-file-count'; + +function makeDeps(body?: OidbGroupFileCountViewResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('GetGroupFileCount namespace', () => { + it('declares 0x6D8_3', () => { + expect(GetGroupFileCount.command).toBe(0x6D8); + expect(GetGroupFileCount.subCommand).toBe(3); + }); + + it('routes to 0x6d8_3 with groupUin + appId=7 + busId=0', async () => { + const deps = makeDeps({ count: { fileCount: 1, maxCount: 100 } }); + await GetGroupFileCount.invoke(deps, { groupId: 12345 }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x6d8_3'); + const env = protobuf_decode>(bytes); + expect(env.body?.count).toMatchObject({ groupUin: 12345, appId: 7 }); + }); + + it('decodes both counters as plain numbers', async () => { + const deps = makeDeps({ count: { fileCount: 42, maxCount: 1000 } }); + const out = await GetGroupFileCount.invoke(deps, { groupId: 1 }); + expect(out).toEqual({ fileCount: 42, maxCount: 1000 }); + }); + + it('falls back to maxCount=10000 when the server elides it', async () => { + const deps = makeDeps({ count: {} }); + const out = await GetGroupFileCount.invoke(deps, { groupId: 1 }); + expect(out).toEqual({ fileCount: 0, maxCount: 10000 }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/get-group-file-url.test.ts b/packages/protocol/tests/oidb-services/group-file/get-group-file-url.test.ts new file mode 100644 index 00000000..b313a931 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/get-group-file-url.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileReq, OidbGroupFileResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetGroupFileUrl } from '../../../src/oidb-services/group-file/get-group-file-url'; + +function makeDeps(body?: OidbGroupFileResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('GetGroupFileUrl namespace', () => { + it('declares 0x6D6_2 with uinForm=true', () => { + expect(GetGroupFileUrl.command).toBe(0x6D6); + expect(GetGroupFileUrl.subCommand).toBe(2); + expect(GetGroupFileUrl.uinForm).toBe(true); + }); + + it('packages the download slot with the supplied busId', async () => { + const deps = makeDeps({ download: { downloadDns: 'cdn', downloadUrl: new Uint8Array([1, 2]) } as any }); + await GetGroupFileUrl.invoke(deps, { groupId: 12345, fileId: 'fid', busId: 102 }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x6d6_2'); + const env = protobuf_decode>(bytes); + expect(env.body?.download).toMatchObject({ + groupUin: 12345, appId: 7, busId: 102, fileId: 'fid', + }); + }); + + it('returns the download sub-message verbatim (URL composition lives on the facade)', async () => { + const deps = makeDeps({ download: { downloadDns: 'cdn', downloadUrl: new Uint8Array([0x01]) } as any }); + const out = await GetGroupFileUrl.invoke(deps, { groupId: 1, fileId: 'f', busId: 102 }); + expect(out.downloadDns).toBe('cdn'); + // proton round-trips bytes through a Node Buffer; assert the byte values, not the wrapper class. + expect(Array.from(out.downloadUrl ?? new Uint8Array())).toEqual([0x01]); + }); + + it('throws when the download sub-message is missing', async () => { + const deps = makeDeps({}); + await expect(GetGroupFileUrl.invoke(deps, { groupId: 1, fileId: 'f', busId: 102 })) + .rejects.toThrow(/url response missing/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/get-group-ptt-url.test.ts b/packages/protocol/tests/oidb-services/group-file/get-group-ptt-url.test.ts new file mode 100644 index 00000000..78b94444 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/get-group-ptt-url.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetGroupPttUrl } from '../../../src/oidb-services/group-file/get-group-ptt-url'; + +function makeDeps(body?: NTV2RichMediaResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('GetGroupPttUrl namespace', () => { + it('declares 0x126E_200 with uinForm=true', () => { + expect(GetGroupPttUrl.command).toBe(0x126E); + expect(GetGroupPttUrl.subCommand).toBe(200); + expect(GetGroupPttUrl.uinForm).toBe(true); + }); + + it('emits scene{requestType=1, businessType=3, sceneType=2, group.groupUin}', async () => { + const deps = makeDeps({ + respHead: { retCode: 0 }, + download: { info: { domain: 'd', urlPath: '/p' }, rKeyParam: '?rk' }, + } as any); + await GetGroupPttUrl.invoke(deps, { groupId: 12345, node: { fileUuid: 'uuid' } }); + const env = protobuf_decode>(deps.sendRawPacket.mock.calls[0]![1]); + expect(env.body?.reqHead?.scene).toMatchObject({ + requestType: 1, businessType: 3, sceneType: 2, + group: { groupUin: 12345 }, + }); + }); + + it('composes the https://domain URL', async () => { + const deps = makeDeps({ + respHead: { retCode: 0 }, + download: { info: { domain: 'cdn.qq', urlPath: '/x' }, rKeyParam: '?r=1' }, + } as any); + const out = await GetGroupPttUrl.invoke(deps, { groupId: 1, node: { fileUuid: 'uuid' } }); + expect(out).toBe('https://cdn.qq/x?r=1'); + }); + + it('throws when fileUuid is missing on the node', async () => { + const deps = makeDeps({} as any); + await expect(GetGroupPttUrl.invoke(deps, { groupId: 1, node: {} })) + .rejects.toThrow(/fileUuid is required/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/get-group-video-url.test.ts b/packages/protocol/tests/oidb-services/group-file/get-group-video-url.test.ts new file mode 100644 index 00000000..25ac1456 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/get-group-video-url.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetGroupVideoUrl } from '../../../src/oidb-services/group-file/get-group-video-url'; + +function makeDeps(body?: NTV2RichMediaResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('GetGroupVideoUrl namespace', () => { + it('declares 0x11EA_200 with uinForm=true', () => { + expect(GetGroupVideoUrl.command).toBe(0x11EA); + expect(GetGroupVideoUrl.subCommand).toBe(200); + expect(GetGroupVideoUrl.uinForm).toBe(true); + }); + + it('emits scene{requestType=2, businessType=2, sceneType=2, group}', async () => { + const deps = makeDeps({ + respHead: { retCode: 0 }, + download: { info: { domain: 'd', urlPath: '/v' }, rKeyParam: '' }, + } as any); + await GetGroupVideoUrl.invoke(deps, { groupId: 12345, node: { fileUuid: 'uuid' } }); + const env = protobuf_decode>(deps.sendRawPacket.mock.calls[0]![1]); + expect(env.body?.reqHead?.scene).toMatchObject({ + requestType: 2, businessType: 2, sceneType: 2, + group: { groupUin: 12345 }, + }); + }); + + it('bubbles up retCode != 0 via the shared ntv2 deserializer', async () => { + const deps = makeDeps({ + respHead: { retCode: 99, message: 'gone' }, + download: { info: { domain: 'd', urlPath: '/p' }, rKeyParam: '' }, + } as any); + await expect(GetGroupVideoUrl.invoke(deps, { groupId: 1, node: { fileUuid: 'u' } })) + .rejects.toThrow(/code=99/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/get-private-file-url.test.ts b/packages/protocol/tests/oidb-services/group-file/get-private-file-url.test.ts new file mode 100644 index 00000000..06f1693b --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/get-private-file-url.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbPrivateFileDownloadReq, OidbPrivateFileDownloadResp, +} from '@snowluma/proto-defs/oidb-actions/media'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetPrivateFileUrl } from '../../../src/oidb-services/group-file/get-private-file-url'; + +function makeDeps(body?: OidbPrivateFileDownloadResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('GetPrivateFileUrl namespace', () => { + it('declares 0xE37_1200', () => { + expect(GetPrivateFileUrl.command).toBe(0xE37); + expect(GetPrivateFileUrl.subCommand).toBe(1200); + }); + + it('packages the magic field99999 cookie + body fields', async () => { + const deps = makeDeps({ + body: { result: { server: 'host', port: 80, url: '/u' } } as any, + }); + await GetPrivateFileUrl.invoke(deps, { selfUid: 'self', fileId: 'fid', fileHash: 'h' }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0xe37_1200'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ + subCommand: 1200, + field2: 1, + field101: 3, + field102: 103, + field200: 1, + }); + expect(env.body?.body).toMatchObject({ + receiverUid: 'self', fileUuid: 'fid', type: 2, fileHash: 'h', + }); + expect(env.body?.field99999).toEqual(new Uint8Array([0xC0, 0x85, 0x2C, 0x01])); + }); + + it('returns the result sub-message verbatim', async () => { + const deps = makeDeps({ + body: { result: { server: 'srv', port: 8080, url: '/path' } } as any, + }); + const out = await GetPrivateFileUrl.invoke(deps, { selfUid: 's', fileId: 'f', fileHash: 'h' }); + expect(out.server).toBe('srv'); + expect(out.port).toBe(8080); + expect(out.url).toBe('/path'); + }); + + it('throws when result is missing', async () => { + const deps = makeDeps({ body: {} }); + await expect(GetPrivateFileUrl.invoke(deps, { selfUid: 's', fileId: 'f', fileHash: 'h' })) + .rejects.toThrow(/private file url response invalid/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/get-private-ptt-url.test.ts b/packages/protocol/tests/oidb-services/group-file/get-private-ptt-url.test.ts new file mode 100644 index 00000000..1ee983ce --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/get-private-ptt-url.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetPrivatePttUrl } from '../../../src/oidb-services/group-file/get-private-ptt-url'; + +function makeDeps(body?: NTV2RichMediaResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('GetPrivatePttUrl namespace', () => { + it('declares 0x126D_200 with uinForm=true', () => { + expect(GetPrivatePttUrl.command).toBe(0x126D); + expect(GetPrivatePttUrl.subCommand).toBe(200); + expect(GetPrivatePttUrl.uinForm).toBe(true); + }); + + it('emits c2c scene with self uid as targetUid', async () => { + const deps = makeDeps({ + respHead: { retCode: 0 }, + download: { info: { domain: 'd', urlPath: '/p' }, rKeyParam: '' }, + } as any); + await GetPrivatePttUrl.invoke(deps, { selfUid: 'self', node: { fileUuid: 'uuid' } }); + const env = protobuf_decode>(deps.sendRawPacket.mock.calls[0]![1]); + expect(env.body?.reqHead?.scene).toMatchObject({ + requestType: 1, businessType: 3, sceneType: 1, + c2c: { accountType: 2, targetUid: 'self' }, + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/get-private-video-url.test.ts b/packages/protocol/tests/oidb-services/group-file/get-private-video-url.test.ts new file mode 100644 index 00000000..1c3467c4 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/get-private-video-url.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { NTV2RichMediaReq, NTV2RichMediaResp } from '@snowluma/proto-defs/oidb-actions/media'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetPrivateVideoUrl } from '../../../src/oidb-services/group-file/get-private-video-url'; + +function makeDeps(body?: NTV2RichMediaResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('GetPrivateVideoUrl namespace', () => { + it('declares 0x11E9_200 with uinForm=true', () => { + expect(GetPrivateVideoUrl.command).toBe(0x11E9); + expect(GetPrivateVideoUrl.subCommand).toBe(200); + expect(GetPrivateVideoUrl.uinForm).toBe(true); + }); + + it('emits c2c scene with self uid as targetUid', async () => { + const deps = makeDeps({ + respHead: { retCode: 0 }, + download: { info: { domain: 'd', urlPath: '/v' }, rKeyParam: '' }, + } as any); + await GetPrivateVideoUrl.invoke(deps, { selfUid: 'self', node: { fileUuid: 'uuid' } }); + const env = protobuf_decode>(deps.sendRawPacket.mock.calls[0]![1]); + expect(env.body?.reqHead?.scene).toMatchObject({ + requestType: 2, businessType: 2, sceneType: 1, + c2c: { accountType: 2, targetUid: 'self' }, + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/list-group-files-page.test.ts b/packages/protocol/tests/oidb-services/group-file/list-group-files-page.test.ts new file mode 100644 index 00000000..456c698d --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/list-group-files-page.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileViewReq, OidbGroupFileViewResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { ListGroupFilesPage } from '../../../src/oidb-services/group-file/list-group-files-page'; + +function makeDeps(body?: OidbGroupFileViewResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('ListGroupFilesPage namespace', () => { + it('declares 0x6D8_1 with uinForm=true', () => { + expect(ListGroupFilesPage.command).toBe(0x6D8); + expect(ListGroupFilesPage.subCommand).toBe(1); + expect(ListGroupFilesPage.uinForm).toBe(true); + }); + + it('packages the page parameters (sortBy=1, field17=2, field18=0)', async () => { + const deps = makeDeps({ list: { isEnd: true, items: [] } as any }); + await ListGroupFilesPage.invoke(deps, { + groupId: 12345, targetDirectory: '/a', startIndex: 20, pageSize: 50, + }); + const env = protobuf_decode>(deps.sendRawPacket.mock.calls[0]![1]); + expect(env.body?.list).toMatchObject({ + groupUin: 12345, appId: 7, + targetDirectory: '/a', fileCount: 50, + sortBy: 1, startIndex: 20, + field17: 2, + }); + }); + + it('returns the list body so the facade can walk items / isEnd', async () => { + const deps = makeDeps({ + list: { isEnd: false, items: [{ type: 1 }] } as any, + }); + const out = await ListGroupFilesPage.invoke(deps, { + groupId: 1, targetDirectory: '/', startIndex: 0, pageSize: 10, + }); + expect(out?.isEnd ?? false).toBe(false); + expect(out?.items).toHaveLength(1); + }); + + it('returns null when the server elides the list slot', async () => { + const deps = makeDeps({}); + const out = await ListGroupFilesPage.invoke(deps, { + groupId: 1, targetDirectory: '/', startIndex: 0, pageSize: 10, + }); + expect(out).toBeNull(); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/move-group-file.test.ts b/packages/protocol/tests/oidb-services/group-file/move-group-file.test.ts new file mode 100644 index 00000000..6714c5c6 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/move-group-file.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileReq, OidbGroupFileResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { MoveGroupFile } from '../../../src/oidb-services/group-file/move-group-file'; + +function makeDeps(body?: OidbGroupFileResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('MoveGroupFile namespace', () => { + it('declares 0x6D6_5 with uinForm=true', () => { + expect(MoveGroupFile.command).toBe(0x6D6); + expect(MoveGroupFile.subCommand).toBe(5); + expect(MoveGroupFile.uinForm).toBe(true); + }); + + it('packages parent + target directories under the move slot', async () => { + const deps = makeDeps({ move: {} as any }); + await MoveGroupFile.invoke(deps, { + groupId: 12345, fileId: 'fid', + parentDirectory: '/a', targetDirectory: '/b', + }); + const env = protobuf_decode>(deps.sendRawPacket.mock.calls[0]![1]); + expect(env.body?.move).toMatchObject({ + groupUin: 12345, appId: 7, busId: 102, fileId: 'fid', + parentDirectory: '/a', targetDirectory: '/b', + }); + }); + + it('throws on missing move sub-message', async () => { + const deps = makeDeps({}); + await expect(MoveGroupFile.invoke(deps, { + groupId: 1, fileId: 'f', parentDirectory: '/', targetDirectory: '/', + })).rejects.toThrow(/move response missing/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/publish-group-file.test.ts b/packages/protocol/tests/oidb-services/group-file/publish-group-file.test.ts new file mode 100644 index 00000000..f58d3dde --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/publish-group-file.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupSendFileReq } from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { PublishGroupFile } from '../../../src/oidb-services/group-file/publish-group-file'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('PublishGroupFile namespace', () => { + it('declares 0x6D9_4', () => { + expect(PublishGroupFile.command).toBe(0x6D9); + expect(PublishGroupFile.subCommand).toBe(4); + }); + + it('routes to 0x6d9_4 with busiType=102, type=2, field5=true', async () => { + const deps = makeDeps(); + await PublishGroupFile.invoke(deps, { groupId: 12345, fileId: 'fid' }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x6d9_4'); + const env = protobuf_decode>(bytes); + expect(env.body?.body).toMatchObject({ + groupUin: 12345, type: 2, + info: expect.objectContaining({ busiType: 102, fileId: 'fid', field5: true }), + }); + }); + + it('emits a non-zero `info.field3` random discriminator', async () => { + // Lagrange-V2 sets this to `Random.Shared.Next()`; our serialize uses + // Math.random() — both produce a 31-bit unsigned int, never 0. + const deps = makeDeps(); + await PublishGroupFile.invoke(deps, { groupId: 1, fileId: 'f' }); + const env = protobuf_decode>(deps.sendRawPacket.mock.calls[0]![1]); + const field3 = env.body?.body?.info?.field3 ?? 0; + expect(typeof field3).toBe('number'); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/rename-group-folder.test.ts b/packages/protocol/tests/oidb-services/group-file/rename-group-folder.test.ts new file mode 100644 index 00000000..7ab28b86 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/rename-group-folder.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileFolderReq, OidbGroupFileFolderResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { RenameGroupFolder } from '../../../src/oidb-services/group-file/rename-group-folder'; + +function makeDeps(body?: OidbGroupFileFolderResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('RenameGroupFolder namespace', () => { + it('declares 0x6D7_2 with uinForm=true', () => { + expect(RenameGroupFolder.command).toBe(0x6D7); + expect(RenameGroupFolder.subCommand).toBe(2); + expect(RenameGroupFolder.uinForm).toBe(true); + }); + + it('packages rename.{groupUin, folderId, newFolderName}', async () => { + const deps = makeDeps({ rename: {} as any }); + await RenameGroupFolder.invoke(deps, { + groupId: 12345, folderId: 'fid', newFolderName: 'newname', + }); + const env = protobuf_decode>(deps.sendRawPacket.mock.calls[0]![1]); + expect(env.body?.rename).toMatchObject({ + groupUin: 12345, folderId: 'fid', newFolderName: 'newname', + }); + }); + + it('throws on missing rename sub-message', async () => { + const deps = makeDeps({}); + await expect(RenameGroupFolder.invoke(deps, { + groupId: 1, folderId: 'f', newFolderName: 'n', + })).rejects.toThrow(/folder rename response missing/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/upload-group-file-request.test.ts b/packages/protocol/tests/oidb-services/group-file/upload-group-file-request.test.ts new file mode 100644 index 00000000..bbb3b9a1 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/upload-group-file-request.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileReq, OidbGroupFileResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { UploadGroupFileRequest } from '../../../src/oidb-services/group-file/upload-group-file-request'; + +function makeDeps(body?: OidbGroupFileResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('UploadGroupFileRequest namespace', () => { + it('declares 0x6D6_0 with uinForm=true', () => { + expect(UploadGroupFileRequest.command).toBe(0x6D6); + expect(UploadGroupFileRequest.subCommand).toBe(0); + expect(UploadGroupFileRequest.uinForm).toBe(true); + }); + + it('packages the file pre-flight slot (entrance=6, appId=4, busId=102)', async () => { + const deps = makeDeps({ upload: { fileId: 'fid', boolFileExist: true } as any }); + await UploadGroupFileRequest.invoke(deps, { + groupId: 12345, + fileName: 'doc.pdf', + folderId: '/', + fileSize: 1024, + fileSha1: new Uint8Array(20), + fileMd5: new Uint8Array(16), + }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x6d6_0'); + const env = protobuf_decode>(bytes); + expect(env.reserved).toBe(1); // uinForm + expect(env.body?.file).toMatchObject({ + groupUin: 12345, appId: 4, busId: 102, entrance: 6, + targetDirectory: '/', fileName: 'doc.pdf', localDirectory: '/doc.pdf', + fileSize: 1024n, field15: true, + }); + }); + + it('returns the upload-info body for the facade orchestration', async () => { + const deps = makeDeps({ upload: { fileId: 'fid-X', boolFileExist: true } as any }); + const out = await UploadGroupFileRequest.invoke(deps, { + groupId: 1, fileName: 'f', folderId: '/', + fileSize: 0, fileSha1: new Uint8Array(0), fileMd5: new Uint8Array(0), + }); + expect(out.fileId).toBe('fid-X'); + expect(out.boolFileExist).toBe(true); + }); + + it('throws when the upload sub-message is missing', async () => { + const deps = makeDeps({}); + await expect(UploadGroupFileRequest.invoke(deps, { + groupId: 1, fileName: 'f', folderId: '/', + fileSize: 0, fileSha1: new Uint8Array(0), fileMd5: new Uint8Array(0), + })).rejects.toThrow(/upload response missing/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-file/upload-private-file-request.test.ts b/packages/protocol/tests/oidb-services/group-file/upload-private-file-request.test.ts new file mode 100644 index 00000000..9b120dd5 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/upload-private-file-request.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbPrivateFileUploadReq, OidbPrivateFileUploadResp, +} from '@snowluma/proto-defs/oidb-actions/media'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { UploadPrivateFileRequest } from '../../../src/oidb-services/group-file/upload-private-file-request'; + +function makeDeps(body?: OidbPrivateFileUploadResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('UploadPrivateFileRequest namespace', () => { + it('declares 0xE37_1700', () => { + expect(UploadPrivateFileRequest.command).toBe(0xE37); + expect(UploadPrivateFileRequest.subCommand).toBe(1700); + }); + + it('packages businessId=3, clientType=1, flagSupportMediaPlatform=1 alongside the upload body', async () => { + const deps = makeDeps({ upload: { uuid: 'fid', boolFileExist: true } as any }); + await UploadPrivateFileRequest.invoke(deps, { + senderUid: 's', receiverUid: 'r', + fileName: 'f.pdf', fileSize: 4096, + fileSha1: new Uint8Array(20), fileMd5: new Uint8Array(16), + md510MCheckSum: new Uint8Array(16), + }); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0xe37_1700'); + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ + command: 1700, businessId: 3, clientType: 1, flagSupportMediaPlatform: 1, + }); + expect(env.body?.upload).toMatchObject({ + senderUid: 's', receiverUid: 'r', + fileSize: 4096, fileName: 'f.pdf', + }); + }); + + it('returns the upload body for the facade host-selection step', async () => { + const deps = makeDeps({ + upload: { uuid: 'fid-Y', fileAddon: 'hash', boolFileExist: true } as any, + }); + const out = await UploadPrivateFileRequest.invoke(deps, { + senderUid: 's', receiverUid: 'r', + fileName: 'f', fileSize: 0, + fileSha1: new Uint8Array(0), fileMd5: new Uint8Array(0), + md510MCheckSum: new Uint8Array(0), + }); + expect(out.uuid).toBe('fid-Y'); + expect(out.fileAddon).toBe('hash'); + }); + + it('throws when the upload sub-message is missing', async () => { + const deps = makeDeps({}); + await expect(UploadPrivateFileRequest.invoke(deps, { + senderUid: 's', receiverUid: 'r', + fileName: 'f', fileSize: 0, + fileSha1: new Uint8Array(0), fileMd5: new Uint8Array(0), + md510MCheckSum: new Uint8Array(0), + })).rejects.toThrow(/upload response missing/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/interaction/send-like.test.ts b/packages/protocol/tests/oidb-services/interaction/send-like.test.ts new file mode 100644 index 00000000..6388d7cf --- /dev/null +++ b/packages/protocol/tests/oidb-services/interaction/send-like.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbLike } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SendLike } from '../../../src/oidb-services/interaction/send-like'; + +function makeDeps(uid = 'target-uid-xyz') { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + resolveUserUid: vi.fn(async () => uid), + }; +} + +describe('SendLike namespace', () => { + it('declares 0x7E5_104', () => { + expect(SendLike.command).toBe(0x7E5); + expect(SendLike.subCommand).toBe(104); + }); + + describe('serialize', () => { + it('resolves uid via ctx and emits {targetUid, sourceId=71, count}', async () => { + const deps = makeDeps('UID-AAA'); + const body = await SendLike.serialize(deps, { userId: 10001, count: 3 }); + expect(deps.resolveUserUid).toHaveBeenCalledWith(10001); + expect(body).toEqual({ targetUid: 'UID-AAA', sourceId: 71, count: 3 }); + }); + + it('throws when ctx returns an empty uid', async () => { + const deps = makeDeps(''); + await expect(SendLike.serialize(deps, { userId: 10001, count: 1 })) + .rejects.toThrow(/failed to resolve uid/); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0x7e5_104', async () => { + const deps = makeDeps(); + await SendLike.invoke(deps, { userId: 10001, count: 3 }); + expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x7e5_104'); + }); + + it('encodes targetUid (field 11) + sourceId=71 (field 12) + count (field 13)', async () => { + const deps = makeDeps('UID-BBB'); + await SendLike.invoke(deps, { userId: 10001, count: 5 }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0x7E5); + expect(env.subCommand).toBe(104); + expect(env.body).toMatchObject({ targetUid: 'UID-BBB', sourceId: 71, count: 5 }); + // Defensive: the obsolete uin-form field must not appear (server + // rejects uin-form payloads with "被点赞 QQ 号非法"). + expect((env.body as any).targetUin).toBeUndefined(); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/interaction/send-poke.test.ts b/packages/protocol/tests/oidb-services/interaction/send-poke.test.ts new file mode 100644 index 00000000..adfd3d28 --- /dev/null +++ b/packages/protocol/tests/oidb-services/interaction/send-poke.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbPoke } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SendPoke } from '../../../src/oidb-services/interaction/send-poke'; + +function makeSender() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('SendPoke namespace', () => { + it('declares 0xED3_1', () => { + expect(SendPoke.command).toBe(0xED3); + expect(SendPoke.subCommand).toBe(1); + }); + + describe('serialize', () => { + it('group poke: groupUin = peer, friendUin = 0, uin = targetUin', () => { + expect(SendPoke.serialize({} as any, { isGroup: true, peerUin: 12345, targetUin: 67890 })).toEqual({ + uin: 67890, groupUin: 12345, friendUin: 0, ext: 0, + }); + }); + + it('group poke without targetUin: uin defaults to peer', () => { + expect(SendPoke.serialize({} as any, { isGroup: true, peerUin: 12345 })).toEqual({ + uin: 12345, groupUin: 12345, friendUin: 0, ext: 0, + }); + }); + + it('friend poke: friendUin = peer, groupUin = 0, uin = targetUin', () => { + expect(SendPoke.serialize({} as any, { isGroup: false, peerUin: 67890, targetUin: 11111 })).toEqual({ + uin: 11111, groupUin: 0, friendUin: 67890, ext: 0, + }); + }); + + it('friend poke without targetUin: uin defaults to peer', () => { + expect(SendPoke.serialize({} as any, { isGroup: false, peerUin: 67890 })).toEqual({ + uin: 67890, groupUin: 0, friendUin: 67890, ext: 0, + }); + }); + + it('always sets ext = 0', () => { + expect(SendPoke.serialize({} as any, { isGroup: true, peerUin: 1 }).ext).toBe(0); + expect(SendPoke.serialize({} as any, { isGroup: false, peerUin: 1 }).ext).toBe(0); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0xed3_1', async () => { + const sender = makeSender(); + await SendPoke.invoke(sender, { isGroup: true, peerUin: 1 }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xed3_1'); + }); + + it('encodes serialize() output into envelope body', async () => { + const sender = makeSender(); + await SendPoke.invoke(sender, { isGroup: true, peerUin: 12345, targetUin: 67890 }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0xED3); + expect(env.subCommand).toBe(1); + expect(env.body).toMatchObject({ uin: 67890, groupUin: 12345 }); + // proto3 default 0 for friendUin/ext is omitted on the wire. + expect(env.body?.friendUin ?? 0).toBe(0); + }); + + it('resolves to undefined', async () => { + const sender = makeSender(); + const result = await SendPoke.invoke(sender, { isGroup: false, peerUin: 1 }); + expect(result).toBeUndefined(); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/interaction/set-essence.test.ts b/packages/protocol/tests/oidb-services/interaction/set-essence.test.ts new file mode 100644 index 00000000..06b5ad99 --- /dev/null +++ b/packages/protocol/tests/oidb-services/interaction/set-essence.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbEssence } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetEssence } from '../../../src/oidb-services/interaction/set-essence'; + +function makeSender() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('SetEssence namespace', () => { + it('declares 0xEAC', () => { + expect(SetEssence.command).toBe(0xEAC); + }); + + describe('resolveSubCommand', () => { + it('returns 1 when enable=true', () => { + expect(SetEssence.resolveSubCommand({ groupId: 1, sequence: 1, random: 1, enable: true })).toBe(1); + }); + it('returns 2 when enable=false', () => { + expect(SetEssence.resolveSubCommand({ groupId: 1, sequence: 1, random: 1, enable: false })).toBe(2); + }); + }); + + describe('serialize', () => { + it('passes groupId / sequence / random through verbatim', () => { + expect(SetEssence.serialize({} as any, { groupId: 12345, sequence: 99, random: 0xCAFEBABE, enable: true })).toEqual({ + groupUin: 12345, sequence: 99, random: 0xCAFEBABE, + }); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0xeac_1 when enabling', async () => { + const sender = makeSender(); + await SetEssence.invoke(sender, { groupId: 12345, sequence: 99, random: 0, enable: true }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xeac_1'); + }); + + it('routes to OidbSvcTrpcTcp.0xeac_2 when disabling', async () => { + const sender = makeSender(); + await SetEssence.invoke(sender, { groupId: 12345, sequence: 99, random: 0, enable: false }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xeac_2'); + }); + + it('encodes envelope body with the right shape', async () => { + const sender = makeSender(); + await SetEssence.invoke(sender, { groupId: 12345, sequence: 99, random: 7, enable: true }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0xEAC); + expect(env.subCommand).toBe(1); + expect(env.body).toMatchObject({ groupUin: 12345, sequence: 99, random: 7 }); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/misc/click-inline-keyboard-button.test.ts b/packages/protocol/tests/oidb-services/misc/click-inline-keyboard-button.test.ts new file mode 100644 index 00000000..b6accd30 --- /dev/null +++ b/packages/protocol/tests/oidb-services/misc/click-inline-keyboard-button.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x112eReq, Oidb0x112eResp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { ClickInlineKeyboardButton } from '../../../src/oidb-services/misc/click-inline-keyboard-button'; + +function makeSender(resp?: Buffer) { + const r: SendPacketResult = { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: resp ?? Buffer.alloc(0), + }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('ClickInlineKeyboardButton namespace', () => { + it('declares 0x112E_1', () => { + expect(ClickInlineKeyboardButton.command).toBe(0x112E); + expect(ClickInlineKeyboardButton.subCommand).toBe(1); + }); + + describe('serialize', () => { + it('widens numeric ids to BigInt for uint_64 fields', () => { + const out = ClickInlineKeyboardButton.serialize({} as any, { + groupId: 12345, botAppid: 67890, buttonId: 'btn', callbackData: 'data', msgSeq: 100, + }); + expect(out.groupId).toBe(12345n); + expect(out.botAppid).toBe(67890n); + expect(out.msgSeq).toBe(100n); + }); + + it('always sends unknown7=0 / unknown9=1 magic values', () => { + const out = ClickInlineKeyboardButton.serialize({} as any, { + groupId: 1, botAppid: 1, buttonId: 'x', callbackData: 'y', msgSeq: 1, + }); + expect(out.unknown7).toBe(0); + expect(out.unknown9).toBe(1); + }); + + it('coerces buttonId / callbackData to strings (defensive)', () => { + const out = ClickInlineKeyboardButton.serialize({} as any, { + groupId: 1, botAppid: 1, buttonId: 123 as any, callbackData: null as any, msgSeq: 1, + }); + expect(out.buttonId).toBe('123'); + expect(out.callbackData).toBe(''); + }); + }); + + describe('deserialize', () => { + it('shapes the response with status/promptType/promptIcon = 0', () => { + expect(ClickInlineKeyboardButton.deserialize({} as any, { + result: 1, errMsg: 'ok', promptText: 'hi', + } as Oidb0x112eResp)).toEqual({ + result: 1, errMsg: 'ok', status: 0, promptText: 'hi', promptType: 0, promptIcon: 0, + }); + }); + + it('defaults result/errMsg/promptText when omitted', () => { + expect(ClickInlineKeyboardButton.deserialize({} as any, {} as Oidb0x112eResp)).toEqual({ + result: 0, errMsg: '', status: 0, promptText: '', promptType: 0, promptIcon: 0, + }); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0x112e_1', async () => { + const sender = makeSender(); + await ClickInlineKeyboardButton.invoke(sender, { + groupId: 1, botAppid: 1, buttonId: 'x', callbackData: 'y', msgSeq: 1, + }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112e_1'); + }); + + it('round-trips a real envelope', async () => { + const sender = makeSender(Buffer.from(protobuf_encode>({ + body: { result: 7, errMsg: 'denied', promptText: 'try again' } as any, + }))); + const out = await ClickInlineKeyboardButton.invoke(sender, { + groupId: 1, botAppid: 1, buttonId: 'x', callbackData: 'y', msgSeq: 1, + }); + expect(out).toMatchObject({ result: 7, errMsg: 'denied', promptText: 'try again' }); + }); + + it('encodes envelope body with all fields', async () => { + const sender = makeSender(); + await ClickInlineKeyboardButton.invoke(sender, { + groupId: 12345, botAppid: 67890, buttonId: 'b', callbackData: 'c', msgSeq: 999, + }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body).toMatchObject({ + botAppid: 67890n, msgSeq: 999n, buttonId: 'b', callbackData: 'c', + groupId: 12345n, unknown9: 1, + }); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/misc/send-group-sign.test.ts b/packages/protocol/tests/oidb-services/misc/send-group-sign.test.ts new file mode 100644 index 00000000..3084cdb9 --- /dev/null +++ b/packages/protocol/tests/oidb-services/misc/send-group-sign.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0xeb7Req } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SendGroupSign } from '../../../src/oidb-services/misc/send-group-sign'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + identity: { uin: '10001' } as any, + }; +} + +describe('SendGroupSign namespace', () => { + it('declares 0xEB7_1', () => { + expect(SendGroupSign.command).toBe(0xEB7); + expect(SendGroupSign.subCommand).toBe(1); + }); + + it('overrides wire name to preserve the historic UPPERCASE EB7 byte-equality', async () => { + const deps = makeDeps(); + await SendGroupSign.invoke(deps, { groupId: 12345 }); + expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xEB7_1'); + }); + + describe('serialize', () => { + it('packages uin / groupId as strings + hardcodes version "9.0.90"', async () => { + const deps = makeDeps(); + await SendGroupSign.invoke(deps, { groupId: 12345 }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.signInInfo).toEqual({ + uin: '10001', + groupId: '12345', + version: '9.0.90', + }); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/misc/translate-en-to-zh.test.ts b/packages/protocol/tests/oidb-services/misc/translate-en-to-zh.test.ts new file mode 100644 index 00000000..d47d35ea --- /dev/null +++ b/packages/protocol/tests/oidb-services/misc/translate-en-to-zh.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x990Req, Oidb0x990Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { TranslateEnToZh } from '../../../src/oidb-services/misc/translate-en-to-zh'; + +function makeSender(resp?: Buffer) { + const r: SendPacketResult = { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: resp ?? Buffer.alloc(0), + }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('TranslateEnToZh namespace', () => { + it('declares 0x990_2', () => { + expect(TranslateEnToZh.command).toBe(0x990); + expect(TranslateEnToZh.subCommand).toBe(2); + }); + + describe('serialize', () => { + it('hardcodes en → zh and tag10/12 = 1', () => { + const out = TranslateEnToZh.serialize({} as any, { words: ['hello'] }); + expect(out).toEqual({ + translateReq: { srcLang: 'en', dstLang: 'zh', words: ['hello'] }, + tag10: 1, + tag12: 1, + }); + }); + + it('passes the words array verbatim', () => { + const out = TranslateEnToZh.serialize({} as any, { words: ['a', 'b', 'c'] }); + expect(out.translateReq?.words).toEqual(['a', 'b', 'c']); + }); + }); + + describe('deserialize', () => { + it('returns dstWords when translateResp is present', () => { + expect(TranslateEnToZh.deserialize({} as any, { + translateResp: { dstWords: ['你好', '世界'] }, + } as Oidb0x990Resp)).toEqual(['你好', '世界']); + }); + + it('returns [] when dstWords is omitted but translateResp exists', () => { + expect(TranslateEnToZh.deserialize({} as any, { translateResp: {} } as Oidb0x990Resp)).toEqual([]); + }); + + it('throws when translateResp is missing', () => { + expect(() => TranslateEnToZh.deserialize({} as any, {} as Oidb0x990Resp)) + .toThrow('translate response empty'); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0x990_2', async () => { + const sender = makeSender(Buffer.from(protobuf_encode>({ + body: { translateResp: { dstWords: ['x'] } } as any, + }))); + await TranslateEnToZh.invoke(sender, { words: ['hello'] }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x990_2'); + }); + + it('encodes envelope body with the request payload', async () => { + const sender = makeSender(Buffer.from(protobuf_encode>({ + body: { translateResp: { dstWords: ['你好'] } } as any, + }))); + const out = await TranslateEnToZh.invoke(sender, { words: ['hello'] }); + expect(out).toEqual(['你好']); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.translateReq?.words).toEqual(['hello']); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/profile/get-like.test.ts b/packages/protocol/tests/oidb-services/profile/get-like.test.ts new file mode 100644 index 00000000..6d14c7f5 --- /dev/null +++ b/packages/protocol/tests/oidb-services/profile/get-like.test.ts @@ -0,0 +1,135 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x7edReq, Oidb0x7edResp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetLike } from '../../../src/oidb-services/profile/get-like'; + +function makeDeps(opts: { + cachedSelfUid?: string | null; + resolveUserUid?: (uin: number) => Promise; + responseBody?: Oidb0x7edResp; +} = {}) { + const responseData = opts.responseBody !== undefined + ? Buffer.from(protobuf_encode>({ body: opts.responseBody })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { + sendRawPacket: vi.fn(async () => r), + identity: { uin: '10001', selfUid: opts.cachedSelfUid ?? null } as any, + resolveUserUid: vi.fn(opts.resolveUserUid ?? (async (uin: number) => `uid-of-${uin}`)), + }; +} + +describe('GetLike namespace', () => { + it('declares 0x7ED_12', () => { + expect(GetLike.command).toBe(0x7ED); + expect(GetLike.subCommand).toBe(12); + }); + + describe('invoke (target uid resolution)', () => { + it('uses cached self uid when userId is omitted', async () => { + const deps = makeDeps({ + cachedSelfUid: 'cached-self', + responseBody: { userLikeInfos: [{ uid: 'cached-self', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + }); + await GetLike.invoke(deps, {}); + expect(deps.resolveUserUid).not.toHaveBeenCalled(); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.targetUid).toBe('cached-self'); + }); + + it('falls back to resolveUserUid for self when cache is empty', async () => { + const deps = makeDeps({ + cachedSelfUid: null, + resolveUserUid: vi.fn(async () => 'fresh-self') as any, + responseBody: { userLikeInfos: [{ uid: 'fresh-self', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + }); + await GetLike.invoke(deps, {}); + expect(deps.resolveUserUid).toHaveBeenCalledWith(10001); + }); + + it('resolves other users via resolveUserUid', async () => { + const deps = makeDeps({ + responseBody: { userLikeInfos: [{ uid: 'uid-of-99999', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + }); + await GetLike.invoke(deps, { userId: 99999 }); + expect(deps.resolveUserUid).toHaveBeenCalledWith(99999); + }); + + it('throws when self uin is invalid and cache is empty', async () => { + const deps = makeDeps({ cachedSelfUid: null }); + deps.identity.uin = 'invalid'; + await expect(GetLike.invoke(deps, {})).rejects.toThrow('self uid is unavailable'); + }); + }); + + describe('serialize', () => { + it('always sets basic=1, vote=1, favorite=1 (full breakdown query)', async () => { + const deps = makeDeps({ + responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + }); + await GetLike.invoke(deps, { userId: 1 }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.basic).toBe(1); + expect(env.body?.vote).toBe(1); + expect(env.body?.favorite).toBe(1); + }); + + it('threads start / limit through to the request', async () => { + const deps = makeDeps({ + responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + }); + await GetLike.invoke(deps, { userId: 1, start: 5, limit: 50 }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.start).toBe(5); + expect(env.body?.limit).toBe(50); + }); + + it('defaults start=0 / limit=10', async () => { + const deps = makeDeps({ + responseBody: { userLikeInfos: [{ uid: 'u', time: 0n, favoriteInfo: {}, voteInfo: {} }] }, + }); + await GetLike.invoke(deps, { userId: 1 }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.start ?? 0).toBe(0); + expect(env.body?.limit).toBe(10); + }); + }); + + describe('deserialize', () => { + it('shapes favorite + vote info with the expected key names', () => { + const out = GetLike.deserialize({} as any, { + userLikeInfos: [{ + uid: 'u', time: 1700000000n, + favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 }, + voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n }, + }], + }); + expect(out.uid).toBe('u'); + expect(out.time).toBe(1700000000); + expect(out.favoriteInfo).toEqual({ + total_count: 5, last_time: 1, today_count: 1, userInfos: [], + }); + expect(out.voteInfo).toEqual({ + total_count: 7, new_count: 2, new_nearby_count: 0, last_visit_time: 2, userInfos: [], + }); + }); + + it('throws when there are no userLikeInfos', () => { + expect(() => GetLike.deserialize({} as any, {})).toThrow('get profile like info empty'); + expect(() => GetLike.deserialize({} as any, { userLikeInfos: [] })).toThrow('get profile like info empty'); + }); + + it('defaults all count fields to 0 when omitted', () => { + const out = GetLike.deserialize({} as any, { userLikeInfos: [{ uid: 'u', time: 0n }] }); + expect(out.favoriteInfo.total_count).toBe(0); + expect(out.voteInfo.total_count).toBe(0); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/profile/get-unidirectional-friend-list.test.ts b/packages/protocol/tests/oidb-services/profile/get-unidirectional-friend-list.test.ts new file mode 100644 index 00000000..71b47a50 --- /dev/null +++ b/packages/protocol/tests/oidb-services/profile/get-unidirectional-friend-list.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0xe17Req, Oidb0xe17Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetUnidirectionalFriendList } from '../../../src/oidb-services/profile/get-unidirectional-friend-list'; + +function makeDeps(responseJson?: unknown) { + const responseData = responseJson !== undefined + ? Buffer.from(protobuf_encode>({ + body: { jsonBody: JSON.stringify(responseJson) }, + })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { + sendRawPacket: vi.fn(async () => r), + identity: { uin: '10001' } as any, + }; +} + +describe('GetUnidirectionalFriendList namespace', () => { + it('declares 0xE17_0', () => { + expect(GetUnidirectionalFriendList.command).toBe(0xE17); + expect(GetUnidirectionalFriendList.subCommand).toBe(0); + }); + + it('overrides the wire name to MQUpdateSvc.OidbSvc.0xe17_0', async () => { + const deps = makeDeps({ rpt_block_list: [] }); + await GetUnidirectionalFriendList.invoke(deps); + expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0'); + }); + + describe('serialize', () => { + it('JSON-encodes the request body with the bot uin and fixed pagination', async () => { + const deps = makeDeps({ rpt_block_list: [] }); + await GetUnidirectionalFriendList.invoke(deps); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + const parsed = JSON.parse(env.body?.jsonBody ?? '{}'); + expect(parsed).toEqual({ + uint64_uin: '10001', + uint64_top: 0, + uint32_req_num: 99, + bytes_cookies: '', + }); + }); + }); + + describe('deserialize', () => { + it('parses the embedded JSON body and returns rpt_block_list', () => { + const out = GetUnidirectionalFriendList.deserialize({} as any, { + jsonBody: JSON.stringify({ rpt_block_list: [{ uin: 10001 }, { uin: 10002 }] }), + }); + expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]); + }); + + it('returns [] when rpt_block_list is absent', () => { + const out = GetUnidirectionalFriendList.deserialize({} as any, { jsonBody: JSON.stringify({}) }); + expect(out).toEqual([]); + }); + + it('throws when jsonBody is empty / missing', () => { + expect(() => GetUnidirectionalFriendList.deserialize({} as any, {})).toThrow('get unidirectional friend list empty'); + expect(() => GetUnidirectionalFriendList.deserialize({} as any, { jsonBody: '' })).toThrow('get unidirectional friend list empty'); + }); + }); + + describe('invoke (e2e)', () => { + it('returns the parsed block list', async () => { + const deps = makeDeps({ rpt_block_list: [{ uin: 999 }] }); + const out = await GetUnidirectionalFriendList.invoke(deps); + expect(out).toEqual([{ uin: 999 }]); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/profile/set-input-status.test.ts b/packages/protocol/tests/oidb-services/profile/set-input-status.test.ts new file mode 100644 index 00000000..53b3cf85 --- /dev/null +++ b/packages/protocol/tests/oidb-services/profile/set-input-status.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0xcd4Req } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetInputStatus } from '../../../src/oidb-services/profile/set-input-status'; + +function makeDeps(uid: string | null = 'resolved-uid') { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + resolveUserUid: vi.fn(async () => uid as string), + }; +} + +describe('SetInputStatus namespace', () => { + it('declares 0xCD4_1', () => { + expect(SetInputStatus.command).toBe(0xCD4); + expect(SetInputStatus.subCommand).toBe(1); + }); + + describe('invoke', () => { + it('routes to OidbSvcTrpcTcp.0xcd4_1', async () => { + const deps = makeDeps(); + await SetInputStatus.invoke(deps, { userId: 10001, eventType: 1 }); + expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xcd4_1'); + }); + + it('resolves the target uid before encoding', async () => { + const deps = makeDeps(); + await SetInputStatus.invoke(deps, { userId: 10001, eventType: 1 }); + expect(deps.resolveUserUid).toHaveBeenCalledWith(10001); + }); + + it('packages uid + chatType=0 + eventType into reqBody', async () => { + const deps = makeDeps('alice-uid'); + await SetInputStatus.invoke(deps, { userId: 10001, eventType: 7 }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.reqBody?.uid).toBe('alice-uid'); + // chatType=0 is proto3 default — omitted on the wire, comes back as null/undefined. + expect(env.body?.reqBody?.chatType ?? 0).toBe(0); + expect(env.body?.reqBody?.eventType).toBe(7); + }); + + it('throws when the target uid cannot be resolved', async () => { + const deps = makeDeps(null); + await expect(SetInputStatus.invoke(deps, { userId: 10001, eventType: 1 })) + .rejects.toThrow('target uid not found'); + expect(deps.sendRawPacket).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/profile/set-profile.test.ts b/packages/protocol/tests/oidb-services/profile/set-profile.test.ts new file mode 100644 index 00000000..348f56c1 --- /dev/null +++ b/packages/protocol/tests/oidb-services/profile/set-profile.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbSetProfile } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetProfile } from '../../../src/oidb-services/profile/set-profile'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + identity: { uin: '10001' } as any, + }; +} + +describe('SetProfile namespace', () => { + it('declares 0x112A_2', () => { + expect(SetProfile.command).toBe(0x112A); + expect(SetProfile.subCommand).toBe(2); + }); + + describe('invoke', () => { + it('is a no-op when both nickname and personalNote are undefined', async () => { + const deps = makeDeps(); + await SetProfile.invoke(deps, {}); + expect(deps.sendRawPacket).not.toHaveBeenCalled(); + }); + + it('packages nickname into fieldId 20002', async () => { + const deps = makeDeps(); + await SetProfile.invoke(deps, { nickname: 'New Nick' }); + expect(deps.sendRawPacket).toHaveBeenCalledOnce(); + const [wireName, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wireName).toBe('OidbSvcTrpcTcp.0x112a_2'); + const env = protobuf_decode>(bytes); + expect(env.body?.stringProfiles).toEqual([{ fieldId: 20002, value: 'New Nick' }]); + }); + + it('packages personalNote into fieldId 102', async () => { + const deps = makeDeps(); + await SetProfile.invoke(deps, { personalNote: 'on vacation' }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.stringProfiles).toEqual([{ fieldId: 102, value: 'on vacation' }]); + }); + + it('packages both fields together', async () => { + const deps = makeDeps(); + await SetProfile.invoke(deps, { nickname: 'Foo', personalNote: 'Bar' }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.stringProfiles).toEqual([ + { fieldId: 20002, value: 'Foo' }, + { fieldId: 102, value: 'Bar' }, + ]); + }); + + it('passes the bot uin in the request body', async () => { + const deps = makeDeps(); + await SetProfile.invoke(deps, { nickname: 'x' }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.uin).toBe(10001n); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/profile/set-self-long-nick.test.ts b/packages/protocol/tests/oidb-services/profile/set-self-long-nick.test.ts new file mode 100644 index 00000000..5e102578 --- /dev/null +++ b/packages/protocol/tests/oidb-services/profile/set-self-long-nick.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x112aReq } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetSelfLongNick } from '../../../src/oidb-services/profile/set-self-long-nick'; + +function makeDeps() { + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; + return { + sendRawPacket: vi.fn(async () => r), + identity: { uin: '10001' } as any, + }; +} + +describe('SetSelfLongNick namespace', () => { + it('declares 0x112A_2', () => { + expect(SetSelfLongNick.command).toBe(0x112A); + expect(SetSelfLongNick.subCommand).toBe(2); + }); + + describe('invoke', () => { + it('routes to OidbSvcTrpcTcp.0x112a_2', async () => { + const deps = makeDeps(); + await SetSelfLongNick.invoke(deps, { longNick: 'hello world' }); + expect(deps.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2'); + }); + + it('wraps the long nick in profile { tag: 102, value }', async () => { + const deps = makeDeps(); + await SetSelfLongNick.invoke(deps, { longNick: 'hello world' }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.uin).toBe(10001n); + expect(env.body?.profile).toEqual({ tag: 102, value: 'hello world' }); + }); + + it('coerces non-string longNick into a string (defensive)', async () => { + const deps = makeDeps(); + // simulate a misbehaving caller passing a number + await SetSelfLongNick.invoke(deps, { longNick: 12345 as any }); + const [, bytes] = deps.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.profile?.value).toBe('12345'); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/reaction/fetch-reaction-summary.test.ts b/packages/protocol/tests/oidb-services/reaction/fetch-reaction-summary.test.ts new file mode 100644 index 00000000..bd97ba96 --- /dev/null +++ b/packages/protocol/tests/oidb-services/reaction/fetch-reaction-summary.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x9084Req, Oidb0x9084Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { FetchReactionSummary } from '../../../src/oidb-services/reaction/fetch-reaction-summary'; + +function makeSender(resp?: Buffer) { + const defaultResp: SendPacketResult = { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: resp ?? Buffer.alloc(0), + }; + return { sendRawPacket: vi.fn(async () => defaultResp) }; +} + +describe('FetchReactionSummary namespace', () => { + it('declares command = 0x9084 and subCommand = 1', () => { + expect(FetchReactionSummary.command).toBe(0x9084); + expect(FetchReactionSummary.subCommand).toBe(1); + }); + + describe('serialize', () => { + it('encodes groupId/sequence as BigInt for uint_64 fields', () => { + const out = FetchReactionSummary.serialize({} as any, { groupId: 1022489779, sequence: 1730183 }); + expect(out.groupId).toBe(1022489779n); + expect(out.sequence).toBe(1730183n); + }); + + it('passes empty / default values for the unused filter fields', () => { + const out = FetchReactionSummary.serialize({} as any, { groupId: 1, sequence: 1 }); + expect(out.emojiId).toBe(''); + expect(out.emojiType).toBe(0); + expect(out.count).toBe(0); + expect(out.field12).toBe(1); + }); + + it('emits a 0-length cookie buffer (no continuation)', () => { + const out = FetchReactionSummary.serialize({} as any, { groupId: 1, sequence: 1 }); + expect(out.cookie).toBeInstanceOf(Uint8Array); + expect(out.cookie!.length).toBe(0); + }); + }); + + describe('deserialize', () => { + it('keeps entries with count > 0 (used emojis)', () => { + const body: Oidb0x9084Resp = { + entries: [ + { lastReactionTime: 1779456439n, count: 3, emojiType: 1, emojiId: '76' }, + { lastReactionTime: 1779456962n, count: 1, emojiType: 1, emojiId: '124' }, + ], + }; + expect(FetchReactionSummary.deserialize({} as any, body)).toEqual([ + { emojiId: '76', emojiType: 1, count: 3, lastReactionTime: 1779456439 }, + { emojiId: '124', emojiType: 1, count: 1, lastReactionTime: 1779456962 }, + ]); + }); + + it('filters out catalog-tail entries (count omitted ≡ 0)', () => { + const body: Oidb0x9084Resp = { + entries: [ + { lastReactionTime: 1n, count: 1, emojiType: 1, emojiId: '76' }, + { emojiType: 1, emojiId: '124' }, // catalog entry + { emojiType: 1, emojiId: '66' }, // catalog entry + ], + }; + const out = FetchReactionSummary.deserialize({} as any, body); + expect(out).toHaveLength(1); + expect(out[0]!.emojiId).toBe('76'); + }); + + it('returns an empty array when the response has no entries', () => { + expect(FetchReactionSummary.deserialize({} as any, {})).toEqual([]); + }); + + it('defaults emojiId / emojiType to safe values when omitted', () => { + const body: Oidb0x9084Resp = { + entries: [{ count: 5, lastReactionTime: 1700000000n }], + }; + const [entry] = FetchReactionSummary.deserialize({} as any, body); + expect(entry).toEqual({ + emojiId: '', emojiType: 1, count: 5, lastReactionTime: 1700000000, + }); + }); + + it('reports lastReactionTime=0 when omitted on a used entry (degenerate but defensive)', () => { + const body: Oidb0x9084Resp = { entries: [{ count: 2, emojiId: 'x', emojiType: 1 }] }; + expect(FetchReactionSummary.deserialize({} as any, body)[0]!.lastReactionTime).toBe(0); + }); + }); + + describe('invoke (e2e via mock sender)', () => { + it('sends to OidbSvcTrpcTcp.0x9084_1', async () => { + const sender = makeSender(); + await FetchReactionSummary.invoke(sender, { groupId: 1, sequence: 1 }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9084_1'); + }); + + it('end-to-end: encode → decode pipeline yields the parsed summary entries', async () => { + const respEnvelope = Buffer.from(protobuf_encode>({ + command: 0x9084, subCommand: 1, + body: { + entries: [ + { lastReactionTime: 1700000000n, count: 5, emojiType: 1, emojiId: '76' }, + { emojiType: 1, emojiId: '124' }, // catalog noise + ], + }, + })); + const sender = makeSender(respEnvelope); + const result = await FetchReactionSummary.invoke(sender, { groupId: 1, sequence: 1 }); + expect(result).toEqual([ + { emojiId: '76', emojiType: 1, count: 5, lastReactionTime: 1700000000 }, + ]); + }); + + it('encodes the request envelope with groupId/sequence as uint_64', async () => { + const sender = makeSender(); + await FetchReactionSummary.invoke(sender, { groupId: 1022489779, sequence: 1730183 }); + const [, reqBytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(reqBytes); + expect(env.command).toBe(0x9084); + expect(env.subCommand).toBe(1); + expect(env.body?.groupId).toBe(1022489779n); + expect(env.body?.sequence).toBe(1730183n); + }); + + it('returns an empty array when server responds with empty envelope', async () => { + const sender = makeSender(); + const result = await FetchReactionSummary.invoke(sender, { groupId: 1, sequence: 1 }); + expect(result).toEqual([]); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/reaction/get-emoji-likes.test.ts b/packages/protocol/tests/oidb-services/reaction/get-emoji-likes.test.ts new file mode 100644 index 00000000..5e1224e5 --- /dev/null +++ b/packages/protocol/tests/oidb-services/reaction/get-emoji-likes.test.ts @@ -0,0 +1,158 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0x9083Req, Oidb0x9083Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetEmojiLikes } from '../../../src/oidb-services/reaction/get-emoji-likes'; + +function makeSender(resp?: Buffer) { + const defaultResp: SendPacketResult = { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: resp ?? Buffer.alloc(0), + }; + return { sendRawPacket: vi.fn(async () => defaultResp) }; +} + +describe('GetEmojiLikes namespace', () => { + it('declares command = 0x9083 and subCommand = 1', () => { + expect(GetEmojiLikes.command).toBe(0x9083); + expect(GetEmojiLikes.subCommand).toBe(1); + }); + + describe('serialize', () => { + it('encodes groupId/sequence as BigInt for uint_64 fields', () => { + const out = GetEmojiLikes.serialize({} as any, { + groupId: 12345, sequence: 99, emojiId: '76', + }); + expect(out.groupId).toBe(12345n); + expect(out.sequence).toBe(99n); + }); + + it('passes emojiId through unchanged', () => { + const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: '128516' }); + expect(out.emojiId).toBe('128516'); + }); + + it('defaults emojiType to 1 when omitted', () => { + const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' }); + expect(out.emojiType).toBe(1); + }); + + it('uses caller-supplied emojiType when present', () => { + const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x', emojiType: 2 }); + expect(out.emojiType).toBe(2); + }); + + it('defaults count to 10 when omitted', () => { + const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' }); + expect(out.count).toBe(10); + }); + + it('uses caller-supplied count when present', () => { + const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x', count: 50 }); + expect(out.count).toBe(50); + }); + + it('decodes base64 cookie into the bytes field for continuation', () => { + const cookie = Buffer.from([0xCA, 0xFE]).toString('base64'); + const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x', cookie }); + expect(out.cookie).toBeInstanceOf(Uint8Array); + expect(Buffer.from(out.cookie!).equals(Buffer.from([0xCA, 0xFE]))).toBe(true); + }); + + it('emits a 0-length cookie buffer for the first page (no cookie supplied)', () => { + const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' }); + expect(out.cookie!.length).toBe(0); + }); + + it('sets field7=0 and field12=1 (magic values matching the historic wire shape)', () => { + const out = GetEmojiLikes.serialize({} as any, { groupId: 1, sequence: 1, emojiId: 'x' }); + expect(out.field7).toBe(0); + expect(out.field12).toBe(1); + }); + }); + + describe('deserialize', () => { + it('extracts users from inner.userInfo and base64-encodes the cookie', () => { + const result = GetEmojiLikes.deserialize({} as any, { + inner: { userInfo: [{ uin: 10001n }, { uin: 20002n }] }, + cookie: new Uint8Array([0xCA, 0xFE]), + }); + expect(result.users).toEqual([{ uin: 10001 }, { uin: 20002 }]); + expect(result.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64')); + expect(result.isLast).toBe(false); + }); + + it('filters out users with uin=0 (placeholder / zero-value)', () => { + const result = GetEmojiLikes.deserialize({} as any, { + inner: { userInfo: [{ uin: 10001n }, { uin: 0n }, { uin: 20002n }] }, + }); + expect(result.users).toEqual([{ uin: 10001 }, { uin: 20002 }]); + }); + + it('returns empty users + empty cookie + isLast=true when body has nothing', () => { + const result = GetEmojiLikes.deserialize({} as any, {}); + expect(result.users).toEqual([]); + expect(result.cookie).toBe(''); + expect(result.isLast).toBe(true); + }); + + it('returns isLast=true when cookie is absent (final page)', () => { + const result = GetEmojiLikes.deserialize({} as any, { + inner: { userInfo: [{ uin: 10001n }] }, + }); + expect(result.isLast).toBe(true); + }); + + it('handles missing userInfo entries field', () => { + const result = GetEmojiLikes.deserialize({} as any, { inner: {} }); + expect(result.users).toEqual([]); + }); + }); + + describe('invoke (e2e via mock sender)', () => { + it('sends to OidbSvcTrpcTcp.0x9083_1', async () => { + const sender = makeSender(); + await GetEmojiLikes.invoke(sender, { groupId: 1, sequence: 1, emojiId: '76' }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9083_1'); + }); + + it('end-to-end: encode → decode yields parsed user list + cookie', async () => { + const respEnvelope = Buffer.from(protobuf_encode>({ + command: 0x9083, subCommand: 1, + body: { + inner: { userInfo: [{ uin: 10001n }] }, + cookie: new Uint8Array([0xDE, 0xAD]), + } as any, + })); + const sender = makeSender(respEnvelope); + const result = await GetEmojiLikes.invoke(sender, { groupId: 1, sequence: 1, emojiId: '76' }); + expect(result.users).toEqual([{ uin: 10001 }]); + expect(result.cookie).toBe(Buffer.from([0xDE, 0xAD]).toString('base64')); + expect(result.isLast).toBe(false); + }); + + it('returns the legacy-stub empty result when server returns ack-only', async () => { + const sender = makeSender(); + const result = await GetEmojiLikes.invoke(sender, { groupId: 1, sequence: 1, emojiId: '76' }); + expect(result).toEqual({ users: [], cookie: '', isLast: true }); + }); + + it('encodes the request envelope with proper field types', async () => { + const sender = makeSender(); + await GetEmojiLikes.invoke(sender, { + groupId: 12345, sequence: 99, emojiId: '128516', emojiType: 2, count: 20, + }); + const [, reqBytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(reqBytes); + expect(env.command).toBe(0x9083); + expect(env.subCommand).toBe(1); + expect(env.body?.groupId).toBe(12345n); + expect(env.body?.sequence).toBe(99n); + expect(env.body?.emojiId).toBe('128516'); + expect(env.body?.emojiType).toBe(2); + expect(env.body?.count).toBe(20); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/reaction/set-reaction.test.ts b/packages/protocol/tests/oidb-services/reaction/set-reaction.test.ts new file mode 100644 index 00000000..c566178a --- /dev/null +++ b/packages/protocol/tests/oidb-services/reaction/set-reaction.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupReaction } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { SetReaction } from '../../../src/oidb-services/reaction/set-reaction'; + +function makeSender() { + const defaultResp: SendPacketResult = { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.alloc(0), + }; + return { sendRawPacket: vi.fn(async () => defaultResp) }; +} + +describe('SetReaction namespace', () => { + it('declares command = 0x9082', () => { + expect(SetReaction.command).toBe(0x9082); + }); + + it('resolveSubCommand: isSet=true → 1, isSet=false → 2', () => { + expect(SetReaction.resolveSubCommand({ groupId: 1, sequence: 1, code: 'x', isSet: true })).toBe(1); + expect(SetReaction.resolveSubCommand({ groupId: 1, sequence: 1, code: 'x', isSet: false })).toBe(2); + }); + + describe('serialize', () => { + it('produces type=1 for short QQ-face codes (≤3 chars)', () => { + const out = SetReaction.serialize({} as any, { groupId: 12345, sequence: 99, code: '76', isSet: true }); + expect(out).toEqual({ + groupUin: 12345, sequence: 99, code: '76', type: 1, field6: false, field7: false, + }); + }); + + it('produces type=1 for exactly 3-character codes (boundary)', () => { + const out = SetReaction.serialize({} as any, { groupId: 1, sequence: 1, code: '999', isSet: true }); + expect(out.type).toBe(1); + }); + + it('produces type=2 for codes longer than 3 chars (unicode codepoint)', () => { + const out = SetReaction.serialize({} as any, { groupId: 1, sequence: 1, code: '128516', isSet: false }); + expect(out.type).toBe(2); + }); + + it('passes through groupId/sequence/code verbatim', () => { + const out = SetReaction.serialize({} as any, { groupId: 999, sequence: 42, code: 'abc', isSet: true }); + expect(out.groupUin).toBe(999); + expect(out.sequence).toBe(42); + expect(out.code).toBe('abc'); + }); + + it('always sets field6/field7 to false (deferred behaviour)', () => { + const out = SetReaction.serialize({} as any, { groupId: 1, sequence: 1, code: 'x', isSet: true }); + expect(out.field6).toBe(false); + expect(out.field7).toBe(false); + }); + }); + + describe('deserialize', () => { + it('always returns void regardless of body content', () => { + expect(SetReaction.deserialize({} as any, {})).toBeUndefined(); + }); + }); + + describe('encode / decode round trip', () => { + it('encode preserves groupUin/sequence/code/type in the envelope body', () => { + const env: OidbBase = { + command: 0x9082, subCommand: 1, + body: { groupUin: 12345, sequence: 99, code: '76', type: 1 } as OidbGroupReaction, + }; + const bytes = SetReaction.encode(env); + const decoded = SetReaction.decode(bytes); + expect(decoded.command).toBe(0x9082); + expect(decoded.subCommand).toBe(1); + }); + }); + + describe('invoke (e2e via mock sender)', () => { + it('routes to OidbSvcTrpcTcp.0x9082_1 when isSet=true', async () => { + const sender = makeSender(); + await SetReaction.invoke(sender, { groupId: 12345, sequence: 99, code: '76', isSet: true }); + expect(sender.sendRawPacket).toHaveBeenCalledOnce(); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9082_1'); + }); + + it('routes to OidbSvcTrpcTcp.0x9082_2 when isSet=false', async () => { + const sender = makeSender(); + await SetReaction.invoke(sender, { groupId: 12345, sequence: 99, code: '76', isSet: false }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x9082_2'); + }); + + it('packages the serialized body into the OIDB envelope wire', async () => { + const sender = makeSender(); + await SetReaction.invoke(sender, { groupId: 12345, sequence: 99, code: '128516', isSet: true }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0x9082); + expect(env.subCommand).toBe(1); + expect(env.body).toMatchObject({ + groupUin: 12345, sequence: 99, code: '128516', type: 2, + }); + }); + + it('resolves to undefined (void)', async () => { + const sender = makeSender(); + const result = await SetReaction.invoke(sender, { groupId: 1, sequence: 1, code: 'x', isSet: true }); + expect(result).toBeUndefined(); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/web/force-fetch-client-key.test.ts b/packages/protocol/tests/oidb-services/web/force-fetch-client-key.test.ts new file mode 100644 index 00000000..61bc88b8 --- /dev/null +++ b/packages/protocol/tests/oidb-services/web/force-fetch-client-key.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbClientKeyResp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { ForceFetchClientKey } from '../../../src/oidb-services/web/force-fetch-client-key'; + +function makeSender(body?: OidbClientKeyResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('ForceFetchClientKey namespace', () => { + it('declares 0x102A_1', () => { + expect(ForceFetchClientKey.command).toBe(0x102A); + expect(ForceFetchClientKey.subCommand).toBe(1); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0x102a_1', async () => { + const sender = makeSender({ clientKey: 'ck', keyIndex: 19, expireTime: 1800 }); + await ForceFetchClientKey.invoke(sender); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x102a_1'); + }); + + it('returns the parsed clientKey / keyIndex / expireTime', async () => { + const sender = makeSender({ clientKey: 'KEY', keyIndex: 7, expireTime: 600 }); + const out = await ForceFetchClientKey.invoke(sender); + expect(out).toEqual({ clientKey: 'KEY', keyIndex: '7', expireTime: '600' }); + }); + + it('falls back to keyIndex="19" and expireTime="1800" when server omits them', async () => { + const sender = makeSender({ clientKey: 'KEY' }); + const out = await ForceFetchClientKey.invoke(sender); + expect(out.keyIndex).toBe('19'); + expect(out.expireTime).toBe('1800'); + }); + + it('returns empty clientKey when server omits it', async () => { + const sender = makeSender({}); + const out = await ForceFetchClientKey.invoke(sender); + expect(out.clientKey).toBe(''); + }); + }); +}); diff --git a/packages/protocol/tests/oidb-services/web/get-pskey.test.ts b/packages/protocol/tests/oidb-services/web/get-pskey.test.ts new file mode 100644 index 00000000..1410420e --- /dev/null +++ b/packages/protocol/tests/oidb-services/web/get-pskey.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbGetPskeyReq, OidbGetPskeyResp } from '@snowluma/proto-defs/oidb-actions/base'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { GetPskey } from '../../../src/oidb-services/web/get-pskey'; + +function makeSender(body?: OidbGetPskeyResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('GetPskey namespace', () => { + it('declares 0x102A_0', () => { + expect(GetPskey.command).toBe(0x102A); + expect(GetPskey.subCommand).toBe(0); + }); + + describe('serialize', () => { + it('passes the domainList through verbatim', () => { + const out = GetPskey.serialize({} as any, { domainList: ['qun.qq.com', 'qzone.qq.com'] }); + expect(out.domainList).toEqual(['qun.qq.com', 'qzone.qq.com']); + }); + }); + + describe('deserialize', () => { + it('builds a Map from server pskeyItems', () => { + const { domainPskeyMap } = GetPskey.deserialize({} as any, { + pskeyItems: [ + { domain: 'qun.qq.com', pskey: 'pskey-qun' }, + { domain: 'qzone.qq.com', pskey: 'pskey-qzone' }, + ], + }); + expect(domainPskeyMap.get('qun.qq.com')).toBe('pskey-qun'); + expect(domainPskeyMap.get('qzone.qq.com')).toBe('pskey-qzone'); + }); + + it('drops entries with missing domain or pskey', () => { + const { domainPskeyMap } = GetPskey.deserialize({} as any, { + pskeyItems: [ + { domain: 'qun.qq.com', pskey: 'ok' }, + { domain: 'missing-pskey.com' }, + { pskey: 'missing-domain' }, + ] as any, + }); + expect(domainPskeyMap.size).toBe(1); + expect(domainPskeyMap.get('qun.qq.com')).toBe('ok'); + }); + + it('returns empty Map when pskeyItems is absent', () => { + const { domainPskeyMap } = GetPskey.deserialize({} as any, {}); + expect(domainPskeyMap.size).toBe(0); + }); + }); + + describe('invoke (e2e)', () => { + it('routes to OidbSvcTrpcTcp.0x102a_0', async () => { + const sender = makeSender({ pskeyItems: [] }); + await GetPskey.invoke(sender, { domainList: ['qq.com'] }); + expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x102a_0'); + }); + + it('encodes the domain list into the request body', async () => { + const sender = makeSender({ pskeyItems: [] }); + await GetPskey.invoke(sender, { domainList: ['qun.qq.com'] }); + const [, bytes] = sender.sendRawPacket.mock.calls[0]!; + const env = protobuf_decode>(bytes); + expect(env.body?.domainList).toEqual(['qun.qq.com']); + }); + }); +}); diff --git a/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts b/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts new file mode 100644 index 00000000..2dbe6ba2 --- /dev/null +++ b/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts @@ -0,0 +1,280 @@ +// Pre-dispatch stranger resolve regression — when a group join +// request comes in, the push only carries the requester's UID. The +// pipeline must do an async UID-form FetchUserProfile lookup BEFORE +// emitting the event so the OneBot layer's `user_id` field is +// populated and the consumer bot's `get_stranger_info` lookup works. +// +// Cross-checked against Lagrange's flow: +// dev/Lagrange.Core/.../MessagingLogic.cs:215-224 +// (FetchUserInfoEvent by uid → resolved uin → posted event) + +import { describe, expect, it, vi } from 'vitest'; +import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline'; +import { BridgeEventBus } from '@snowluma/protocol/event-bus'; +import { IdentityService } from '@snowluma/protocol/identity-service'; +import type { QQEventVariant } from '@snowluma/protocol/events'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; + +function makePipeline(opts: { + resolveStrangerProfile?: vi.Mock; + resolveGroupJoinRequest?: vi.Mock; +} = {}) { + const identity = IdentityService.memory('10001'); + const events = new BridgeEventBus(); + const resolveStrangerProfile = opts.resolveStrangerProfile ?? vi.fn(async () => null); + const resolveGroupJoinRequest = opts.resolveGroupJoinRequest ?? vi.fn(async () => null); + const pipeline = new IncomingPacketPipeline({ + identity, + events, + refreshMemberCache: vi.fn(async () => false), + resolveStrangerProfile, + resolveGroupJoinRequest, + }); + + const captured: QQEventVariant[] = []; + events.onAny((event) => { captured.push(event as QQEventVariant); }); + + return { pipeline, events, captured, resolveStrangerProfile, resolveGroupJoinRequest }; +} + +describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { + it('calls resolveStrangerProfile(uid) when group_invite has fromUin=0 + fromUid', async () => { + const resolveStrangerProfile = vi.fn(async (_uid: string) => ({ + uin: 950929451, nickname: '小明', + })); + const { pipeline, captured } = makePipeline({ resolveStrangerProfile }); + + // Plant a parser that emits the user's exact bug-report shape: + // groupId set, fromUid is a string UID, fromUin=0 (decoder fix). + pipeline.registerCmd('test.cmd', () => [{ + kind: 'group_invite', + time: 1700000000, + selfUin: 10001, + groupId: 123456789, + fromUin: 0, + fromUid: 'u_stranger_abc', + subType: 'add', + message: '', + flag: 'add:123456789:u_stranger_abc', + } as QQEventVariant]); + + pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); + + // Let the async hook flush. + await new Promise(r => setTimeout(r, 10)); + + expect(resolveStrangerProfile).toHaveBeenCalledWith('u_stranger_abc'); + expect(captured).toHaveLength(1); + const event = captured[0] as Extract; + expect(event.fromUin).toBe(950929451); // ← patched in by the async resolve + expect(event.fromUid).toBe('u_stranger_abc'); + expect(event.groupId).toBe(123456789); + }); + + it('still emits the event when resolveStrangerProfile returns null (fail open)', async () => { + const resolveStrangerProfile = vi.fn(async () => null); + const { pipeline, captured } = makePipeline({ resolveStrangerProfile }); + + pipeline.registerCmd('test.cmd', () => [{ + kind: 'group_invite', + time: 1, selfUin: 10001, + groupId: 12345, fromUin: 0, fromUid: 'u_no_such_user', + subType: 'add', message: '', flag: 'add:12345:u_no_such_user', + } as QQEventVariant]); + + pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); + await new Promise(r => setTimeout(r, 10)); + + expect(resolveStrangerProfile).toHaveBeenCalledOnce(); + expect(captured).toHaveLength(1); + const event = captured[0] as Extract; + // fromUin stays 0 — but the event still goes out so the bot can + // see the join request and at least respond using the uid in the + // flag. + expect(event.fromUin).toBe(0); + expect(event.fromUid).toBe('u_no_such_user'); + }); + + it('still emits the event when resolveStrangerProfile throws', async () => { + const resolveStrangerProfile = vi.fn(async () => { throw new Error('network down'); }); + const { pipeline, captured } = makePipeline({ resolveStrangerProfile }); + + pipeline.registerCmd('test.cmd', () => [{ + kind: 'group_invite', + time: 1, selfUin: 10001, + groupId: 12345, fromUin: 0, fromUid: 'u_x', + subType: 'add', message: '', flag: 'add:12345:u_x', + } as QQEventVariant]); + + pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); + await new Promise(r => setTimeout(r, 10)); + + expect(captured).toHaveLength(1); + expect(captured[0]).toMatchObject({ fromUin: 0, fromUid: 'u_x' }); + }); + + it('skips the stranger resolve when fromUin is already populated (cache hit)', async () => { + // If the decoder's `resolveUidToUin` already found the uin in + // the local cache (e.g. group member roster), we shouldn't waste + // a wire call. + const resolveStrangerProfile = vi.fn(async () => null); + const { pipeline, captured } = makePipeline({ resolveStrangerProfile }); + + pipeline.registerCmd('test.cmd', () => [{ + kind: 'group_invite', + time: 1, selfUin: 10001, + groupId: 12345, fromUin: 99999, fromUid: 'u_known', + subType: 'invite', message: '', flag: 'invite:12345:u_known', + } as QQEventVariant]); + + pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); + await new Promise(r => setTimeout(r, 10)); + + expect(resolveStrangerProfile).not.toHaveBeenCalled(); + expect(captured).toHaveLength(1); + expect(captured[0]).toMatchObject({ fromUin: 99999, fromUid: 'u_known' }); + }); + + it('populates event.message from the pending-request queue (NapCat parity)', async () => { + // User-reported bug: SnowLuma's group_invite event surfaces a + // bare uid + uin but the requester's verify text ("你们好") never + // lands in the OneBot `comment` field. NapCat shows the text via + // `notify.postscript` from `getGroupNotifies`; we mirror that by + // doing an `OIDB 0x10C0 fetchGroupRequests` lookup in the async + // pre-dispatch hook and patching `event.message` from the matching + // row's `comment`. + const resolveStrangerProfile = vi.fn(async () => ({ + uin: 1957003260, nickname: 'KitaIkuyo', + })); + const resolveGroupJoinRequest = vi.fn(async () => ({ + comment: '你们好', sequence: 1779543612823906, + })); + const { pipeline, captured } = makePipeline({ + resolveStrangerProfile, resolveGroupJoinRequest, + }); + + pipeline.registerCmd('test.cmd', () => [{ + kind: 'group_invite', + time: 1, selfUin: 10001, + groupId: 950929451, fromUin: 0, + fromUid: 'u_UVLHYYqba27WPUzTrdZlCA', + subType: 'add', message: '', + flag: 'add:950929451:u_UVLHYYqba27WPUzTrdZlCA', + } as QQEventVariant]); + + pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); + await new Promise(r => setTimeout(r, 10)); + + expect(resolveGroupJoinRequest).toHaveBeenCalledWith( + 950929451, 'u_UVLHYYqba27WPUzTrdZlCA', 'add'); + expect(captured).toHaveLength(1); + const ev = captured[0] as Extract; + expect(ev.message).toBe('你们好'); + expect(ev.fromUin).toBe(1957003260); + }); + + it('runs the profile + request lookups in parallel (independent failures)', async () => { + // Profile lookup succeeds, request lookup fails — event should + // still carry the resolved uin but no comment. The dispatch + // doesn't block on the slower / failing path. + const resolveStrangerProfile = vi.fn(async () => ({ + uin: 12345, nickname: 'OK', + })); + const resolveGroupJoinRequest = vi.fn(async () => { + throw new Error('queue lookup failed'); + }); + const { pipeline, captured } = makePipeline({ + resolveStrangerProfile, resolveGroupJoinRequest, + }); + + pipeline.registerCmd('test.cmd', () => [{ + kind: 'group_invite', + time: 1, selfUin: 10001, + groupId: 1, fromUin: 0, fromUid: 'u_x', + subType: 'add', message: '', flag: 'add:1:u_x', + } as QQEventVariant]); + + pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); + await new Promise(r => setTimeout(r, 10)); + + const ev = captured[0] as Extract; + expect(ev.fromUin).toBe(12345); // profile succeeded + expect(ev.message).toBe(''); // request lookup threw, message left empty + }); + + it('invite subtype matches the request on invitorUid (not targetUid)', async () => { + // For `subType: 'invite'` (group member invited the bot or another + // user), the pending-request row's REQUESTER field is + // `invitorUid` not `targetUid`. The dep contract makes this + // explicit so the bridge facade can route the lookup correctly. + const resolveGroupJoinRequest = vi.fn(async () => ({ + comment: 'come join', sequence: 999, + })); + const { pipeline } = makePipeline({ resolveGroupJoinRequest }); + + pipeline.registerCmd('test.cmd', () => [{ + kind: 'group_invite', + time: 1, selfUin: 10001, + groupId: 1, fromUin: 0, fromUid: 'u_inviter', + subType: 'invite', message: '', flag: 'invite:1:u_inviter', + } as QQEventVariant]); + + pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); + await new Promise(r => setTimeout(r, 10)); + + expect(resolveGroupJoinRequest).toHaveBeenCalledWith(1, 'u_inviter', 'invite'); + }); + + it('forces re-resolve when fromUin === groupId (legacy cache pollution)', async () => { + // Pre-fix builds stored ` → ` because + // the decoder's fallback was `ctx.fromUin` (= group's own uin on + // a group-scoped push). After upgrade, the decoder's + // resolveUidToUin would re-read that polluted mapping and emit + // event.fromUin === groupId. The `fromUin <= 0` check alone + // wouldn't fire the async resolve, so the bug would persist. + // This guard catches that signature and forces a re-lookup, so + // the cache self-heals on the next event. + const resolveStrangerProfile = vi.fn(async () => ({ + uin: 1957003260, nickname: 'KitaIkuyo', + })); + const { pipeline, captured } = makePipeline({ resolveStrangerProfile }); + + pipeline.registerCmd('test.cmd', () => [{ + kind: 'group_invite', + time: 1, selfUin: 10001, + groupId: 950929451, + fromUin: 950929451, // ← POLLUTED: equals groupId + fromUid: 'u_kitaikuyo', + subType: 'add', message: '', flag: 'add:950929451:u_kitaikuyo', + } as QQEventVariant]); + + pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); + await new Promise(r => setTimeout(r, 10)); + + expect(resolveStrangerProfile).toHaveBeenCalledWith('u_kitaikuyo'); + expect(captured).toHaveLength(1); + expect(captured[0]).toMatchObject({ + fromUin: 1957003260, // ← corrected by the async resolve + fromUid: 'u_kitaikuyo', + groupId: 950929451, + }); + }); + + it('skips the stranger resolve when fromUid is empty (no uid to look up by)', async () => { + const resolveStrangerProfile = vi.fn(async () => null); + const { pipeline, captured } = makePipeline({ resolveStrangerProfile }); + + pipeline.registerCmd('test.cmd', () => [{ + kind: 'group_invite', + time: 1, selfUin: 10001, + groupId: 12345, fromUin: 0, fromUid: '', + subType: 'add', message: '', flag: 'add:12345:', + } as QQEventVariant]); + + pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); + await new Promise(r => setTimeout(r, 10)); + + expect(resolveStrangerProfile).not.toHaveBeenCalled(); + expect(captured).toHaveLength(1); + }); +}); diff --git a/packages/protocol/tsconfig.json b/packages/protocol/tsconfig.json new file mode 100644 index 00000000..4cd329d7 --- /dev/null +++ b/packages/protocol/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"], + "noEmit": true + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/packages/protocol/vitest.config.ts b/packages/protocol/vitest.config.ts new file mode 100644 index 00000000..0e601ee7 --- /dev/null +++ b/packages/protocol/vitest.config.ts @@ -0,0 +1,19 @@ +// Vitest config — drives both `pnpm bench` and `pnpm test`. +// Tests live under `tests/`, benchmarks under `bench/`. +import protobufVitePlugin from '@snowluma/proton/vite'; +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + // proton's vite plugin inlines `protobuf_encode` / `protobuf_decode` + // call sites at build time. Required for both tests and benchmarks + // to hit the production code path rather than proton's runtime + // fallback (which throws unless a runtime-map JSON is loaded). + plugins: [protobufVitePlugin()], + test: { + include: ['tests/**/*.test.ts'], + benchmark: { + include: ['bench/**/*.bench.ts'], + }, + environment: 'node', + }, +}); diff --git a/packages/proton/package.json b/packages/proton/package.json index 18e2e6db..496e2727 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/proton", - "version": "1.9.1", + "version": "1.9.2", "private": true, "type": "module", "description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.", diff --git a/packages/proton/src/runtime.ts b/packages/proton/src/runtime.ts index b3b8b185..c48cc583 100644 --- a/packages/proton/src/runtime.ts +++ b/packages/proton/src/runtime.ts @@ -1,11 +1,5 @@ -/** - * Runtime fallback functions. - * If the Vite plugin is active, calls to protobuf_encode/decode are replaced - * at compile-time with generated type-specific functions. - * If NOT transformed, these fallbacks throw to alert the developer. - */ -import type { MessageRegistry } from './ast/types.js'; import { buildDependencyRegistry } from './ast/dependency-graph.js'; +import type { MessageRegistry } from './ast/types.js'; import { generateCode } from './codegen/generator.js'; import { normalizeRuntimeMapPath, @@ -19,14 +13,14 @@ type DynamicEncode = (params: unknown) => Uint8Array; type DynamicDecode = (data: Uint8Array) => unknown; interface DynamicTypeFns { - encode?: DynamicEncode; - decode?: DynamicDecode; + encode?: DynamicEncode; + decode?: DynamicDecode; } interface StackFrame { - file: string; - line: number; - column: number; + file: string; + line: number; + column: number; } const DYNAMIC_MISS = Symbol('snowluma-proton-dynamic-miss'); @@ -64,7 +58,7 @@ export function protobuf_encode(_params: T): Uint8Array { throw new Error( 'protobuf_encode() was not transformed by the @snowluma/proton Vite plugin. ' + - 'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.', + 'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.', ); } @@ -74,7 +68,7 @@ export function protobuf_decode(_data: Uint8Array): T { throw new Error( 'protobuf_decode() was not transformed by the @snowluma/proton Vite plugin. ' + - 'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.', + 'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.', ); } @@ -111,9 +105,9 @@ function ensureTypeFunctions(typeName: string): DynamicTypeFns | null { const factory = new Function( `${generated}\nreturn {\n` + - ` encode: typeof protobuf_encode_${typeName} === 'function' ? protobuf_encode_${typeName} : undefined,\n` + - ` decode: typeof protobuf_decode_${typeName} === 'function' ? protobuf_decode_${typeName} : undefined,\n` + - `};`, + ` encode: typeof protobuf_encode_${typeName} === 'function' ? protobuf_encode_${typeName} : undefined,\n` + + ` decode: typeof protobuf_decode_${typeName} === 'function' ? protobuf_decode_${typeName} : undefined,\n` + + `};`, ) as () => DynamicTypeFns; const compiled = factory(); @@ -126,8 +120,8 @@ function resolveCallSite(fnName: RuntimeMapFnName, caller: StackFrame): RuntimeM const candidates = runtimeMapCallSites.filter(cs => cs.fnName === fnName && - cs.line === caller.line && - pathsLikelySame(callerFile, cs.file), + cs.line === caller.line && + pathsLikelySame(callerFile, cs.file), ); if (candidates.length === 0) return null; diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 185a5bda..c2fc31bf 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/runtime", - "version": "1.9.1", + "version": "1.9.2", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index d6c4ae54..d9e45c0f 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.9.1", + "version": "1.9.2", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/sdk/src/messages/chain.ts b/packages/sdk/src/messages/chain.ts index 6df4f8d6..607d4c41 100644 --- a/packages/sdk/src/messages/chain.ts +++ b/packages/sdk/src/messages/chain.ts @@ -24,7 +24,7 @@ export interface MessageChainSender { const SINGLE_USE_TYPES = new Set(['reply']); export class MessageChain implements MessageChainLike { - private readonly replyStateBrand?: THasReply; + declare private readonly replyStateBrand?: THasReply; private constructor( private readonly items: AnyMessageSegment[] = [], diff --git a/packages/sqlite/package.json b/packages/sqlite/package.json index ae72a354..f7e683c3 100644 --- a/packages/sqlite/package.json +++ b/packages/sqlite/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/sqlite", - "version": "1.9.1", + "version": "1.9.2", "private": true, "type": "module", "description": "SnowLuma SQLite wrapper. Exposes the `better-sqlite3` Database constructor + Statement type, but loads the native `.node` binding from `dist/native/sqlite/-/` at runtime instead of going through `bindings('better_sqlite3.node')` + `node_modules/.../build/Release/`. The vendored prebuilds under `packages/runtime/native/sqlite/` get copied into the dist tree by `vite-plugin-cp` during the @snowluma/core build, mirroring how `websocket-*.node` and `ffmpegAddon.*.node` are handled. The end result: production artifacts ship as a single self-contained dist/ directory with no `dist/node_modules/` and no install step at runtime.", diff --git a/packages/sqlite/src/index.ts b/packages/sqlite/src/index.ts index 7ccfd6a2..73f87eb6 100644 --- a/packages/sqlite/src/index.ts +++ b/packages/sqlite/src/index.ts @@ -1,43 +1,13 @@ -// @snowluma/sqlite — wraps better-sqlite3 so the native `.node` binding -// is loaded from -// `dist/native/better-sqlite3-v--.node` instead -// of `node_modules/better-sqlite3/build/Release/`. This lets the -// production artifact ship as a single self-contained `dist/` -// directory (no `dist/node_modules/`, no `npm install --omit=dev` -// step) — the same pattern SnowLuma already uses for its -// `websocket--.node` and `snowluma-*.{dll,node,so}` -// addons (flat dir, dash-separated triplet). -// -// How it works: -// 1. better-sqlite3's `Database` constructor accepts a `nativeBinding` -// option (string path or already-`require()`-ed object) that -// overrides the default `require('bindings')('better_sqlite3.node')` -// lookup. We forward through every other option/argument -// verbatim and inject this one. -// 2. The vendored `.node` lives at one of two locations depending -// on whether we're in dev (workspace TS source) or production -// (bundled into dist/native/): -// - Prod: `/native/better-sqlite3-v-.node` -// - Dev: `/packages/runtime/native/better-sqlite3-v-.node` -// We probe both paths and take whichever exists. -// 3. `` is `-` (e.g. -// `darwin-arm64`, `linux-x64`, `linux-arm64`, `win32-x64`). -// 4. `` is `process.versions.modules` (NODE_MODULE_VERSION). -// better-sqlite3 is NOT N-API — its binding is locked to one -// Node ABI per build. Vendoring `vNNN` in the filename lets us -// ship multiple ABIs side-by-side (e.g. v127 for Node 22 LTS -// shipped to CI, v137 for Node 24 used by some dev boxes). - -import { createRequire } from 'node:module'; -import { fileURLToPath } from 'node:url'; -import { dirname, join, resolve } from 'node:path'; -import { existsSync } from 'node:fs'; import BetterSqlite3 from 'better-sqlite3'; +import { existsSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; // Re-export the public types/classes consumers need. `Database` and // `Statement` come straight from better-sqlite3 — we only intercept // the constructor at call time, not the class shape. -export type { Database, Statement, RunResult, Options } from 'better-sqlite3'; +export type { Database, Options, RunResult, Statement } from 'better-sqlite3'; function triplet(): string { return `${process.platform}-${process.arch}`; @@ -103,16 +73,12 @@ function loadAddon(): unknown { type BetterSqlite3Type = typeof BetterSqlite3; type DatabaseInstance = InstanceType; type DatabaseOptions = ConstructorParameters[1]; +type BetterSqlite3Constructor = new (filename?: string | Buffer, options?: DatabaseOptions) => DatabaseInstance; const Database = function Database(filename?: string | Buffer, options?: DatabaseOptions): DatabaseInstance { const opts = { ...(options ?? {}), nativeBinding: loadAddon() } as DatabaseOptions; - // The `as any` shrug here is unavoidable — better-sqlite3's - // overload set declares `new Database(...)` returns the class type - // but its default export is a callable that *also* returns it via - // an internal `new.target == null` branch. TS can't reconcile the - // two without `as any`. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return new (BetterSqlite3 as any)(filename, opts); + // better-sqlite3 的默认导出同时支持函数调用和 new 调用;这里只需要构造器形态。 + return new (BetterSqlite3 as unknown as BetterSqlite3Constructor)(filename, opts); } as unknown as BetterSqlite3Type; export default Database; diff --git a/packages/ui/package.json b/packages/ui/package.json index 0120b6ff..9645e186 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.9.1", + "version": "1.9.2", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index 3e6dcd13..a4cb9513 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/websocket", - "version": "1.9.1", + "version": "1.9.2", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 29949e1a..72128247 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,7 +1,7 @@ { "name": "webui", "private": true, - "version": "1.9.1", + "version": "1.9.2", "type": "module", "scripts": { "dev": "vite", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a535946a..fb96ef9f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -23,6 +23,12 @@ importers: '@eslint/js': specifier: ^10.0.1 version: 10.0.1(eslint@10.2.0(jiti@2.6.1)) + '@vitest/coverage-istanbul': + specifier: 4.1.4 + version: 4.1.4(vitest@4.1.4) + '@vitest/coverage-v8': + specifier: ^4.1.4 + version: 4.1.4(vitest@4.1.4) cross-env: specifier: ^10.1.0 version: 10.1.0 @@ -53,15 +59,6 @@ importers: '@snowluma/common': specifier: workspace:* version: link:../common - '@snowluma/proto-defs': - specifier: workspace:* - version: link:../proto-defs - '@snowluma/proton': - specifier: workspace:* - version: link:../proton - '@snowluma/sqlite': - specifier: workspace:* - version: link:../sqlite devDependencies: '@types/node': specifier: ^24.12.2 @@ -74,7 +71,7 @@ importers: version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) vitest: specifier: ^4.1.4 - version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) packages/common: devDependencies: @@ -99,6 +96,9 @@ importers: '@snowluma/proto-defs': specifier: workspace:* version: link:../proto-defs + '@snowluma/protocol': + specifier: workspace:* + version: link:../protocol '@snowluma/proton': specifier: workspace:* version: link:../proton @@ -138,13 +138,10 @@ importers: version: 6.0.3 vitest: specifier: ^4.1.4 - version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) packages/onebot: dependencies: - '@snowluma/bridge': - specifier: workspace:* - version: link:../bridge '@snowluma/common': specifier: workspace:* version: link:../common @@ -154,6 +151,9 @@ importers: '@snowluma/proto-defs': specifier: workspace:* version: link:../proto-defs + '@snowluma/protocol': + specifier: workspace:* + version: link:../protocol '@snowluma/proton': specifier: workspace:* version: link:../proton @@ -175,7 +175,7 @@ importers: version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) vitest: specifier: ^4.1.4 - version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) packages/proto-defs: dependencies: @@ -190,6 +190,34 @@ importers: specifier: 'catalog:' version: 6.0.2 + packages/protocol: + dependencies: + '@snowluma/common': + specifier: workspace:* + version: link:../common + '@snowluma/proto-defs': + specifier: workspace:* + version: link:../proto-defs + '@snowluma/proton': + specifier: workspace:* + version: link:../proton + '@snowluma/sqlite': + specifier: workspace:* + version: link:../sqlite + devDependencies: + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 + typescript: + specifier: 'catalog:' + version: 6.0.2 + vite: + specifier: 'catalog:' + version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + vitest: + specifier: ^4.1.4 + version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + packages/proton: dependencies: typescript: @@ -207,7 +235,7 @@ importers: version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) vitest: specifier: ^4.1.4 - version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) packages/runtime: {} @@ -221,7 +249,7 @@ importers: version: 6.0.2 vitest: specifier: ^4.1.4 - version: 4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) packages/sqlite: devDependencies: @@ -474,6 +502,11 @@ packages: engines: {node: '>=6.0.0'} hasBin: true + '@babel/parser@7.29.3': + resolution: {integrity: sha512-b3ctpQwp+PROvU/cttc4OYl4MzfJUWy6FZg+PMXfzmt/+39iHVF0sDfqay8TQM3JA2EUOyKcFZt75jWriQijsA==} + engines: {node: '>=6.0.0'} + hasBin: true + '@babel/template@7.28.6': resolution: {integrity: sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==} engines: {node: '>=6.9.0'} @@ -486,6 +519,10 @@ packages: resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==} engines: {node: '>=6.9.0'} + '@bcoe/v8-coverage@1.0.2': + resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==} + engines: {node: '>=18'} + '@emnapi/core@1.9.2': resolution: {integrity: sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==} @@ -730,6 +767,10 @@ packages: resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} engines: {node: '>=18.18'} + '@istanbuljs/schema@0.1.6': + resolution: {integrity: sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==} + engines: {node: '>=8'} + '@jridgewell/gen-mapping@0.3.13': resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} @@ -1773,6 +1814,20 @@ packages: babel-plugin-react-compiler: optional: true + '@vitest/coverage-istanbul@4.1.4': + resolution: {integrity: sha512-Pyi4F8RnqU6hBGiIDhS/e8gVD4FRcUvZJ2AbFiIlmIxHlEIsKyCxGOqufCECobty/dXELcN8oIH4Gms3hVOCYA==} + peerDependencies: + vitest: 4.1.4 + + '@vitest/coverage-v8@4.1.4': + resolution: {integrity: sha512-x7FptB5oDruxNPDNY2+S8tCh0pcq7ymCe1gTHcsp733jYjrJl8V1gMUlVysuCD9Kz46Xz9t1akkv08dPcYDs1w==} + peerDependencies: + '@vitest/browser': 4.1.4 + vitest: 4.1.4 + peerDependenciesMeta: + '@vitest/browser': + optional: true + '@vitest/expect@4.1.4': resolution: {integrity: sha512-iPBpra+VDuXmBFI3FMKHSFXp3Gx5HfmSCE8X67Dn+bwephCnQCaB7qWK2ldHa+8ncN8hJU8VTMcxjPpyMkUjww==} @@ -1826,6 +1881,9 @@ packages: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} + ast-v8-to-istanbul@1.0.0: + resolution: {integrity: sha512-1fSfIwuDICFA4LKkCzRPO7F0hzFf0B7+Xqrl27ynQaa+Rh0e1Es0v6kWHPott3lU10AyAr7oKHa65OppjLn3Rg==} + balanced-match@4.0.4: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} @@ -2162,6 +2220,10 @@ packages: graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + hasown@2.0.2: resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} engines: {node: '>= 0.4'} @@ -2176,6 +2238,9 @@ packages: resolution: {integrity: sha512-RWzP96k/yv0PQfyXnWjs6zot20TqfpfsNXhOnev8d1InAxubW93L11/oNUc3tQqn2G0bSdAOBpX+2uDFHV7kdQ==} engines: {node: '>=16.9.0'} + html-escaper@2.0.2: + resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==} + ieee754@1.2.1: resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} @@ -2225,6 +2290,18 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + istanbul-lib-coverage@3.2.2: + resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==} + engines: {node: '>=8'} + + istanbul-lib-report@3.0.1: + resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==} + engines: {node: '>=10'} + + istanbul-reports@3.2.0: + resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==} + engines: {node: '>=8'} + jiti@2.6.1: resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} hasBin: true @@ -2233,6 +2310,9 @@ packages: resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} engines: {node: '>=10'} + js-tokens@10.0.0: + resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -2365,6 +2445,13 @@ packages: magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + magicast@0.5.3: + resolution: {integrity: sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw==} + + make-dir@4.0.0: + resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} + engines: {node: '>=10'} + mimic-response@3.1.0: resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==} engines: {node: '>=10'} @@ -2670,6 +2757,10 @@ packages: engines: {node: '>=16 || 14 >=14.17'} hasBin: true + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + supports-preserve-symlinks-flag@1.0.0: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} @@ -3032,6 +3123,10 @@ snapshots: dependencies: '@babel/types': 7.29.0 + '@babel/parser@7.29.3': + dependencies: + '@babel/types': 7.29.0 + '@babel/template@7.28.6': dependencies: '@babel/code-frame': 7.29.0 @@ -3055,6 +3150,8 @@ snapshots: '@babel/helper-string-parser': 7.27.1 '@babel/helper-validator-identifier': 7.28.5 + '@bcoe/v8-coverage@1.0.2': {} + '@emnapi/core@1.9.2': dependencies: '@emnapi/wasi-threads': 1.2.1 @@ -3217,6 +3314,8 @@ snapshots: '@humanwhocodes/retry@0.4.3': {} + '@istanbuljs/schema@0.1.6': {} + '@jridgewell/gen-mapping@0.3.13': dependencies: '@jridgewell/sourcemap-codec': 1.5.5 @@ -4122,6 +4221,36 @@ snapshots: '@rolldown/pluginutils': 1.0.0-rc.7 vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + '@vitest/coverage-istanbul@4.1.4(vitest@4.1.4)': + dependencies: + '@babel/core': 7.29.0 + '@istanbuljs/schema': 0.1.6 + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + istanbul-lib-coverage: 3.2.2 + istanbul-lib-report: 3.0.1 + istanbul-reports: 3.2.0 + magicast: 0.5.3 + obug: 2.1.1 + tinyrainbow: 3.1.0 + vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + transitivePeerDependencies: + - supports-color + + '@vitest/coverage-v8@4.1.4(vitest@4.1.4)': + dependencies: + '@bcoe/v8-coverage': 1.0.2 + '@vitest/utils': 4.1.4 + ast-v8-to-istanbul: 1.0.0 + istanbul-lib-coverage: 3.2.2 + istanbul-lib-report: 3.0.1 + istanbul-reports: 3.2.0 + magicast: 0.5.3 + obug: 2.1.1 + std-env: 4.1.0 + tinyrainbow: 3.1.0 + vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + '@vitest/expect@4.1.4': dependencies: '@standard-schema/spec': 1.1.0 @@ -4184,6 +4313,12 @@ snapshots: assertion-error@2.0.1: {} + ast-v8-to-istanbul@1.0.0: + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + estree-walker: 3.0.3 + js-tokens: 10.0.0 + balanced-match@4.0.4: {} base-log-factory@2.1.4: @@ -4527,6 +4662,8 @@ snapshots: graceful-fs@4.2.11: {} + has-flag@4.0.0: {} + hasown@2.0.2: dependencies: function-bind: 1.1.2 @@ -4539,6 +4676,8 @@ snapshots: hono@4.12.18: {} + html-escaper@2.0.2: {} + ieee754@1.2.1: {} ignore@5.3.2: {} @@ -4572,10 +4711,25 @@ snapshots: isexe@2.0.0: {} + istanbul-lib-coverage@3.2.2: {} + + istanbul-lib-report@3.0.1: + dependencies: + istanbul-lib-coverage: 3.2.2 + make-dir: 4.0.0 + supports-color: 7.2.0 + + istanbul-reports@3.2.0: + dependencies: + html-escaper: 2.0.2 + istanbul-lib-report: 3.0.1 + jiti@2.6.1: {} joycon@3.1.1: {} + js-tokens@10.0.0: {} + js-tokens@4.0.0: {} jsesc@3.1.0: {} @@ -4674,6 +4828,16 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 + magicast@0.5.3: + dependencies: + '@babel/parser': 7.29.3 + '@babel/types': 7.29.0 + source-map-js: 1.2.1 + + make-dir@4.0.0: + dependencies: + semver: 7.7.4 + mimic-response@3.1.0: {} minimatch@10.2.5: @@ -4991,6 +5155,10 @@ snapshots: tinyglobby: 0.2.16 ts-interface-checker: 0.1.13 + supports-color@7.2.0: + dependencies: + has-flag: 4.0.0 + supports-preserve-symlinks-flag@1.0.0: {} tailwind-merge@3.5.0: {} @@ -5181,7 +5349,7 @@ snapshots: sass: 1.99.0 tsx: 4.21.0 - vitest@4.1.4(@types/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)): + vitest@4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)): dependencies: '@vitest/expect': 4.1.4 '@vitest/mocker': 4.1.4(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) @@ -5205,6 +5373,8 @@ snapshots: why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 24.12.2 + '@vitest/coverage-istanbul': 4.1.4(vitest@4.1.4) + '@vitest/coverage-v8': 4.1.4(vitest@4.1.4) transitivePeerDependencies: - msw diff --git a/tsconfig.base.json b/tsconfig.base.json index 0f4ad410..b9036bde 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -7,6 +7,12 @@ "ES2022" ], "strict": true, + "noImplicitAny": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "noImplicitOverride": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true,