diff --git a/.github/workflows/issue-template-guard.yml b/.github/workflows/issue-template-guard.yml new file mode 100644 index 00000000..3e8c47bf --- /dev/null +++ b/.github/workflows/issue-template-guard.yml @@ -0,0 +1,65 @@ +name: Issue template guard + +# Blank / free-form issues bypass `blank_issues_enabled: false` (it only hides +# the chooser link — the CLI, API and direct URLs still create template-less +# issues). This guard enforces the policy after the fact: an issue opened by +# someone WITHOUT write access that did not go through a template (no template +# label) is commented on and closed. Properly-filed bug reports / feature +# requests (which carry `bug` / `enhancement`) and anyone with write access are +# left alone. +# +# Note: workflows for `issues` events run from the file on the DEFAULT branch, +# so this only takes effect once it lands on `main`. + +on: + issues: + types: [opened] + +permissions: + issues: write + +jobs: + guard: + runs-on: ubuntu-latest + steps: + - uses: actions/github-script@v7 + with: + script: | + const issue = context.payload.issue; + + // Write-access roles are exempt. + const privileged = ['OWNER', 'MEMBER', 'COLLABORATOR']; + if (privileged.includes(issue.author_association)) { + core.info(`author_association=${issue.author_association} — allowed`); + return; + } + + // A template was used iff it stamped its label. + const TEMPLATE_LABELS = ['bug', 'enhancement']; + const labels = (issue.labels || []).map((l) => (typeof l === 'string' ? l : l.name)); + if (labels.some((l) => TEMPLATE_LABELS.includes(l))) { + core.info('template label present — allowed'); + return; + } + + // Non-privileged + no template → guide and close. + const { owner, repo } = context.repo; + const chooser = `https://github.com/${owner}/${repo}/issues/new/choose`; + const body = [ + '感谢你的反馈。', + '', + '本仓库的 issue 需要通过模板提交:请使用 **Bug 反馈** 或 **功能请求** 模板重新创建,', + '以便我们准确、高效地处理。直接创建的空白 / 自定义 issue 会被自动关闭。', + '', + `- 重新创建:${chooser}`, + '- 日常使用、快速交流类问题,可先到 README 中的 QQ 群', + '', + '本 issue 将自动关闭,感谢理解。', + ].join('\n'); + + await github.rest.issues.createComment({ owner, repo, issue_number: issue.number, body }); + await github.rest.issues.update({ + owner, repo, issue_number: issue.number, + state: 'closed', state_reason: 'not_planned', + }); + core.info(`closed #${issue.number} (author_association=${issue.author_association}, no template label)`); diff --git a/package.json b/package.json index 18400a0b..a8de2337 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "snowluma-monorepo", - "version": "1.10.4", + "version": "1.11.0", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index 72411256..ced5c0fc 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/bridge", - "version": "1.10.4", + "version": "1.11.0", "private": true, "type": "module", "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).", diff --git a/packages/bridge/src/hook-manager.ts b/packages/bridge/src/hook-manager.ts index 1cb658f9..7c41b83a 100644 --- a/packages/bridge/src/hook-manager.ts +++ b/packages/bridge/src/hook-manager.ts @@ -6,10 +6,12 @@ import { HookSession, type HookSessionDeps } from './hook-session'; import { injectHookProcess, listHookProcesses, + resolveHookNativePath, unloadHookProcess, type HookProcessBaseInfo, } from './injector'; import { PipeWatcher } from './pipe-watcher'; +import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator'; import { QqHookClient } from './qq-hook-client'; import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe'; import type { HookProcessInfo } from './types'; @@ -81,7 +83,13 @@ export class HookManager { private readonly makeClient: HookSessionDeps['makeClient']; private readonly pipeWatcher: PipeWatcher; private readonly ownsPipeWatcher: boolean; - private readonly listProcessesNative: () => HookProcessBaseInfo[]; + /** Watcher/API process enumeration — isolated + timeout-bounded by default + * so a blocked native /proc walk can't freeze the loop (issue #158). + * Resolves to `null` (UNKNOWN) on timeout/failure. */ + private readonly enumerate: () => Promise; + /** The owned enumerator (worker lifecycle), or null when a custom lister was + * injected (tests) — nothing to tear down in that case. */ + private readonly enumerator: ProcessEnumerator | null; private readonly autoLoadOnDiscovery: boolean; private readonly onSessionsChangedRaw?: () => void; private readonly log: Logger; @@ -104,15 +112,38 @@ export class HookManager { }, }; this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid)); - this.listProcessesNative = deps.listProcesses ?? listHookProcesses; this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false; + // A custom lister (tests) is used directly — no worker, no isolation, just + // an async wrap that maps a throw to the UNKNOWN sentinel. The default path + // wraps the native enumerator in a worker with a timeout. + if (deps.listProcesses) { + const lister = deps.listProcesses; + this.enumerator = null; + this.enumerate = async () => { + try { + return await lister(); + } catch (error) { + this.log.warn('listProcesses failed: %s', errMsg(error)); + return null; + } + }; + } else { + this.enumerator = createNativeProcessEnumerator({ + addonPath: resolveHookNativePath('node'), + fallbackSync: listHookProcesses, + processName: defaultProcessName(), + log: this.log, + }); + this.enumerate = () => this.enumerator!.enumerate(); + } + if (deps.pipeWatcher) { this.pipeWatcher = deps.pipeWatcher; this.ownsPipeWatcher = false; } else { this.pipeWatcher = new PipeWatcher({ - listProcesses: this.listProcessesNative, + listProcesses: this.enumerate, listLivePipes: () => QqHookClient.listLivePipes(), intervalMs: deps.watcherIntervalMs, log: this.log, @@ -128,12 +159,13 @@ export class HookManager { async listProcesses(): Promise { await this.startPromise; - let processes: HookProcessBaseInfo[]; - try { - processes = this.listProcessesNative(); - } catch (error) { - this.log.warn('listProcesses failed: %s', errMsg(error)); - processes = []; + const processes = await this.enumerate(); + if (processes === null) { + // Enumeration timed out / failed — report the last-known sessions rather + // than an empty list (which the WebUI would render as "no QQ"). + return [...this.sessions.values()] + .map((s) => s.toInfo()) + .sort((a, b) => a.pid - b.pid); } const result: HookProcessInfo[] = []; for (const proc of processes) { @@ -181,6 +213,7 @@ export class HookManager { session.dispose(); } this.sessions.clear(); + this.enumerator?.dispose(); if (this.ownsPipeWatcher) { this.pipeWatcher.dispose(); } diff --git a/packages/bridge/src/pipe-watcher.ts b/packages/bridge/src/pipe-watcher.ts index c0d7cc82..7b615423 100644 --- a/packages/bridge/src/pipe-watcher.ts +++ b/packages/bridge/src/pipe-watcher.ts @@ -6,8 +6,11 @@ const DEFAULT_INTERVAL_MS = 1500; const MIN_INTERVAL_MS = 250; export type PipeWatcherDeps = { - /** Native: list QQ.exe processes currently running. */ - listProcesses: () => HookProcessBaseInfo[]; + /** Native: list QQ.exe processes currently running. May be async and may + * return `null` (UNKNOWN) when enumeration timed out / failed — in which + * case this tick keeps the prior process+pipe state instead of treating the + * missing data as "everything disappeared" (issue #158). */ + listProcesses: () => HookProcessBaseInfo[] | null | Promise; /** Native: PIDs that currently have a live SnowLuma named pipe. */ listLivePipes: () => Promise>; /** Polling interval in ms. Defaults to 1500, floored to 250. */ @@ -138,12 +141,22 @@ export class PipeWatcher extends EventEmitter { } this.ticking = true; try { - let processes: HookProcessBaseInfo[]; + let processes: HookProcessBaseInfo[] | null; try { - processes = this.listProcesses(); + processes = await this.listProcesses(); } catch (error) { this.log.warn('listProcesses failed: %s', errMsg(error)); - processes = []; + processes = null; + } + // UNKNOWN (timeout / failure): keep the prior process + pipe snapshot. + // Treating missing data as "everything disappeared" would fire + // process-gone for every live PID and dispose healthy sessions — the + // freeze-then-teardown footgun behind issue #158. Still emit 'tick' so + // the manager's per-tick reconnect retries keep running off last-known + // live pipes. + if (processes === null) { + this.emit('tick'); + return; } let livePipes: Set; try { diff --git a/packages/bridge/src/process-enumerator.ts b/packages/bridge/src/process-enumerator.ts new file mode 100644 index 00000000..82287745 --- /dev/null +++ b/packages/bridge/src/process-enumerator.ts @@ -0,0 +1,238 @@ +import { createLogger, type Logger } from '@snowluma/common/logger'; +import { Worker } from 'worker_threads'; +import type { HookProcessBaseInfo } from './injector'; + +/** + * Isolated, timeout-bounded wrapper around the native `getAllMainProcess()` + * enumeration. + * + * Why this exists (issue #158): the watcher polls QQ processes every ~1.5s by + * calling the synchronous native enumerator, which walks `/proc` and reads each + * candidate's `cmdline`/`maps`. Those reads go through the target's mm and + * BLOCK while a process is mid-`exec()` — exactly what happens when QQ runs a + * silent hot-update and the process table churns. A blocked synchronous native + * call freezes the whole Node event loop: OneBot stops responding, the watcher + * stops ticking, reconnect logic never runs. The process stays "alive" so the + * supervisor never restarts it — the bot just goes silent. + * + * The only way to put a real timeout on a synchronous native call is to run it + * off the main thread. We run it in a worker; the main thread races the result + * against a deadline. On timeout the main loop keeps going (it returns the + * UNKNOWN sentinel `null`, which the watcher treats as "no fresh data, keep + * prior state" — crucially NOT "all processes gone"). The blocked worker is + * abandoned (a fresh one is spawned next time); it exits on its own once the + * native call finally returns. + * + * Graceful degradation: if the native addon can't be loaded in a worker (e.g. + * it isn't context-aware) or there's no addon at all (macOS reads sockets, not + * `/proc`), we fall back to calling `fallbackSync` on the main thread — i.e. + * exactly today's behaviour, no worse. + */ +export interface ProcessEnumerator { + /** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed + * out / failed and the caller should keep its prior state. */ + enumerate(): Promise; + dispose(): void; +} + +export interface NativeEnumeratorDeps { + /** Resolved path to the hook `.node` addon, or null when there is none + * (macOS / missing) — in which case we never spawn a worker. */ + addonPath: string | null; + /** Synchronous lister used when worker isolation is unavailable. Returns + * today's value (and may itself block — that's the no-worse-than-before + * fallback). */ + fallbackSync: () => HookProcessBaseInfo[]; + /** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */ + processName: string; + /** Per-enumeration deadline. Default 4000ms — comfortably above a healthy + * enumeration (single-digit ms) but well under a human "is it dead?". */ + timeoutMs?: number; + /** Cap on abandoned (blocked) workers before we stop spawning more and just + * return UNKNOWN until they drain. Bounds thread growth across a long + * hot-update window. Default 4. */ + maxOrphans?: number; + log?: Logger; +} + +const DEFAULT_TIMEOUT_MS = 4000; +const DEFAULT_MAX_ORPHANS = 4; + +// Worker body (CommonJS — eval workers default to CJS so `require` is available; +// `process.dlopen` is a global and needs no module system). Loads the addon +// handed in via workerData, then answers each 'enumerate' with the raw pid list +// from the blocking native call. All the cheap post-processing stays on main. +const WORKER_SOURCE = ` +const { parentPort, workerData } = require('node:worker_threads'); +let addon = null; +try { + const mod = { exports: {} }; + process.dlopen(mod, workerData.addonPath); + addon = mod.exports; +} catch (e) { + parentPort.postMessage({ type: 'fatal', error: String((e && e.message) || e) }); +} +if (addon) { + parentPort.on('message', (msg) => { + if (!msg || msg.type !== 'enumerate') return; + try { + const pids = addon.getAllMainProcess(); + parentPort.postMessage({ type: 'result', id: msg.id, pids: Array.from(pids) }); + } catch (e) { + parentPort.postMessage({ type: 'error', id: msg.id, error: String((e && e.message) || e) }); + } + }); + parentPort.postMessage({ type: 'ready' }); +} +`; + +function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] { + return [...new Set(pids)] + .filter((pid) => Number.isInteger(pid) && pid > 0) + .sort((a, b) => a - b) + .map((pid) => ({ pid, name: processName, path: '' })); +} + +export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator { + const log = deps.log ?? createLogger('ProcessEnumerator'); + const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS; + + // No addon to isolate (macOS / missing) → never spawn a worker; the sync + // fallback there is a cheap socket read, not a /proc walk. + if (!deps.addonPath) { + return { + async enumerate() { + try { + return deps.fallbackSync(); + } catch (err) { + log.warn('enumerate fallback failed: %s', errMsg(err)); + return null; + } + }, + dispose() { /* nothing to tear down */ }, + }; + } + + const addonPath = deps.addonPath; + let worker: Worker | null = null; + /** Set once we learn the addon can't load in a worker — permanent fallback. */ + let isolationBroken = false; + let orphans = 0; + let seq = 0; + const pending = new Map void }>(); + let disposed = false; + + const spawnWorker = (): void => { + const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } }); + worker = w; + w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => { + if (msg.type === 'ready') return; + if (msg.type === 'fatal') { + // The addon won't load off-thread — give up on isolation for good and + // fall back to the synchronous path from here on. Resolve any in-flight + // request now (UNKNOWN) so it doesn't sit waiting for the timeout. + log.warn('process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration', msg.error ?? ''); + isolationBroken = true; + for (const { resolve } of pending.values()) resolve(null); + pending.clear(); + teardownWorker(); + return; + } + if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') { + const entry = pending.get(msg.id); + if (!entry) return; + pending.delete(msg.id); + entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null); + } + }); + w.on('error', (err) => { + log.warn('enumeration worker error: %s', errMsg(err)); + if (worker === w) teardownWorker(); + }); + }; + + const teardownWorker = (): void => { + const w = worker; + worker = null; + if (!w) return; + // terminate() can't preempt a thread blocked in the native call; it takes + // effect once the call returns. Track it as an orphan until it actually + // exits so we can bound how many we let pile up. + orphans += 1; + w.once('exit', () => { orphans = Math.max(0, orphans - 1); }); + void w.terminate().catch(() => { /* already gone */ }); + }; + + const syncFallback = (): HookProcessBaseInfo[] | null => { + try { + return deps.fallbackSync(); + } catch (err) { + log.warn('enumerate sync fallback failed: %s', errMsg(err)); + return null; + } + }; + + return { + async enumerate(): Promise { + if (disposed || isolationBroken) return syncFallback(); + + if (!worker) { + if (orphans >= maxOrphans) { + // Too many blocked workers already piling up (a sustained hang) — + // don't spawn more; report UNKNOWN and let them drain. + return null; + } + spawnWorker(); + } + const w = worker; + if (!w) return syncFallback(); + + const id = ++seq; + const resultPromise = new Promise((resolve) => { + pending.set(id, { resolve }); + }); + try { + w.postMessage({ type: 'enumerate', id }); + } catch (err) { + pending.delete(id); + log.warn('failed to post enumerate request: %s', errMsg(err)); + teardownWorker(); + return syncFallback(); + } + + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise<'timeout'>((resolve) => { + timer = setTimeout(() => resolve('timeout'), timeoutMs); + }); + const outcome = await Promise.race([resultPromise, timeout]); + if (timer) clearTimeout(timer); + + if (outcome === 'timeout') { + pending.delete(id); + log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs); + teardownWorker(); + return null; + } + if (outcome === null) { + // Native call threw inside the worker — treat as a transient failure, + // keep prior state rather than nuking every session. + return null; + } + return mapPids(outcome, deps.processName); + }, + + dispose() { + disposed = true; + for (const { resolve } of pending.values()) resolve(null); + pending.clear(); + const w = worker; + worker = null; + if (w) void w.terminate().catch(() => { /* ignore */ }); + }, + }; +} + +function errMsg(value: unknown): string { + return value instanceof Error ? value.message : String(value); +} diff --git a/packages/bridge/tests/pipe-watcher.test.ts b/packages/bridge/tests/pipe-watcher.test.ts index 1623c8f8..29abc90e 100644 --- a/packages/bridge/tests/pipe-watcher.test.ts +++ b/packages/bridge/tests/pipe-watcher.test.ts @@ -192,4 +192,40 @@ describe('PipeWatcher', () => { expect(events).toEqual([['discovered', 1234], ['up', 1234]]); watcher.stop(); }); + + it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => { + let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }]; + let live = new Set([1234]); + const watcher = new PipeWatcher({ + listProcesses: () => result, + listLivePipes: async () => new Set(live), + intervalMs: 60_000, + }); + + await watcher.start(); + expect(watcher.isProcessAlive(1234)).toBe(true); + expect(watcher.isPipeLive(1234)).toBe(true); + + const events = captureEvents(watcher); + + // Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ + // hot-update). Prior process + pipe state MUST be preserved — no teardown. + result = null; + await watcher.tickNow(); + expect(events).toEqual([]); + expect(watcher.isProcessAlive(1234)).toBe(true); + expect(watcher.isPipeLive(1234)).toBe(true); + + // Enumeration recovers with the same set → still no churn. + result = [{ pid: 1234, name: 'qq', path: '' }]; + await watcher.tickNow(); + expect(events).toEqual([]); + + // A REAL disappearance (empty list, not null) still fires the teardown. + result = []; + live = new Set(); + await watcher.tickNow(); + expect(events).toEqual([['down', 1234], ['gone', 1234]]); + watcher.stop(); + }); }); diff --git a/packages/bridge/tests/process-enumerator.test.ts b/packages/bridge/tests/process-enumerator.test.ts new file mode 100644 index 00000000..6d45d1de --- /dev/null +++ b/packages/bridge/tests/process-enumerator.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect, vi } from 'vitest'; +import { createNativeProcessEnumerator } from '../src/process-enumerator'; +import type { HookProcessBaseInfo } from '../src/injector'; + +const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' }); + +describe('createNativeProcessEnumerator', () => { + describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => { + it('returns the sync lister result', async () => { + const en = createNativeProcessEnumerator({ + addonPath: null, + fallbackSync: () => [QQ(10), QQ(20)], + processName: 'qq', + }); + expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]); + en.dispose(); + }); + + it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => { + const en = createNativeProcessEnumerator({ + addonPath: null, + fallbackSync: () => { throw new Error('boom'); }, + processName: 'qq', + }); + expect(await en.enumerate()).toBeNull(); + en.dispose(); + }); + }); + + describe('worker isolation that cannot load the addon → permanent fallback', () => { + it('falls back to the sync lister after the worker reports a fatal load error', async () => { + const fallback = vi.fn(() => [QQ(7)]); + const en = createNativeProcessEnumerator({ + // A path that exists nowhere → process.dlopen throws in the worker → + // the worker posts 'fatal' → isolation is abandoned for good. + addonPath: '/nonexistent/snowluma-test.node', + fallbackSync: fallback, + processName: 'qq', + timeoutMs: 200, + }); + + // First call spawns the worker; the fatal message drains it to UNKNOWN. + const first = await en.enumerate(); + expect(first).toBeNull(); + + // Give the 'fatal' message a moment to flip isolationBroken if it hadn't + // already, then subsequent calls take the synchronous fallback. + await new Promise((r) => setTimeout(r, 50)); + const second = await en.enumerate(); + expect(second).toEqual([QQ(7)]); + expect(fallback).toHaveBeenCalled(); + en.dispose(); + }); + }); +}); diff --git a/packages/common/package.json b/packages/common/package.json index 0ed6b2b3..374511fe 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/common", - "version": "1.10.4", + "version": "1.11.0", "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/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).", diff --git a/packages/core/package.json b/packages/core/package.json index 5edd481a..b3932d3a 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/core", - "version": "1.10.4", + "version": "1.11.0", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/core/src/bridge/apis/extras.ts b/packages/core/src/bridge/apis/extras.ts index 557a088a..56b14d47 100644 --- a/packages/core/src/bridge/apis/extras.ts +++ b/packages/core/src/bridge/apis/extras.ts @@ -5,6 +5,9 @@ import { } 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 { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon'; +import { loadBinarySource } from '@snowluma/protocol/highway/utils'; +import { createLogger } from '@snowluma/common/logger'; import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { BridgeContext } from '../bridge-context'; @@ -28,15 +31,6 @@ export interface PttTransInput { fileId?: number; } -function hexToBytes(hex: string): Uint8Array { - const s = (hex || '').trim(); - if (!s) return new Uint8Array(0); - const len = s.length >> 1; - const out = new Uint8Array(len); - for (let i = 0; i < len; i++) out[i] = parseInt(s.substr(i * 2, 2), 16); - return out; -} - // ─────────────── public types (re-exported from bridge.ts as before) ─── export type StrangerStatus = NamespaceStrangerStatus; @@ -55,6 +49,8 @@ export interface AiVoiceItem { voiceExampleUrl: string; } +const log = createLogger('Bridge.Extras'); + export class ExtrasApi { constructor(private readonly ctx: BridgeContext) { } @@ -126,10 +122,13 @@ export class ExtrasApi { * already-transcribed case). For a freshly-received voice the response is an * empty ack and the text is delivered later via the async Event 0x210 * subType-61 push — callers should treat `''` as "pending" and wait for the - * `ptt_trans_result` event (correlated by msgId). Live-verified end to end. + * `ptt_trans_result` event (correlated by msgId). */ async translatePttToText(input: PttTransInput): Promise { - const md5 = hexToBytes(input.md5Hex); + // QQ NT sends the md5 as a 32-char lowercase HEX STRING, not the raw 16 + // bytes (RE'd from wrapper.linux.node EncodeTroopPtt/EncodeC2CPtt: the md5 + // field goes through a bytes→hex helper). Sending raw bytes → errCode -1079. + const md5 = input.md5Hex.toLowerCase(); const req: PttTransReq = input.isGroup ? { type: 1, @@ -154,7 +153,32 @@ export class ExtrasApi { } const resp = protobuf_decode(result.responseData); const item = input.isGroup ? resp?.groupResult : resp?.c2cResult; - if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`); + if (item?.errCode) { + // Diagnostic (#165 备选): correlate QQ's errCode with the request fields we + // sourced from cache, to tell a server-side ASR failure apart from our own + // missing/zero field (md5/format/uuid). Behaviour unchanged — still throws. + log.warn( + 'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d', + item.errCode, input.isGroup, + input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY', + input.format, input.uuid ? 'set' : 'EMPTY', input.duration, input.size, + ); + throw new Error(`ptt translate failed: error=${item.errCode}`); + } return item?.text ?? ''; // '' = transcribing async; caller awaits the push } + + /** + * Transcode a voice record (`get_record out_format`, #165). `source` is a + * URL / local path / `base64://…` (the record's download URL in practice); + * it is loaded then transcoded to `format` via the bundled SILK-capable + * ffmpeg addon. Returns base64 + size. Throws on unsupported format or a + * failed conversion. + */ + async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> { + // Voices are tiny — cap the download well below loadBinarySource's 1 GiB + // default so a tampered/oversized source can't be pulled in. + const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024); + return convertAudioBytes(bytes, format); + } } diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/bridge/apis/forward.ts index dbd61704..6b6f1f4a 100644 --- a/packages/core/src/bridge/apis/forward.ts +++ b/packages/core/src/bridge/apis/forward.ts @@ -24,6 +24,17 @@ function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; // resolve a forward immediately after receiving the parent message. const forwardResCache = new Map(); +/** QQ's placeholder when it doesn't hand back a real sender name — treated as + * "missing" so #174's enrichment resolves the real nickname. */ +const FORWARD_NAME_PLACEHOLDER = 'QQ用户'; + +/** Bounds on the L4 (per-uin profile) fallback when enriching forward senders. + * Profile lookups are un-cached single-point OIDB calls Tencent rate-limits + * aggressively, so cap how many distinct uins one forward resolves and how + * many run at once — the rest keep the placeholder. */ +const FORWARD_PROFILE_MAX = 20; +const FORWARD_PROFILE_CONCURRENCY = 4; + // Per-layer piggyback entry. Each level of a nested forward attaches // its own msgBody under a uuid `actionCommand`, so when the receiver // fetches the outermost res_id it gets every layer in one shot @@ -518,7 +529,7 @@ export class ForwardApi { const bridge = asBridge(this.ctx); const cached = forwardResCache.get(resId); if (cached) { - return cached.map(node => ({ + const nodes = cached.map(node => ({ userUin: node.userUin, nickname: node.nickname, elements: [...node.elements], @@ -529,6 +540,10 @@ export class ForwardApi { senderCard: node.senderCard, messageType: node.messageType, })); + // Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich + // on read (a no-op once names are present) and persist so later hits skip. + if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes)); + return nodes; } const selfUid = await resolveSelfUid(bridge); @@ -588,12 +603,96 @@ export class ForwardApi { this.consumePiggybacks(nodes, piggybackByUuid); } + // Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty + // or stamped with the "QQ用户" placeholder (#174) — the long-msg member name + // isn't always populated, and the sync decode only consults the L1 cache. + await this.enrichSenders(nodes); + if (nodes.length > 0) { forwardResCache.set(resId, cloneNodes(nodes)); } return nodes; } + /** A node whose display name the server didn't give us (empty or the QQ + * placeholder) and that we can resolve (has a uin). */ + private needsName(n: ForwardNodePayload): boolean { + return !!n.userUin && (!n.nickname || n.nickname === FORWARD_NAME_PLACEHOLDER); + } + + /** Backfill sender nickname/card on forward nodes the long-msg payload left + * nameless. Resolves group senders via one member-list fetch per group (L3, + * inflight+TTL cached in ContactsApi), then any residue + private nodes via + * the user-profile lookup (L4). Best-effort: a failed lookup keeps the + * placeholder rather than failing the whole forward. Returns true if any + * node was changed (so callers can persist the enriched cache). */ + private async enrichSenders(nodes: ForwardNodePayload[]): Promise { + const pending = nodes.filter(n => this.needsName(n)); + if (pending.length === 0) return false; + let changed = false; + + // L3 — group member lists (one fetch resolves every sender from that group). + const byGroup = new Map(); + const residue: ForwardNodePayload[] = []; + for (const n of pending) { + if (n.messageType === 'group' && n.groupId) { + const arr = byGroup.get(n.groupId) ?? []; + arr.push(n); + byGroup.set(n.groupId, arr); + } else { + residue.push(n); + } + } + for (const [groupId, groupNodes] of byGroup) { + let byUin: Map; + try { + const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId); + byUin = new Map(members.map(m => [m.uin, { nickname: m.nickname, card: m.card }])); + } catch { + // Member list (one cheap, cached call) failed — keep the placeholder + // rather than fanning the whole group out to per-uin profile lookups. + // That error path is exactly what would amplify into a rate-limit ban. + continue; + } + for (const n of groupNodes) { + const m = byUin.get(n.userUin); + const name = m?.card || m?.nickname; + if (name) { + n.senderCard = m!.card || n.senderCard || ''; + n.nickname = name; + changed = true; + } else { + residue.push(n); // in-group sender that left the group → profile fallback + } + } + } + + // L4 — user profile for the residue (members who left the group, private + // nodes). fetchUserProfile is an un-cached single-point OIDB 0xFE1_2, and + // Tencent rate-limits these hard (see ContactsApi's member-list note), so: + // dedupe by uin, CAP the count (drop the rest to placeholder), and resolve + // in small concurrency-limited batches. Best-effort. + const uins = [...new Set(residue.filter(n => this.needsName(n)).map(n => n.userUin))] + .slice(0, FORWARD_PROFILE_MAX); + if (uins.length > 0) { + const byUin = new Map(); + for (let i = 0; i < uins.length; i += FORWARD_PROFILE_CONCURRENCY) { + const batch = uins.slice(i, i + FORWARD_PROFILE_CONCURRENCY); + const results = await Promise.all(batch.map(async (uin): Promise => { + try { return [uin, (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname] as const; } + catch { return [uin, ''] as const; } + })); + for (const [uin, nick] of results) byUin.set(uin, nick); + } + for (const n of residue) { + if (!this.needsName(n)) continue; + const nick = byUin.get(n.userUin); + if (nick) { n.nickname = nick; changed = true; } + } + } + return changed; + } + /** 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. */ diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts index cac85589..b134be54 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/bridge/apis/group-file.ts @@ -100,8 +100,14 @@ function normalizeUploadFileName(name: string, fallback: string): string { return safeFallback || 'file.bin'; } +// QQ's "first 10 MB" checksum uses the magic limit 0x98A000 (10002432) — +// NOT 10*1024*1024 and not 10^7. Using the wrong limit makes the server's +// first-block verification fail for files larger than 0x98A000, so the +// offline file uploads but never finalises as downloadable (#157). +const MD5_HEAD_LIMIT = 10002432; + function md5First10MB(bytes: Uint8Array): Uint8Array { - const limit = Math.min(bytes.length, 10 * 1024 * 1024); + const limit = Math.min(bytes.length, MD5_HEAD_LIMIT); return computeMd5(bytes.subarray(0, limit)); } @@ -177,7 +183,12 @@ function buildPrivateFileUploadExt( unknown2: 1, entry: { busiBuff: { - busId: 102, + // #157: NapCat/Lagrange (and the QQ client, confirmed by packet + // capture) emit a busiBuff with ONLY senderUin — no busId. A stale + // busId:102 here made the offline-file server accept the highway + // upload but never finalise it as downloadable once the file got + // big (>5 MiB): the receiver saw the file but every download failed. + // (The other half of that bug was the wrong md5-head limit above.) senderUin: BigInt(senderUin), receiverUin: 0n, groupCode: 0n, diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/bridge/apis/message.ts index bda4e388..f727090f 100644 --- a/packages/core/src/bridge/apis/message.ts +++ b/packages/core/src/bridge/apis/message.ts @@ -13,6 +13,7 @@ import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events'; import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { createLogger } from '@snowluma/common/logger'; 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` @@ -26,6 +27,8 @@ import type { Bridge, SendMessageReceipt } from '../bridge'; const SEND_MSG_CMD = 'MessageSvc.PbSendMsg'; +const log = createLogger('Bridge.Message'); + type GroupMessage = Extract; type FriendMessage = Extract; @@ -240,10 +243,11 @@ export class MessageApi { * - `dangerEvel: 0` — virus-scan severity, always 0 client-side * - `expireTime` — 7 days from now (Lagrange convention) * - * Beyond NotOnlineFile (`FileExtra.file`), the message MUST also carry - * `FileExtra.field6` — the server-issued download routing. We obtain it by - * running the 0xE37_800 finalize first; without it the recipient sees - * "文件传输失败" even though PbSendMsg returns ok (issue #157). + * `FileExtra.file` alone makes the file downloadable (verified on a live + * account). We ALSO attach `FileExtra.field6` — extra server-issued download + * routing from a best-effort 0xE37_800 finalize that mirrors NapCat and may + * help some receiver clients. The finalize is non-fatal: if it fails we send + * without field6 rather than failing the send (issue #157). */ async sendC2cFile( userUin: number, @@ -262,22 +266,31 @@ export class MessageApi { } if (!selfUid) throw new Error('self uid unavailable for c2c file send'); - // Finalize the offline file (0xE37_800) to obtain the server-issued - // download routing. The apply + Highway upload alone leave the file - // un-downloadable; `field6` below carries the credential the recipient - // needs (see finalize-offline-file.ts). Mirrors NapCat's upload→finalize - // →send sequence (issue #157). + // The file is already downloadable from the `NotOnlineFile` reference + // alone — verified on a live account: a plain c2c file send (no field6) + // downloads fine. `field6` is EXTRA server-issued download routing (from + // the 0xE37_800 finalize) that mirrors NapCat and may help some receiver + // clients. So fetch it BEST-EFFORT: if the finalize fails, send without + // field6 rather than failing the whole send. (issue #157 — the finalize + // was originally fatal, which could regress a send that would otherwise + // succeed.) const fileHash = info.fileHash ?? ''; - const meta = await FinalizeOfflineFile.invoke(this.ctx, { - senderUid: selfUid, - receiverUid: userUid, - fileUuid: info.fileId, - fileHash, - }); + let meta: Awaited> | null = null; + try { + meta = await FinalizeOfflineFile.invoke(this.ctx, { + senderUid: selfUid, + receiverUid: userUid, + fileUuid: info.fileId, + fileHash, + }); + } catch (err) { + log.warn('c2c file finalize (0xE37_800) failed, sending without field6: %s', + err instanceof Error ? err.message : String(err)); + } const nowSec = Math.floor(Date.now() / 1000); const sevenDaysSec = 7 * 24 * 60 * 60; - const fileExtraBytes = protobuf_encode({ + const fileExtra: FileExtra = { file: { fileType: 0, fileUuid: info.fileId, @@ -289,7 +302,9 @@ export class MessageApi { expireTime: nowSec + sevenDaysSec, fileHash, }, - field6: { + }; + if (meta) { + fileExtra.field6 = { field2: { field1: meta.field110, fileUuid: info.fileId, @@ -302,8 +317,9 @@ export class MessageApi { selfUid, destUid: userUid, }, - }, - }); + }; + } + const fileExtraBytes = protobuf_encode(fileExtra); const request = protobuf_encode({ routingHead: { diff --git a/packages/core/src/bridge/apis/qzone.ts b/packages/core/src/bridge/apis/qzone.ts index 44fe4138..6e9b1765 100644 --- a/packages/core/src/bridge/apis/qzone.ts +++ b/packages/core/src/bridge/apis/qzone.ts @@ -5,18 +5,20 @@ import { getQzoneMsgList, publishQzoneMsg, setQzoneLike, + uploadQzoneImageFromSource, type QzoneCommentResult, type QzoneFeedsResult, type QzoneMsgListResult, type QzonePublishResult, + type QzoneUploadImageResult, } from '@snowluma/protocol/web/qzone'; import type { BridgeContext } from '../bridge-context'; /** * Personal QQ-Zone (个人空间) web API: 说说 (feed) read/write, likes, - * comments — all over the cookie-backed qzone.qq.com CGIs, reusing the same - * `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi. Distinct from the - * group-album surface, which lives on GroupAlbumApi. + * comments, image upload — all over the cookie-backed qzone.qq.com CGIs, + * reusing the same `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi. + * Distinct from the group-album surface, which lives on GroupAlbumApi. */ export class QzoneApi { constructor(private readonly ctx: BridgeContext) { } @@ -40,10 +42,23 @@ export class QzoneApi { return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count); } - /** 发表一条纯文字说说,返回新说说的 tid。始终发到机器人自己的空间。 */ - async publish(content: string): Promise { + /** + * 从来源上传图片到 QQ 空间。 + * `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据 + */ + async uploadImageFromSource(source: string): Promise { const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content); + return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source); + } + + /** + * 发表说说,返回新说说的 tid。始终发到机器人自己的空间。 + * `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串 + * (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。 + */ + async publish(content: string, richType?: number, richval?: string): Promise { + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval); } /** 删除机器人自己空间的一条说说(按 tid)。 */ @@ -66,11 +81,19 @@ export class QzoneApi { /** * 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间); * 始终以机器人身份发表评论。返回新评论 id(尽力而为)。 + * `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL + * (从 uploadImageFromSource 的 url 字段获取)。 */ - async comment(tid: string, content: string, targetUin: number | undefined): Promise { + async comment( + tid: string, + content: string, + targetUin: number | undefined, + richType?: number, + richval?: string, + ): Promise { const selfUin = this.ctx.identity.uin; const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin; const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - return commentQzoneMsg(cookieObject, selfUin, owner, tid, content); + return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval); } } diff --git a/packages/core/src/webui/debug-tools.ts b/packages/core/src/webui/debug-tools.ts new file mode 100644 index 00000000..4e115869 --- /dev/null +++ b/packages/core/src/webui/debug-tools.ts @@ -0,0 +1,197 @@ +// debug-tools — backend for the debug console's two heavier endpoints +// (Phase 2 of the debug-console expansion): +// +// • POST /api/debug/invoke-stream — drive a Stream API action and relay every +// frame to the browser over an SSE body. Unlike the live-activity stream +// (debug-stream.ts), this MUST NOT drop frames: a file transfer that loses a +// chunk is corrupt. So backpressure is handled by *waiting* for the consumer +// to drain, never by dropping. +// • POST /api/debug/upload — stream a browser-selected file to a temp path on +// the SERVER (the bot runs on the server, not the user's machine), so the +// returned path can be fed to a send action. Streamed straight to disk with a +// byte cap — never buffered whole, so large videos don't blow up memory. +// +// The pure pieces live here (path sanitisation, the size-capped disk sink, the +// stream-invoke Response builder) so they are unit-testable away from Hono. + +import { createWriteStream } from 'fs'; +import { mkdir, readdir, rm, stat } from 'fs/promises'; +import os from 'os'; +import path from 'path'; +import { randomBytes } from 'crypto'; + +/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but + * kept distinct so the two cleanup stories don't entangle. */ +export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'snowluma-debug-upload'); + +/** Hard ceiling on a single upload. Mirrors the Stream API's upload cap. */ +export const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB + +/** Uploads older than this are swept on the next upload (best-effort). */ +const UPLOAD_TTL_MS = 24 * 60 * 60 * 1000; + +/** Reduce a client-supplied filename to a safe basename (extension preserved), + * with no path separators or traversal. The client path is NEVER trusted for + * placement — this is only used to keep the stored name human-readable. */ +export function safeUploadName(raw: string | undefined): string { + // Treat both separators as path delimiters, then take the basename so any + // `../` / absolute prefix is discarded regardless of host platform. + const base = path.basename(String(raw ?? '').replace(/\\/g, '/')); + const cleaned = base + .replace(/[^\w.\-]+/g, '_') // collapse anything exotic to underscore + .replace(/^\.+/, '') // no leading dots (no hidden / '..' names) + .slice(0, 120); + return cleaned || 'file'; +} + +/** Unguessable destination path under DEBUG_UPLOAD_DIR for a sanitised name. + * Throws if the composed path would escape the dir (defence in depth — it + * can't, given the random id + basename, but we assert anyway). */ +export function uploadDestPath(safeName: string): string { + const id = randomBytes(12).toString('hex'); + const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`); + const rel = path.relative(DEBUG_UPLOAD_DIR, dest); + if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) { + throw new Error('invalid upload path'); + } + return dest; +} + +/** Stream raw request-body bytes to a temp file under DEBUG_UPLOAD_DIR, enforcing + * a byte cap. Returns the final server path + byte size. On overflow or any + * error the partial file is removed and the call rejects. Never buffers the + * whole body. */ +export async function streamUploadToDisk( + body: ReadableStream | null, + filename: string | undefined, + opts: { maxBytes?: number } = {}, +): Promise<{ path: string; size: number }> { + if (!body) throw new Error('empty body'); + const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES; + await mkdir(DEBUG_UPLOAD_DIR, { recursive: true }); + void sweepOldUploads(); // fire-and-forget TTL cleanup + + const dest = uploadDestPath(safeUploadName(filename)); + const out = createWriteStream(dest, { mode: 0o600 }); + // A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a + // background flush — typically while we're parked at reader.read() or waiting + // on 'drain'. An unhandled 'error' event would crash the whole process, and a + // backpressured error would leave 'drain' to never fire (a forever-hung await + // + leaked fd). So turn it into a rejection and race it into every await; the + // catch below then destroys + unlinks the partial. + const errored = new Promise((_, rej) => out.once('error', rej)); + errored.catch(() => { /* swallow a late error after success (still raced below) */ }); + let size = 0; + try { + const reader = body.getReader(); + for (;;) { + const { done, value } = await Promise.race([errored, reader.read()]); + if (done) break; + if (!value || value.byteLength === 0) continue; + size += value.byteLength; + if (size > maxBytes) throw new Error('上传超出大小上限'); + // Respect the write stream's backpressure (but never hang on an error). + if (!out.write(value)) { + await Promise.race([errored, new Promise((res) => out.once('drain', res))]); + } + } + await Promise.race([errored, new Promise((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())))]); + if (size === 0) throw new Error('empty body'); + return { path: dest, size }; + } catch (err) { + // Wait for the stream to fully close BEFORE unlinking: createWriteStream + // opens the fd asynchronously, so a fast failure can reach `rm` before the + // file even exists on disk — then the late open would re-create it and leak + // the partial. 'close' guarantees the fd is settled and no more writes land. + out.destroy(); + if (!out.closed) await new Promise((res) => out.once('close', () => res())); + await rm(dest, { force: true }).catch(() => { /* best-effort */ }); + throw err; + } +} + +/** Remove upload temp files older than the TTL. Best-effort; never throws. */ +export async function sweepOldUploads(now: number = Date.now()): Promise { + let removed = 0; + try { + const names = await readdir(DEBUG_UPLOAD_DIR); + await Promise.all( + names.map(async (n) => { + const p = path.join(DEBUG_UPLOAD_DIR, n); + try { + const s = await stat(p); + if (now - s.mtimeMs > UPLOAD_TTL_MS) { + await rm(p, { force: true, recursive: true }); + removed += 1; + } + } catch { /* racing cleanup / vanished file */ } + }), + ); + } catch { /* dir absent yet */ } + return removed; +} + +/** Drives a stream-capable action and relays its frames. The driver is the + * instance's `invokeStream` (which itself handles non-stream actions by emitting + * a single frame). */ +export type StreamInvokeDriver = ( + rawRequest: string, + emit: (json: string) => Promise, + isAlive: () => boolean, +) => Promise; + +/** How long emit() will wait for a backed-up consumer to drain before it gives + * up waiting and enqueues anyway (the request abort / action idle-watchdog are + * the real stall guards). */ +const DRAIN_WAIT_MS = 20; +const DRAIN_MAX_SPINS = 3000; // 3000 * 20ms ≈ 60s + +/** Build the SSE `Response` for `/api/debug/invoke-stream`: each relayed frame + * is one `data: \n\n` event; no frame is ever dropped. A driver error + * becomes a terminal `failed` frame. Closing the request (signal abort) stops + * delivery. `delay` is injectable for tests. */ +export function buildStreamInvokeResponse( + driver: StreamInvokeDriver, + rawRequest: string, + signal: AbortSignal, + delay: (ms: number) => Promise = (ms) => new Promise((r) => setTimeout(r, ms)), +): Response { + const encoder = new TextEncoder(); + const stream = new ReadableStream({ + async start(controller) { + let closed = false; + const onAbort = () => { closed = true; }; + signal.addEventListener('abort', onAbort); + const isAlive = () => !closed && !signal.aborted; + + const emit = async (json: string): Promise => { + if (!isAlive()) throw new Error('stream transport closed'); + // Backpressure WITHOUT dropping: wait for the consumer to catch up. + let spins = 0; + while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) { + await delay(DRAIN_WAIT_MS); + spins += 1; + } + if (!isAlive()) throw new Error('stream transport closed'); + controller.enqueue(encoder.encode(`data: ${json}\n\n`)); + }; + + try { + await driver(rawRequest, emit, isAlive); + } catch (err) { + if (isAlive()) { + const msg = err instanceof Error ? err.message : 'stream error'; + try { + controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`)); + } catch { /* controller already torn down */ } + } + } finally { + signal.removeEventListener('abort', onAbort); + try { controller.close(); } catch { /* already closed */ } + } + }, + }); + return new Response(stream, { + headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }, + }); +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 78c80431..13784925 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -22,6 +22,7 @@ import { coerceSettingsPatch } from './system-settings'; import { buildBackup, planRestore, validateBackup } from './backup'; import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs'; import { createFramePusher } from './debug-stream'; +import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools'; import { bindStateStream } from './state-stream'; import type { StateBus, StateResource } from './state-bus'; import { startConnectionDiffLoop } from './connection-diff-loop'; @@ -929,6 +930,42 @@ export async function initWebUI( return c.json(result); }); + // Invoke a Stream API action (or any action) and relay every frame to the + // browser over an SSE body. The frontend reads this with fetch()+a stream + // reader (Bearer auth in the header), so — unlike /api/debug/stream — it does + // NOT need a query-token allowlist entry. Frames are never dropped. + app.post('/api/debug/invoke-stream', async (c) => { + let body: unknown; + try { body = await c.req.json(); } catch { return c.json({ status: 'failed', message: '请求格式错误' }, 400); } + const { uin, action, params } = (body ?? {}) as { uin?: unknown; action?: unknown; params?: unknown }; + if (typeof uin !== 'string' || !UIN_REGEX.test(uin)) return c.json({ status: 'failed', message: '无效的账号' }, 400); + if (typeof action !== 'string' || !action) return c.json({ status: 'failed', message: 'action 必填' }, 400); + if (params !== undefined && (typeof params !== 'object' || params === null || Array.isArray(params))) { + return c.json({ status: 'failed', message: 'params 必须是对象' }, 400); + } + const inst = oneBotManager.getInstance(uin); + if (!inst) return c.json({ status: 'failed', message: '账号不在线' }, 404); + const rawRequest = JSON.stringify({ action, params: params ?? {} }); + return buildStreamInvokeResponse( + (rq, emit, alive) => inst.invokeStream(rq, emit, alive), + rawRequest, + c.req.raw.signal, + ); + }); + + // Stream a browser-selected file to a temp path on THIS server (the bot runs + // here, not on the operator's machine), so the returned path can be fed to a + // send action's file/image/record/video param. Raw bytes in the body, + // `?filename=` for a human-readable suffix; streamed to disk with a byte cap. + app.post('/api/debug/upload', async (c) => { + try { + const result = await streamUploadToDisk(c.req.raw.body as ReadableStream | null, c.req.query('filename')); + return c.json({ status: 'ok', path: result.path, size: result.size }); + } catch (err) { + return c.json({ status: 'failed', message: err instanceof Error ? err.message : '上传失败' }, 400); + } + }); + // Live merged SSE of OneBot events + action calls across all accounts. Taps // are attached only while a client is connected (on-demand). A slow client is // dropped (not back-pressured onto the bot) with a periodic drop marker. diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index fa424d0b..1f47c895 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -151,3 +151,71 @@ describe('actions/forward', () => { expect(sendRawPacket).toHaveBeenCalledOnce(); }); }); + +describe('actions/forward — sender name enrichment (#174)', () => { + function apiWith(contacts: { fetchGroupMemberList: any; fetchUserProfile: any }) { + return new ForwardApi({ apis: { contacts } } as any); + } + + it('fills empty / "QQ用户" names via the group member list (L3), card preferred', async () => { + const fetchGroupMemberList = vi.fn(async () => [ + { uin: 10001, nickname: 'AliceNick', card: 'AliceCard' }, + { uin: 10002, nickname: 'BobNick', card: '' }, + ]); + const fetchUserProfile = vi.fn(async (uin: number) => ({ uin, nickname: 'Stranger' })); + const api = apiWith({ fetchGroupMemberList, fetchUserProfile }); + + const nodes: any[] = [ + { userUin: 10001, nickname: '', groupId: 700, messageType: 'group', elements: [] }, + { userUin: 10002, nickname: 'QQ用户', groupId: 700, messageType: 'group', elements: [] }, + { userUin: 10003, nickname: '', groupId: 700, messageType: 'group', elements: [] }, // not in list + { userUin: 10009, nickname: '', messageType: 'private', elements: [] }, // private + { userUin: 10005, nickname: 'KeepMe', groupId: 700, messageType: 'group', elements: [] }, + ]; + const changed = await (api as any).enrichSenders(nodes); + + expect(changed).toBe(true); + expect(nodes[0].nickname).toBe('AliceCard'); // card preferred over nick + expect(nodes[0].senderCard).toBe('AliceCard'); + expect(nodes[1].nickname).toBe('BobNick'); // card empty → nickname + expect(nodes[2].nickname).toBe('Stranger'); // not in member list → L4 profile + expect(nodes[3].nickname).toBe('Stranger'); // private node → L4 profile + expect(nodes[4].nickname).toBe('KeepMe'); // already named → untouched + expect(fetchGroupMemberList).toHaveBeenCalledTimes(1); // one fetch covers the whole group + }); + + it('is a no-op (no fetch) when every node already has a name', async () => { + const fetchGroupMemberList = vi.fn(); + const fetchUserProfile = vi.fn(); + const api = apiWith({ fetchGroupMemberList, fetchUserProfile }); + const nodes: any[] = [{ userUin: 1, nickname: 'has-name', groupId: 7, messageType: 'group', elements: [] }]; + expect(await (api as any).enrichSenders(nodes)).toBe(false); + expect(fetchGroupMemberList).not.toHaveBeenCalled(); + }); + + it('keeps the placeholder and never throws when resolution fails', async () => { + const api = apiWith({ + fetchGroupMemberList: vi.fn(async () => { throw new Error('net down'); }), + fetchUserProfile: vi.fn(async () => { throw new Error('net down'); }), + }); + const nodes: any[] = [{ userUin: 10001, nickname: 'QQ用户', groupId: 700, messageType: 'group', elements: [] }]; + await expect((api as any).enrichSenders(nodes)).resolves.toBe(false); + expect(nodes[0].nickname).toBe('QQ用户'); + }); + + it('does NOT fan a member-list failure out to per-uin profile lookups (rate-limit guard)', async () => { + const fetchUserProfile = vi.fn(async (uin: number) => ({ uin, nickname: 'X' })); + const api = apiWith({ + fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }), + fetchUserProfile, + }); + // 5 distinct group senders whose member list errors → must keep placeholder, + // NOT trigger 5 profile calls. + const nodes: any[] = Array.from({ length: 5 }, (_, i) => ({ + userUin: 20000 + i, nickname: '', groupId: 700, messageType: 'group', elements: [], + })); + expect(await (api as any).enrichSenders(nodes)).toBe(false); + expect(fetchUserProfile).not.toHaveBeenCalled(); + expect(nodes.every((n) => n.nickname === '')).toBe(true); + }); +}); diff --git a/packages/core/tests/actions/qzone.test.ts b/packages/core/tests/actions/qzone.test.ts index 89f55c90..a1e9ed8b 100644 --- a/packages/core/tests/actions/qzone.test.ts +++ b/packages/core/tests/actions/qzone.test.ts @@ -49,16 +49,57 @@ describe('apis/qzone', () => { expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20); }); - it('publish posts to the bot\'s own space with the given content', async () => { + it('uploadImageFromSource uploads from file:// http:// base64:// and returns richval + url', async () => { + const getCookies = vi.fn(async () => ({ p_skey: 'PSK', skey: 'SK' })); + const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); + const uploadSpy = vi.spyOn(qzoneWeb, 'uploadQzoneImageFromSource').mockResolvedValue({ + richval: ',12345,abc,abc,22,800,600,,800,600', + url: 'https://example.com/img.jpg', + albumid: '12345', + lloc: 'abc', + type: 22, + width: 600, + height: 800, + }); + const out = await new QzoneApi(bridge as never).uploadImageFromSource('file:///path/to/image.jpg'); + expect(getCookies).toHaveBeenCalledWith('qzone.qq.com'); + expect(uploadSpy).toHaveBeenCalledWith({ p_skey: 'PSK', skey: 'SK' }, '10001', 'file:///path/to/image.jpg'); + expect(out.richval).toBe(',12345,abc,abc,22,800,600,,800,600'); + expect(out.url).toBe('https://example.com/img.jpg'); + }); + + it('publish posts to the bot\'s own space with the given content (text-only)', async () => { const getCookies = vi.fn(async () => ({ p_skey: 'PSK' })); const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 }); const out = await new QzoneApi(bridge as never).publish('hello'); expect(getCookies).toHaveBeenCalledWith('qzone.qq.com'); - expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello'); + expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined); expect(out).toEqual({ tid: 'T', time: 1 }); }); + it('publish posts with richtype and richval for image post', async () => { + const getCookies = vi.fn(async () => ({ p_skey: 'PSK' })); + const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); + const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T2', time: 2 }); + const richval = ',12345,abc,abc,22,800,600,,800,600'; + const out = await new QzoneApi(bridge as never).publish('look at this', 1, richval); + expect(getCookies).toHaveBeenCalledWith('qzone.qq.com'); + expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'look at this', 1, richval); + expect(out).toEqual({ tid: 'T2', time: 2 }); + }); + + it('publish posts with multiple images (richval joined with tab)', async () => { + const getCookies = vi.fn(async () => ({ p_skey: 'PSK' })); + const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); + const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T3', time: 3 }); + const richval = ',12345,a,a,22,800,600,,800,600\t,12346,b,b,22,1024,768,,1024,768'; + const out = await new QzoneApi(bridge as never).publish('two images', 1, richval); + expect(getCookies).toHaveBeenCalledWith('qzone.qq.com'); + expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'two images', 1, richval); + expect(out).toEqual({ tid: 'T3', time: 3 }); + }); + it('delete removes a feed by tid from the bot\'s own space', async () => { const getCookies = vi.fn(async () => ({ p_skey: 'PSK' })); const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); @@ -92,7 +133,7 @@ describe('apis/qzone', () => { const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '1' }); const out = await new QzoneApi(bridge as never).comment('TIDX', 'nice', undefined); // selfUin='10001' commenter; owner defaults to self - expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice'); + expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice', undefined, undefined); expect(out).toEqual({ comment_id: '1' }); }); @@ -101,6 +142,15 @@ describe('apis/qzone', () => { const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '2' }); await new QzoneApi(bridge as never).comment('TIDX', 'nice', 20002); - expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', 'nice'); + expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', 'nice', undefined, undefined); + }); + + it('comment with images (richType=1, richval=direct URLs joined with tab)', async () => { + const getCookies = vi.fn(async () => ({ p_skey: 'PSK' })); + const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); + const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '3' }); + const richval = 'https://example.com/a.jpg\thttps://example.com/b.jpg'; + await new QzoneApi(bridge as never).comment('TIDX', 'nice pic', undefined, 1, richval); + expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice pic', 1, richval); }); }); diff --git a/packages/core/tests/bridge-private-routing.test.ts b/packages/core/tests/bridge-private-routing.test.ts index baf7a19d..f90506ca 100644 --- a/packages/core/tests/bridge-private-routing.test.ts +++ b/packages/core/tests/bridge-private-routing.test.ts @@ -136,8 +136,9 @@ describe('Bridge private media routing', () => { // expireTime is now+7d; just sanity-check it landed (non-zero, plausible) expect(fileExtra?.file?.expireTime).toBeGreaterThan(Math.floor(Date.now() / 1000)); - // issue #157: the finalize (0xE37_800) must run, and its download routing - // must ride along in field6 — without it the recipient can't download. + // issue #157: when the 0xE37_800 finalize succeeds, its download routing + // rides along in field6 (best-effort enrichment on top of the always- + // present NotOnlineFile). expect(bridge.finalizeCmd).toBe('OidbSvcTrpcTcp.0xe37_800'); expect(fileExtra?.field6?.field2).toMatchObject({ fileUuid: 'uuid-abc-123', @@ -157,4 +158,46 @@ describe('Bridge private media routing', () => { // c2c-file path. expect(request?.contentHead?.c2cCmd ?? 0).toBe(0); }); + + it('c2c file send survives a failing 0xE37_800 finalize — sends without field6 (#157 best-effort)', async () => { + const { Bridge } = await import('../src/bridge/bridge'); + const { IdentityService } = await import('@snowluma/protocol/identity-service'); + + class TestBridge extends Bridge { + capturedBody: Uint8Array | null = null; + + override async resolveUserUid(uin: number): Promise { + return uin === 10000 ? 'u_self' : `u_${uin}`; + } + + override async sendRawPacket(cmd: string, body: Uint8Array): Promise { + // Finalize fails (server error → OidbError). The send must NOT fail + // because of it. + if (cmd.includes('0xe37_800')) { + return { success: false, gotResponse: true, errorCode: 9999, errorMessage: 'finalize boom', responseData: Buffer.alloc(0) }; + } + this.capturedBody = body; + return { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: Buffer.from(protobuf_encode({ + result: 0, errMsg: '', privateSequence: 88, timestamp1: 1710000000, + })), + }; + } + } + const bridge = new TestBridge(IdentityService.memory('10000')); + + // Should resolve (not throw) despite the finalize error. + await bridge.apis.message.sendC2cFile(67890, 'u_peer_xyz', { + fileId: 'uuid-abc-123', fileName: 'doc.txt', fileSize: 1024, + fileMd5: new Uint8Array([1, 2, 3, 4]), fileHash: 'hash-xyz', + }); + + // PbSendMsg still went out, carrying the file but NO field6. + expect(bridge.capturedBody).toBeInstanceOf(Uint8Array); + const request = protobuf_decode(bridge.capturedBody as Uint8Array); + const fileExtra = protobuf_decode(request!.messageBody!.msgContent as Uint8Array); + expect(fileExtra?.file?.fileUuid).toBe('uuid-abc-123'); + expect(fileExtra?.field6 ?? undefined).toBeUndefined(); + }); }); diff --git a/packages/core/tests/highway/pipeline.test.ts b/packages/core/tests/highway/pipeline.test.ts index e2c63a1b..0023d68d 100644 --- a/packages/core/tests/highway/pipeline.test.ts +++ b/packages/core/tests/highway/pipeline.test.ts @@ -283,112 +283,10 @@ describe('pipeline — runNtv2Upload', () => { }))).rejects.toThrow(/image fast-upload not available/); }); - // ─────────── forceFullOnFastPath (video stale-resource fallback, #145) ─────────── - - // Bridge whose sendRawPacket returns a different OIDB response per call, - // so we can model "round 1 fast-paths the main file, round 2 demands the - // bytes after we disable fast-upload". - function makeSequencedBridge(responses: Buffer[]) { - let call = 0; - const sendRawPacket = vi.fn<(cmd: string, body: Uint8Array) => Promise>( - async () => { - const responseData = responses[Math.min(call, responses.length - 1)]!; - call += 1; - return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; - }, - ); - return { sendRawPacket }; - } - - it('forceFullOnFastPath: re-requests with fast-upload disabled when the flagged main file is fast-pathed', async () => { - const bridge = makeSequencedBridge([ - // Round 1: server fast-paths the main file (no uKey) but demands nothing. - encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } /* no uKey */ } }), - // Round 2 (fast-upload disabled): server now hands back a uKey. - encodeOidbResponse({ - upload: { - uKey: 'fresh-ukey', - ipv4s: [{ ipv4: '1.2.3.4', port: 80 }], - msgInfo: { msgInfoBody: [], extBizInfo: {} }, - }, - }), - ]); - - const upload = await runNtv2Upload(baseParams({ - bridge, - label: 'video', - uploads: [{ - source: 'top', - cmdId: 1003, - bytes: new Uint8Array([1, 2, 3]), - md5: new Uint8Array(16), - sha1: new Uint8Array(20), - forceFullOnFastPath: true, - }], - })); - - // Two OIDB requests went out; the second omits tryFastUploadCompleted - // (proton drops `false`), which the server reads as "no fast-upload". - expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2); - const firstReq: any = protobuf_decode>(bridge.sendRawPacket.mock.calls[0]![1] as Uint8Array); - const secondReq: any = protobuf_decode>(bridge.sendRawPacket.mock.calls[1]![1] as Uint8Array); - expect(firstReq.body.upload.tryFastUploadCompleted).toBe(true); - expect(secondReq.body.upload.tryFastUploadCompleted ?? false).toBe(false); - - // The forced full upload PUT ran, and the returned upload is round 2's. - expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce(); - expect(upload.uKey).toBe('fresh-ukey'); - }); - - it('forceFullOnFastPath: no retry when the flagged file gets a uKey on the first try', async () => { - const bridge = makeBridge({ - responseData: encodeOidbResponse({ - upload: { uKey: 'ukey-1', msgInfo: { msgInfoBody: [], extBizInfo: {} } }, - }), - }); - await runNtv2Upload(baseParams({ - bridge, - uploads: [{ - source: 'top', cmdId: 1003, bytes: new Uint8Array([1, 2, 3]), - md5: new Uint8Array(16), sha1: new Uint8Array(20), forceFullOnFastPath: true, - }], - })); - expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); - expect(highway.uploadHighwayHttp).toHaveBeenCalledOnce(); - }); - - it('forceFullOnFastPath: no retry for a fast-pathed forward (no bytes to upload)', async () => { - const bridge = makeBridge({ - responseData: encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } } }), - }); - await runNtv2Upload(baseParams({ - bridge, - uploads: [{ - source: 'top', cmdId: 1003, bytes: new Uint8Array(0), - md5: new Uint8Array(16), sha1: new Uint8Array(20), forceFullOnFastPath: true, - }], - })); - // bytes.length === 0 → nothing to distrust; the fast-path stands. - expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); - expect(highway.uploadHighwayHttp).not.toHaveBeenCalled(); - }); - - it('a fast-pathed sub-file WITHOUT the flag (e.g. thumb) does not trigger a retry', async () => { - const bridge = makeBridge({ - responseData: encodeOidbResponse({ - // Main fully uploaded (has uKey); thumb fast-pathed (no subFileInfos). - upload: { uKey: 'main-ukey', msgInfo: { msgInfoBody: [], extBizInfo: {} } }, - }), - }); - await runNtv2Upload(baseParams({ - bridge, - uploads: [ - { source: 'top', cmdId: 1001, bytes: new Uint8Array([1]), md5: new Uint8Array(16), sha1: new Uint8Array(20), forceFullOnFastPath: true }, - { source: 0, cmdId: 1002, bytes: new Uint8Array([2]), md5: new Uint8Array(16), sha1: new Uint8Array(20) /* no flag */ }, - ], - })); - expect(bridge.sendRawPacket).toHaveBeenCalledOnce(); - }); + // (Removed the forceFullOnFastPath retry tests with the feature itself — real- + // machine testing + kernel RE proved the tryFastUploadCompleted:false retry + // never forces a fresh upload; expired-but-indexed video resources are a + // platform limitation. See #145.) it('silently skips a sub-file with empty bytes when no fastOnlyError is configured', async () => { // This mirrors the video-thumb path where bytes are always synthesised diff --git a/packages/core/tests/highway/video-upload.test.ts b/packages/core/tests/highway/video-upload.test.ts index e996fabb..cd1eb8ec 100644 --- a/packages/core/tests/highway/video-upload.test.ts +++ b/packages/core/tests/highway/video-upload.test.ts @@ -80,14 +80,14 @@ describe('video-upload', () => { expect(uploads[1]!.fastOnlyError).toBeUndefined(); }); - it('main file distrusts a server fast-path (forceFullOnFastPath); thumb does not (#145)', async () => { - // Group/c2c video resources expire server-side: a fast-path hit can - // reference a stale object the receiver shows as "资源已过期", so the - // main file forces a fresh full upload. The thumb stays fast-path-OK. + it('does NOT set a force-full retry flag on the main file (#145 — proven ineffective)', async () => { + // The old forceFullOnFastPath retry was removed: real-machine + kernel RE + // showed it never forces a fresh upload (the server fast-paths by md5 + // metadata regardless of tryFastUploadCompleted). An expired-but-indexed + // video resource is a platform limitation, not an upload-flow fix. await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT); const uploads = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads; - expect(uploads[0]!.forceFullOnFastPath).toBe(true); - expect(uploads[1]!.forceFullOnFastPath).toBeUndefined(); + expect((uploads[0] as unknown as Record).forceFullOnFastPath).toBeUndefined(); }); it('uploadInfo carries TWO entries (main mp4 + thumb jpg) with subFileType 0 and 100', async () => { diff --git a/packages/core/tests/webui-debug-tools.test.ts b/packages/core/tests/webui-debug-tools.test.ts new file mode 100644 index 00000000..aa63d7ea --- /dev/null +++ b/packages/core/tests/webui-debug-tools.test.ts @@ -0,0 +1,151 @@ +import { afterAll, describe, expect, it } from 'vitest'; +import { readdir, readFile, rm } from 'fs/promises'; +import path from 'path'; +import { + buildStreamInvokeResponse, + DEBUG_UPLOAD_DIR, + safeUploadName, + streamUploadToDisk, + uploadDestPath, +} from '../src/webui/debug-tools'; + +const written: string[] = []; +afterAll(async () => { + await Promise.all(written.map((p) => rm(p, { force: true }).catch(() => {}))); +}); + +function streamOf(...chunks: Uint8Array[]): ReadableStream { + let i = 0; + return new ReadableStream({ + pull(controller) { + if (i < chunks.length) controller.enqueue(chunks[i++]); + else controller.close(); + }, + }); +} + +async function readSse(res: Response): Promise { + const text = await res.text(); + return text.split('\n\n').filter((s) => s.startsWith('data: ')).map((s) => s.slice('data: '.length)); +} + +describe('safeUploadName', () => { + it('strips path traversal and separators to a bare basename', () => { + expect(safeUploadName('../../etc/passwd')).toBe('passwd'); + expect(safeUploadName('/abs/secret.key')).toBe('secret.key'); + expect(safeUploadName('a\\b\\c.png')).toBe('c.png'); + expect(safeUploadName('..')).toBe('file'); // leading dots stripped → empty → fallback + expect(safeUploadName('...hidden')).toBe('hidden'); + }); + it('collapses exotic chars and falls back for empties', () => { + expect(safeUploadName('my pic!@#.jpg')).toBe('my_pic_.jpg'); + expect(safeUploadName('')).toBe('file'); + expect(safeUploadName(undefined)).toBe('file'); + }); + it('keeps the extension and caps length', () => { + const long = 'x'.repeat(500) + '.mp4'; + const out = safeUploadName(long); + expect(out.length).toBeLessThanOrEqual(120); + expect(out.startsWith('x')).toBe(true); + }); +}); + +describe('uploadDestPath', () => { + it('produces a unique path inside the upload dir', () => { + const a = uploadDestPath('pic.png'); + const b = uploadDestPath('pic.png'); + expect(a).not.toBe(b); // random id prefix + expect(path.dirname(a)).toBe(DEBUG_UPLOAD_DIR); + expect(a.endsWith('__pic.png')).toBe(true); + const rel = path.relative(DEBUG_UPLOAD_DIR, a); + expect(rel.startsWith('..')).toBe(false); + expect(path.isAbsolute(rel)).toBe(false); + }); +}); + +describe('streamUploadToDisk', () => { + it('streams bytes to disk and reports the size', async () => { + const data = new TextEncoder().encode('hello debug upload'); + const res = await streamUploadToDisk(streamOf(data.slice(0, 5), data.slice(5)), 'note.txt'); + written.push(res.path); + expect(res.size).toBe(data.byteLength); + expect(path.dirname(res.path)).toBe(DEBUG_UPLOAD_DIR); + expect(await readFile(res.path, 'utf8')).toBe('hello debug upload'); + }); + + it('rejects and removes the partial file when the cap is exceeded', async () => { + const big = new Uint8Array(64); + await expect( + streamUploadToDisk(streamOf(big, big), 'big.bin', { maxBytes: 100 }), + ).rejects.toThrow(/大小上限/); + // the partial must not survive — no leftover `__big.bin` in the dir + const names = await readdir(DEBUG_UPLOAD_DIR).catch(() => [] as string[]); + expect(names.filter((n) => n.endsWith('__big.bin'))).toEqual([]); + }); + + it('rejects an empty body', async () => { + await expect(streamUploadToDisk(null, 'x')).rejects.toThrow(/empty/); + await expect(streamUploadToDisk(streamOf(), 'x')).rejects.toThrow(/empty/); + }); + + it('propagates a mid-transfer source error and removes the partial', async () => { + const failing = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('partial-bytes')); + controller.error(new Error('source aborted')); + }, + }); + await expect(streamUploadToDisk(failing, 'oops.bin')).rejects.toThrow(/source aborted/); + const names = await readdir(DEBUG_UPLOAD_DIR).catch(() => [] as string[]); + expect(names.filter((n) => n.endsWith('__oops.bin'))).toEqual([]); + }); +}); + +describe('buildStreamInvokeResponse', () => { + const noDelay = async () => {}; + + it('relays each emitted frame as one SSE event, in order', async () => { + const ac = new AbortController(); + const driver = async (_rq: string, emit: (j: string) => Promise) => { + await emit(JSON.stringify({ data: { type: 'stream', i: 1 } })); + await emit(JSON.stringify({ data: { type: 'stream', i: 2 } })); + await emit(JSON.stringify({ status: 'ok', data: { type: 'response' } })); + }; + const res = buildStreamInvokeResponse(driver, '{"action":"x"}', ac.signal, noDelay); + const frames = (await readSse(res)).map((s) => JSON.parse(s)); + expect(frames).toHaveLength(3); + expect(frames[0].data.i).toBe(1); + expect(frames[2].data.type).toBe('response'); + }); + + it('turns a driver error into a terminal failed frame', async () => { + const ac = new AbortController(); + const driver = async (_rq: string, emit: (j: string) => Promise) => { + await emit(JSON.stringify({ data: { type: 'stream' } })); + throw new Error('disk exploded'); + }; + const res = buildStreamInvokeResponse(driver, '{}', ac.signal, noDelay); + const frames = (await readSse(res)).map((s) => JSON.parse(s)); + expect(frames).toHaveLength(2); + expect(frames[1].status).toBe('failed'); + expect(frames[1].message).toMatch(/disk exploded/); + }); + + it('passes the raw request through to the driver', async () => { + const ac = new AbortController(); + let seen = ''; + const driver = async (rq: string, emit: (j: string) => Promise) => { + seen = rq; + await emit('{"data":{"type":"response"}}'); + }; + const res = buildStreamInvokeResponse(driver, '{"action":"test_download_stream"}', ac.signal, noDelay); + await readSse(res); + expect(seen).toBe('{"action":"test_download_stream"}'); + }); + + it('exposes an SSE content-type', () => { + const ac = new AbortController(); + const res = buildStreamInvokeResponse(async () => {}, '{}', ac.signal, noDelay); + expect(res.headers.get('Content-Type')).toBe('text/event-stream'); + }); +}); diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 25eb4069..fb901dad 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/mcp", - "version": "1.10.4", + "version": "1.11.0", "description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.", "repository": { "type": "git", diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index 31fbc9fc..24438b6c 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -10,6 +10,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -40,7 +41,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "fid": { "type": "string" @@ -66,6 +68,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -80,7 +83,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -172,6 +176,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -194,7 +199,8 @@ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "image" }, { "name": "pinned", @@ -222,7 +228,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "content": { "type": "string", @@ -230,7 +237,8 @@ }, "image": { "type": "string", - "default": "" + "default": "", + "x-role": "image" }, "pinned": {}, "type": {}, @@ -282,6 +290,7 @@ "name": "file", "type": "string", "required": true, + "role": "image", "schema": { "type": "string", "minLength": 1 @@ -294,7 +303,8 @@ "properties": { "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "image" } }, "required": [ @@ -379,6 +389,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -419,7 +430,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -452,6 +464,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -462,6 +475,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -477,13 +491,15 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "message_id": { "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -535,6 +551,21 @@ }, "category": "扩展" }, + { + "name": "clean_stream_temp_file", + "aliases": [], + "summary": "清理流式传输临时文件(仅清理 stream 上传/下载目录)", + "returns": "{ message, removed }", + "readOnly": false, + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "流式接口" + }, { "name": "click_inline_keyboard_button", "aliases": [], @@ -545,6 +576,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -577,7 +609,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "bot_appid": { "type": "integer", @@ -600,7 +633,7 @@ { "name": "comment_qzone", "aliases": [], - "summary": "评论一条说说(QQ 空间)", + "summary": "评论一条说说(QQ 空间,支持纯文字或带图;传 images 自动上传)", "readOnly": false, "params": [ { @@ -627,11 +660,25 @@ "name": "target_uin", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 }, "desc": "说说所属 QQ 号,省略则为机器人自己" + }, + { + "name": "images", + "type": "string[]", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "desc": "图片数组(可选),支持 file:// http:// base64://;自动上传" } ], "invariants": [], @@ -651,7 +698,16 @@ "target_uin": { "type": "integer", "minimum": 1, - "description": "说说所属 QQ 号,省略则为机器人自己" + "description": "说说所属 QQ 号,省略则为机器人自己", + "x-role": "user_id" + }, + "images": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "description": "图片数组(可选),支持 file:// http:// base64://;自动上传" } }, "required": [ @@ -672,6 +728,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -682,6 +739,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -697,13 +755,15 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "message_id": { "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -783,6 +843,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -815,7 +876,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "name": { "type": "string", @@ -843,6 +905,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -875,7 +938,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -937,6 +1001,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -953,7 +1018,8 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -1005,6 +1071,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -1028,7 +1095,8 @@ "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "user_id" }, "block": { "type": "boolean", @@ -1052,6 +1120,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1062,6 +1131,7 @@ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -1075,11 +1145,13 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" } }, "required": [ @@ -1100,6 +1172,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1123,7 +1196,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "folder_id": { "type": "string", @@ -1148,6 +1222,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1171,7 +1246,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "folder_id": { "type": "string", @@ -1196,6 +1272,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -1212,7 +1289,8 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -1265,6 +1343,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1306,7 +1385,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -1387,6 +1467,195 @@ }, "category": "扩展" }, + { + "name": "download_file_image_stream", + "aliases": [], + "summary": "以流式方式下载图片(缓存图片 id / URL / stream 目录本地文件)", + "returns": "流式帧:file_info → file_chunk* → file_complete", + "readOnly": false, + "params": [ + { + "name": "file", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件路径(限 stream 临时目录)/ http(s) URL", + "role": "file" + }, + { + "name": "file_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件 ID(缓存的图片/语音 id)", + "role": "file_id" + }, + { + "name": "chunk_size", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "分块大小(字节,默认 64KB)" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "file": { + "type": "string", + "description": "文件路径(限 stream 临时目录)/ http(s) URL", + "x-role": "file" + }, + "file_id": { + "type": "string", + "description": "文件 ID(缓存的图片/语音 id)", + "x-role": "file_id" + }, + "chunk_size": { + "type": "integer", + "minimum": 1, + "description": "分块大小(字节,默认 64KB)" + } + }, + "additionalProperties": true + }, + "stream": true, + "category": "流式接口" + }, + { + "name": "download_file_record_stream", + "aliases": [], + "summary": "以流式方式下载语音(缓存语音 id / URL / stream 目录本地文件)", + "returns": "流式帧:file_info → file_chunk* → file_complete", + "readOnly": false, + "params": [ + { + "name": "file", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件路径(限 stream 临时目录)/ http(s) URL", + "role": "file" + }, + { + "name": "file_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件 ID(缓存的图片/语音 id)", + "role": "file_id" + }, + { + "name": "chunk_size", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "分块大小(字节,默认 64KB)" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "file": { + "type": "string", + "description": "文件路径(限 stream 临时目录)/ http(s) URL", + "x-role": "file" + }, + "file_id": { + "type": "string", + "description": "文件 ID(缓存的图片/语音 id)", + "x-role": "file_id" + }, + "chunk_size": { + "type": "integer", + "minimum": 1, + "description": "分块大小(字节,默认 64KB)" + } + }, + "additionalProperties": true + }, + "stream": true, + "category": "流式接口" + }, + { + "name": "download_file_stream", + "aliases": [], + "summary": "以流式方式下载文件(stream 目录本地文件 / URL / 缓存媒体)", + "returns": "流式帧:file_info → file_chunk* → file_complete", + "readOnly": false, + "params": [ + { + "name": "file", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件路径(限 stream 临时目录)/ http(s) URL", + "role": "file" + }, + { + "name": "file_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件 ID(缓存的图片/语音 id)", + "role": "file_id" + }, + { + "name": "chunk_size", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "分块大小(字节,默认 64KB)" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "file": { + "type": "string", + "description": "文件路径(限 stream 临时目录)/ http(s) URL", + "x-role": "file" + }, + "file_id": { + "type": "string", + "description": "文件 ID(缓存的图片/语音 id)", + "x-role": "file_id" + }, + "chunk_size": { + "type": "integer", + "minimum": 1, + "description": "分块大小(字节,默认 64KB)" + } + }, + "additionalProperties": true + }, + "stream": true, + "category": "流式接口" + }, { "name": "download_fileset", "aliases": [], @@ -1564,6 +1833,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -1608,7 +1878,8 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "emojiId": { "type": "string", @@ -1661,7 +1932,8 @@ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "message_id" } ], "invariants": [], @@ -1670,7 +1942,8 @@ "properties": { "message_id": { "type": "string", - "default": "" + "default": "", + "x-role": "message_id" } }, "additionalProperties": true @@ -1687,6 +1960,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -1698,6 +1972,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -1712,11 +1987,13 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" } }, "required": [ @@ -1737,6 +2014,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -1748,6 +2026,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1762,11 +2041,13 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -1787,6 +2068,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -1796,6 +2078,7 @@ "name": "target_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -1808,11 +2091,13 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "target_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" } }, "required": [ @@ -1875,6 +2160,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1899,7 +2185,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "chat_type": { "type": "integer", @@ -1924,6 +2211,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1966,7 +2254,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "character": { "type": "string", @@ -2275,6 +2564,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -2300,7 +2590,8 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "emoji_id": { "type": "string", @@ -2325,6 +2616,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -2339,7 +2631,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -2362,7 +2655,8 @@ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "file_id" }, { "name": "file", @@ -2371,7 +2665,8 @@ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "file" } ], "invariants": [], @@ -2380,11 +2675,13 @@ "properties": { "file_id": { "type": "string", - "default": "" + "default": "", + "x-role": "file_id" }, "file": { "type": "string", - "default": "" + "default": "", + "x-role": "file" } }, "additionalProperties": true @@ -2663,6 +2960,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -2675,7 +2973,8 @@ "schema": { "type": "integer" }, - "default": 0 + "default": 0, + "role": "message_id" }, { "name": "count", @@ -2694,11 +2993,13 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "message_id": { "type": "integer", - "default": 0 + "default": 0, + "x-role": "message_id" }, "count": { "type": "integer", @@ -2768,6 +3069,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -2782,7 +3084,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -2822,6 +3125,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -2854,7 +3158,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -2906,6 +3211,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -2920,7 +3226,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -2940,6 +3247,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -2952,7 +3260,8 @@ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -3000,6 +3309,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3014,7 +3324,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -3047,6 +3358,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3057,6 +3369,7 @@ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -3076,11 +3389,13 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" }, "busid": {} }, @@ -3202,6 +3517,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3234,7 +3550,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "folder_id": { "type": "string", @@ -3262,6 +3579,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3282,7 +3600,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "type": {} }, @@ -3481,6 +3800,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3504,7 +3824,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "no_cache": { "type": "boolean", @@ -3528,6 +3849,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3540,7 +3862,8 @@ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -3686,6 +4009,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3696,6 +4020,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -3719,12 +4044,14 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "no_cache": { "type": "boolean", @@ -3818,6 +4145,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3841,7 +4169,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "no_cache": { "type": "boolean", @@ -3881,6 +4210,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3894,7 +4224,8 @@ "schema": { "type": "integer" }, - "default": 0 + "default": 0, + "role": "message_id" }, { "name": "count", @@ -3914,11 +4245,13 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "message_id": { "type": "integer", - "default": 0 + "default": 0, + "x-role": "message_id" }, "count": { "type": "integer", @@ -4043,6 +4376,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -4057,7 +4391,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -4103,6 +4438,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -4117,7 +4453,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -4137,6 +4474,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -4151,7 +4489,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -4188,7 +4527,8 @@ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "image" }, { "name": "file_id", @@ -4197,7 +4537,8 @@ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "file_id" } ], "invariants": [], @@ -4206,11 +4547,13 @@ "properties": { "file": { "type": "string", - "default": "" + "default": "", + "x-role": "image" }, "file_id": { "type": "string", - "default": "" + "default": "", + "x-role": "file_id" } }, "additionalProperties": true @@ -4273,6 +4616,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -4289,7 +4633,8 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -4349,6 +4694,7 @@ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -4358,6 +4704,7 @@ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -4379,11 +4726,13 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" }, "file_hash": { "type": "string", @@ -4479,7 +4828,8 @@ "type": "integer", "minimum": 0 }, - "default": 0 + "default": 0, + "role": "user_id" }, { "name": "start", @@ -4509,7 +4859,8 @@ "user_id": { "type": "integer", "minimum": 0, - "default": 0 + "default": 0, + "x-role": "user_id" }, "start": { "type": "integer", @@ -4585,6 +4936,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -4599,7 +4951,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -4784,6 +5137,7 @@ "name": "target_uin", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -4821,7 +5175,8 @@ "target_uin": { "type": "integer", "minimum": 1, - "description": "目标 QQ 号,省略则取机器人自己" + "description": "目标 QQ 号,省略则取机器人自己", + "x-role": "user_id" }, "pos": { "type": "integer", @@ -4880,7 +5235,7 @@ { "name": "get_record", "aliases": [], - "summary": "获取语音信息", + "summary": "获取语音信息;传 out_format 则服务端转码并附带 base64", "readOnly": true, "params": [ { @@ -4890,7 +5245,8 @@ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "record" }, { "name": "file_id", @@ -4899,7 +5255,35 @@ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "file_id" + }, + { + "name": "out_format", + "type": "enum", + "required": false, + "values": [ + "mp3", + "amr", + "wma", + "m4a", + "spx", + "ogg", + "wav", + "flac" + ], + "schema": { + "enum": [ + "mp3", + "amr", + "wma", + "m4a", + "spx", + "ogg", + "wav", + "flac" + ] + } } ], "invariants": [], @@ -4908,11 +5292,25 @@ "properties": { "file": { "type": "string", - "default": "" + "default": "", + "x-role": "record" }, "file_id": { "type": "string", - "default": "" + "default": "", + "x-role": "file_id" + }, + "out_format": { + "enum": [ + "mp3", + "amr", + "wma", + "m4a", + "spx", + "ogg", + "wav", + "flac" + ] } }, "additionalProperties": true @@ -5084,6 +5482,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -5098,7 +5497,8 @@ "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "user_id" } }, "required": [ @@ -5168,6 +5568,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -5178,6 +5579,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -5192,12 +5594,14 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" } }, "required": [ @@ -5228,6 +5632,7 @@ "name": "target_uin", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -5243,7 +5648,8 @@ "minimum": 0 }, "desc": "说说发表时间(unix 秒),传真实值更可靠", - "default": 0 + "default": 0, + "role": "timestamp" } ], "invariants": [], @@ -5258,13 +5664,15 @@ "target_uin": { "type": "integer", "minimum": 1, - "description": "说说所属 QQ 号,省略则为机器人自己" + "description": "说说所属 QQ 号,省略则为机器人自己", + "x-role": "user_id" }, "abstime": { "type": "integer", "minimum": 0, "description": "说说发表时间(unix 秒),传真实值更可靠", - "default": 0 + "default": 0, + "x-role": "timestamp" } }, "required": [ @@ -5298,6 +5706,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -5309,6 +5718,7 @@ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -5323,11 +5733,13 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -5347,6 +5759,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -5372,7 +5785,8 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "target_id": { "type": "integer", @@ -5396,6 +5810,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -5407,6 +5822,7 @@ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -5421,11 +5837,13 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" } }, "required": [ @@ -5522,6 +5940,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -5532,6 +5951,7 @@ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -5563,11 +5983,13 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" }, "parent_directory": { "type": "string", @@ -5635,6 +6057,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -5647,7 +6070,8 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" } }, "required": [ @@ -5726,6 +6150,7 @@ "name": "image", "type": "string", "required": true, + "role": "image", "schema": { "type": "string", "minLength": 1 @@ -5738,7 +6163,8 @@ "properties": { "image": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "image" } }, "required": [ @@ -5804,6 +6230,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -5814,6 +6241,7 @@ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -5845,11 +6273,13 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" }, "current_parent_directory": { "type": "string", @@ -5879,6 +6309,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -5920,7 +6351,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "folder_id": { "type": "string", @@ -5998,6 +6430,7 @@ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6007,6 +6440,7 @@ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6028,11 +6462,13 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "phone_number": { "type": "string", @@ -6063,6 +6499,7 @@ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6072,6 +6509,7 @@ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6088,11 +6526,13 @@ }, "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -6151,6 +6591,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6193,7 +6634,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "character": { "type": "string", @@ -6233,6 +6675,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6245,7 +6688,8 @@ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -6266,6 +6710,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6296,7 +6741,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "messages": { "description": "OneBot message: string | segment[] | object" @@ -6323,6 +6769,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6354,7 +6801,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "message": { "description": "OneBot message: string | segment[] | object" @@ -6382,6 +6830,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6404,7 +6853,8 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "times": { "type": "integer", @@ -6446,6 +6896,7 @@ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6455,6 +6906,7 @@ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6482,11 +6934,13 @@ }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "auto_escape": { "type": "boolean", @@ -6570,6 +7024,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6579,6 +7034,7 @@ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6591,11 +7047,13 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -6616,6 +7074,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6644,7 +7103,8 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "messages": { "description": "OneBot message: string | segment[] | object" @@ -6671,6 +7131,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6700,7 +7161,8 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "message": { "description": "OneBot message: string | segment[] | object" @@ -6721,7 +7183,7 @@ { "name": "send_qzone_msg", "aliases": [], - "summary": "发表一条纯文字说说(QQ 空间)", + "summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)", "readOnly": false, "params": [ { @@ -6733,6 +7195,19 @@ "minLength": 1 }, "desc": "说说正文" + }, + { + "name": "images", + "type": "string[]", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "desc": "图片数组(可选),支持 file:// http:// base64://;自动上传" } ], "invariants": [], @@ -6743,6 +7218,14 @@ "type": "string", "minLength": 1, "description": "说说正文" + }, + "images": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "description": "图片数组(可选),支持 file:// http:// base64://;自动上传" } }, "required": [ @@ -6760,11 +7243,12 @@ "params": [ { "name": "face_id", - "type": "uint", + "type": "int", "required": true, + "role": "face_id", "schema": { "type": "integer", - "minimum": 1 + "minimum": 0 } }, { @@ -6793,7 +7277,8 @@ "properties": { "face_id": { "type": "integer", - "minimum": 1 + "minimum": 0, + "x-role": "face_id" }, "face_type": { "type": "integer", @@ -6867,6 +7352,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -6883,7 +7369,8 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -6948,6 +7435,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6968,7 +7456,8 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "remark": { "type": "string" @@ -6992,6 +7481,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7016,7 +7506,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "add_type": { "type": "integer", @@ -7113,6 +7604,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7123,6 +7615,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -7146,12 +7639,14 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "enable": { "type": "boolean", @@ -7175,6 +7670,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7215,7 +7711,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -7276,6 +7773,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7286,6 +7784,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -7296,6 +7795,7 @@ "name": "duration", "type": "int", "required": false, + "role": "duration", "schema": { "type": "integer", "minimum": 0 @@ -7310,17 +7810,20 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "duration": { "type": "integer", "minimum": 0, - "default": 1800 + "default": 1800, + "x-role": "duration" } }, "required": [ @@ -7341,6 +7844,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7351,6 +7855,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -7374,12 +7879,14 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "card": { "type": "string", @@ -7404,6 +7911,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7414,6 +7922,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -7437,12 +7946,14 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "reject_add_request": { "type": "boolean", @@ -7467,6 +7978,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7481,7 +7993,8 @@ "type": "array", "items": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "member_id" }, "minItems": 1 } @@ -7503,13 +8016,15 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "array", "items": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "member_id" }, "minItems": 1 }, @@ -7536,6 +8051,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7550,7 +8066,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -7570,6 +8087,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7593,7 +8111,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "group_name": { "type": "string", @@ -7617,6 +8136,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7627,6 +8147,7 @@ "name": "file", "type": "string", "required": true, + "role": "image", "schema": { "type": "string", "minLength": 1 @@ -7640,11 +8161,13 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "image" } }, "required": [ @@ -7665,6 +8188,7 @@ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7674,6 +8198,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -7706,13 +8231,15 @@ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "message_id": { "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "code": { "type": "string", @@ -7741,6 +8268,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7761,7 +8289,8 @@ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "remark": { "type": "string" @@ -7785,6 +8314,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7817,7 +8347,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "robot_member_switch": { "type": "integer", @@ -7845,6 +8376,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7859,7 +8391,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -7881,6 +8414,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7895,7 +8429,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -7915,6 +8450,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7925,6 +8461,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -7948,12 +8485,14 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "special_title": { "type": "string", @@ -7978,6 +8517,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7988,6 +8528,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -8003,13 +8544,15 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "message_id": { "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -8030,6 +8573,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8053,7 +8597,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "enable": { "type": "boolean", @@ -8077,6 +8622,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -8098,7 +8644,8 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "event_type": { "type": "integer", @@ -8122,6 +8669,7 @@ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -8156,7 +8704,8 @@ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "emoji_id": { "type": "string", @@ -8251,6 +8800,7 @@ "name": "file", "type": "string", "required": true, + "role": "image", "schema": { "type": "string", "minLength": 1 @@ -8263,7 +8813,8 @@ "properties": { "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "image" } }, "required": [ @@ -8370,6 +8921,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8382,7 +8934,8 @@ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -8415,6 +8968,7 @@ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -8424,6 +8978,7 @@ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8445,11 +9000,13 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "phone_number": { "type": "string", @@ -8460,6 +9017,39 @@ }, "category": "扩展" }, + { + "name": "test_download_stream", + "aliases": [], + "summary": "测试下载流(推送 10 个数据帧,验证流式传输,不触达 QQ)", + "returns": "流式帧:data_chunk*10 → data_complete(error=true 时以 error 帧结束)", + "readOnly": false, + "params": [ + { + "name": "error", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false, + "desc": "是否触发测试错误" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "error": { + "type": "boolean", + "description": "是否触发测试错误", + "default": false + } + }, + "additionalProperties": true + }, + "stream": true, + "category": "流式接口" + }, { "name": "trans_group_file", "aliases": [], @@ -8533,6 +9123,7 @@ "name": "target_uin", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -8548,7 +9139,8 @@ "minimum": 0 }, "desc": "说说发表时间(unix 秒),传真实值更可靠", - "default": 0 + "default": 0, + "role": "timestamp" } ], "invariants": [], @@ -8563,13 +9155,15 @@ "target_uin": { "type": "integer", "minimum": 1, - "description": "说说所属 QQ 号,省略则为机器人自己" + "description": "说说所属 QQ 号,省略则为机器人自己", + "x-role": "user_id" }, "abstime": { "type": "integer", "minimum": 0, "description": "说说发表时间(unix 秒),传真实值更可靠", - "default": 0 + "default": 0, + "x-role": "timestamp" } }, "required": [ @@ -8579,6 +9173,182 @@ }, "category": "空间" }, + { + "name": "upload_file_stream", + "aliases": [], + "summary": "以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)", + "returns": "流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_size/sha256)", + "readOnly": false, + "params": [ + { + "name": "stream_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + }, + "desc": "流 ID(客户端生成的 UUID,限 [A-Za-z0-9_-])" + }, + { + "name": "chunk_data", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "分块数据(Base64)" + }, + { + "name": "chunk_index", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "desc": "分块索引(从 0 开始)" + }, + { + "name": "total_chunks", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "总分块数(新流必填)" + }, + { + "name": "file_size", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "desc": "文件总大小(字节)" + }, + { + "name": "expected_sha256", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "期望的整文件 SHA256(校验)" + }, + { + "name": "is_complete", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "desc": "是否为最后一个分块/触发合并" + }, + { + "name": "filename", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件名" + }, + { + "name": "reset", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "desc": "重置并丢弃该流" + }, + { + "name": "verify_only", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "desc": "仅查询当前流状态" + }, + { + "name": "file_retention", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 300000, + "desc": "合并文件保留毫秒(0=不回收)" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "stream_id": { + "type": "string", + "minLength": 1, + "description": "流 ID(客户端生成的 UUID,限 [A-Za-z0-9_-])" + }, + "chunk_data": { + "type": "string", + "description": "分块数据(Base64)" + }, + "chunk_index": { + "type": "integer", + "minimum": 0, + "description": "分块索引(从 0 开始)" + }, + "total_chunks": { + "type": "integer", + "minimum": 1, + "description": "总分块数(新流必填)" + }, + "file_size": { + "type": "integer", + "minimum": 0, + "description": "文件总大小(字节)" + }, + "expected_sha256": { + "type": "string", + "description": "期望的整文件 SHA256(校验)" + }, + "is_complete": { + "type": "boolean", + "description": "是否为最后一个分块/触发合并" + }, + "filename": { + "type": "string", + "description": "文件名" + }, + "reset": { + "type": "boolean", + "description": "重置并丢弃该流" + }, + "verify_only": { + "type": "boolean", + "description": "仅查询当前流状态" + }, + "file_retention": { + "type": "integer", + "minimum": 0, + "description": "合并文件保留毫秒(0=不回收)", + "default": 300000 + } + }, + "required": [ + "stream_id" + ], + "additionalProperties": true + }, + "stream": true, + "category": "流式接口" + }, { "name": "upload_forward_msg", "aliases": [], @@ -8605,6 +9375,7 @@ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8623,7 +9394,8 @@ }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "additionalProperties": true @@ -8656,6 +9428,7 @@ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8674,7 +9447,8 @@ }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "additionalProperties": true @@ -8692,6 +9466,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8702,6 +9477,7 @@ "name": "file", "type": "string", "required": true, + "role": "file", "schema": { "type": "string", "minLength": 1 @@ -8751,11 +9527,13 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file" }, "name": { "type": "string", @@ -8791,6 +9569,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8819,6 +9598,7 @@ "name": "file", "type": "string", "required": true, + "role": "image", "schema": { "type": "string", "minLength": 1 @@ -8832,7 +9612,8 @@ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -8844,7 +9625,8 @@ }, "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "image" } }, "required": [ @@ -8868,6 +9650,7 @@ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -8877,6 +9660,7 @@ "name": "file", "type": "string", "required": true, + "role": "file", "schema": { "type": "string", "minLength": 1 @@ -8907,11 +9691,13 @@ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file" }, "name": { "type": "string", @@ -8971,6 +9757,10 @@ { "category": "空间", "count": 7 + }, + { + "category": "流式接口", + "count": 6 } ] } diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 3cb4dba9..b462ff50 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -13,6 +13,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -43,7 +44,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "fid": { "type": "string" @@ -69,6 +71,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -83,7 +86,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -175,6 +179,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -197,7 +202,8 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "image" }, { "name": "pinned", @@ -225,7 +231,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "content": { "type": "string", @@ -233,7 +240,8 @@ export const ACTIONS: CatalogAction[] = [ }, "image": { "type": "string", - "default": "" + "default": "", + "x-role": "image" }, "pinned": {}, "type": {}, @@ -285,6 +293,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file", "type": "string", "required": true, + "role": "image", "schema": { "type": "string", "minLength": 1 @@ -297,7 +306,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "image" } }, "required": [ @@ -382,6 +392,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -422,7 +433,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -455,6 +467,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -465,6 +478,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -480,13 +494,15 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "message_id": { "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -538,6 +554,21 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "clean_stream_temp_file", + "aliases": [], + "summary": "清理流式传输临时文件(仅清理 stream 上传/下载目录)", + "returns": "{ message, removed }", + "readOnly": false, + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "流式接口" + }, { "name": "click_inline_keyboard_button", "aliases": [], @@ -548,6 +579,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -580,7 +612,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "bot_appid": { "type": "integer", @@ -603,7 +636,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "comment_qzone", "aliases": [], - "summary": "评论一条说说(QQ 空间)", + "summary": "评论一条说说(QQ 空间,支持纯文字或带图;传 images 自动上传)", "readOnly": false, "params": [ { @@ -630,11 +663,25 @@ export const ACTIONS: CatalogAction[] = [ "name": "target_uin", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 }, "desc": "说说所属 QQ 号,省略则为机器人自己" + }, + { + "name": "images", + "type": "string[]", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "desc": "图片数组(可选),支持 file:// http:// base64://;自动上传" } ], "invariants": [], @@ -654,7 +701,16 @@ export const ACTIONS: CatalogAction[] = [ "target_uin": { "type": "integer", "minimum": 1, - "description": "说说所属 QQ 号,省略则为机器人自己" + "description": "说说所属 QQ 号,省略则为机器人自己", + "x-role": "user_id" + }, + "images": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "description": "图片数组(可选),支持 file:// http:// base64://;自动上传" } }, "required": [ @@ -675,6 +731,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -685,6 +742,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -700,13 +758,15 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "message_id": { "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -786,6 +846,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -818,7 +879,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "name": { "type": "string", @@ -846,6 +908,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -878,7 +941,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -940,6 +1004,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -956,7 +1021,8 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -1008,6 +1074,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -1031,7 +1098,8 @@ export const ACTIONS: CatalogAction[] = [ "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "user_id" }, "block": { "type": "boolean", @@ -1055,6 +1123,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1065,6 +1134,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -1078,11 +1148,13 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" } }, "required": [ @@ -1103,6 +1175,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1126,7 +1199,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "folder_id": { "type": "string", @@ -1151,6 +1225,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1174,7 +1249,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "folder_id": { "type": "string", @@ -1199,6 +1275,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -1215,7 +1292,8 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -1268,6 +1346,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1309,7 +1388,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -1390,6 +1470,195 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "download_file_image_stream", + "aliases": [], + "summary": "以流式方式下载图片(缓存图片 id / URL / stream 目录本地文件)", + "returns": "流式帧:file_info → file_chunk* → file_complete", + "readOnly": false, + "params": [ + { + "name": "file", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件路径(限 stream 临时目录)/ http(s) URL", + "role": "file" + }, + { + "name": "file_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件 ID(缓存的图片/语音 id)", + "role": "file_id" + }, + { + "name": "chunk_size", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "分块大小(字节,默认 64KB)" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "file": { + "type": "string", + "description": "文件路径(限 stream 临时目录)/ http(s) URL", + "x-role": "file" + }, + "file_id": { + "type": "string", + "description": "文件 ID(缓存的图片/语音 id)", + "x-role": "file_id" + }, + "chunk_size": { + "type": "integer", + "minimum": 1, + "description": "分块大小(字节,默认 64KB)" + } + }, + "additionalProperties": true + }, + "stream": true, + "category": "流式接口" + }, + { + "name": "download_file_record_stream", + "aliases": [], + "summary": "以流式方式下载语音(缓存语音 id / URL / stream 目录本地文件)", + "returns": "流式帧:file_info → file_chunk* → file_complete", + "readOnly": false, + "params": [ + { + "name": "file", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件路径(限 stream 临时目录)/ http(s) URL", + "role": "file" + }, + { + "name": "file_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件 ID(缓存的图片/语音 id)", + "role": "file_id" + }, + { + "name": "chunk_size", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "分块大小(字节,默认 64KB)" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "file": { + "type": "string", + "description": "文件路径(限 stream 临时目录)/ http(s) URL", + "x-role": "file" + }, + "file_id": { + "type": "string", + "description": "文件 ID(缓存的图片/语音 id)", + "x-role": "file_id" + }, + "chunk_size": { + "type": "integer", + "minimum": 1, + "description": "分块大小(字节,默认 64KB)" + } + }, + "additionalProperties": true + }, + "stream": true, + "category": "流式接口" + }, + { + "name": "download_file_stream", + "aliases": [], + "summary": "以流式方式下载文件(stream 目录本地文件 / URL / 缓存媒体)", + "returns": "流式帧:file_info → file_chunk* → file_complete", + "readOnly": false, + "params": [ + { + "name": "file", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件路径(限 stream 临时目录)/ http(s) URL", + "role": "file" + }, + { + "name": "file_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件 ID(缓存的图片/语音 id)", + "role": "file_id" + }, + { + "name": "chunk_size", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "分块大小(字节,默认 64KB)" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "file": { + "type": "string", + "description": "文件路径(限 stream 临时目录)/ http(s) URL", + "x-role": "file" + }, + "file_id": { + "type": "string", + "description": "文件 ID(缓存的图片/语音 id)", + "x-role": "file_id" + }, + "chunk_size": { + "type": "integer", + "minimum": 1, + "description": "分块大小(字节,默认 64KB)" + } + }, + "additionalProperties": true + }, + "stream": true, + "category": "流式接口" + }, { "name": "download_fileset", "aliases": [], @@ -1567,6 +1836,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -1611,7 +1881,8 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "emojiId": { "type": "string", @@ -1664,7 +1935,8 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "message_id" } ], "invariants": [], @@ -1673,7 +1945,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "message_id": { "type": "string", - "default": "" + "default": "", + "x-role": "message_id" } }, "additionalProperties": true @@ -1690,6 +1963,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -1701,6 +1975,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -1715,11 +1990,13 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" } }, "required": [ @@ -1740,6 +2017,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -1751,6 +2029,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1765,11 +2044,13 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -1790,6 +2071,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -1799,6 +2081,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "target_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -1811,11 +2094,13 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "target_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" } }, "required": [ @@ -1878,6 +2163,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1902,7 +2188,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "chat_type": { "type": "integer", @@ -1927,6 +2214,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -1969,7 +2257,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "character": { "type": "string", @@ -2278,6 +2567,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -2303,7 +2593,8 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "emoji_id": { "type": "string", @@ -2328,6 +2619,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -2342,7 +2634,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -2365,7 +2658,8 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "file_id" }, { "name": "file", @@ -2374,7 +2668,8 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "file" } ], "invariants": [], @@ -2383,11 +2678,13 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "file_id": { "type": "string", - "default": "" + "default": "", + "x-role": "file_id" }, "file": { "type": "string", - "default": "" + "default": "", + "x-role": "file" } }, "additionalProperties": true @@ -2666,6 +2963,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -2678,7 +2976,8 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "integer" }, - "default": 0 + "default": 0, + "role": "message_id" }, { "name": "count", @@ -2697,11 +2996,13 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "message_id": { "type": "integer", - "default": 0 + "default": 0, + "x-role": "message_id" }, "count": { "type": "integer", @@ -2771,6 +3072,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -2785,7 +3087,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -2825,6 +3128,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -2857,7 +3161,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -2909,6 +3214,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -2923,7 +3229,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -2943,6 +3250,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -2955,7 +3263,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -3003,6 +3312,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3017,7 +3327,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -3050,6 +3361,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3060,6 +3372,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -3079,11 +3392,13 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" }, "busid": {} }, @@ -3205,6 +3520,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3237,7 +3553,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "folder_id": { "type": "string", @@ -3265,6 +3582,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3285,7 +3603,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "type": {} }, @@ -3484,6 +3803,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3507,7 +3827,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "no_cache": { "type": "boolean", @@ -3531,6 +3852,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3543,7 +3865,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -3689,6 +4012,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3699,6 +4023,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -3722,12 +4047,14 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "no_cache": { "type": "boolean", @@ -3821,6 +4148,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3844,7 +4172,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "no_cache": { "type": "boolean", @@ -3884,6 +4213,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -3897,7 +4227,8 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "integer" }, - "default": 0 + "default": 0, + "role": "message_id" }, { "name": "count", @@ -3917,11 +4248,13 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "message_id": { "type": "integer", - "default": 0 + "default": 0, + "x-role": "message_id" }, "count": { "type": "integer", @@ -4046,6 +4379,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -4060,7 +4394,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -4106,6 +4441,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -4120,7 +4456,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -4140,6 +4477,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -4154,7 +4492,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -4191,7 +4530,8 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "image" }, { "name": "file_id", @@ -4200,7 +4540,8 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "file_id" } ], "invariants": [], @@ -4209,11 +4550,13 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "file": { "type": "string", - "default": "" + "default": "", + "x-role": "image" }, "file_id": { "type": "string", - "default": "" + "default": "", + "x-role": "file_id" } }, "additionalProperties": true @@ -4276,6 +4619,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -4292,7 +4636,8 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -4352,6 +4697,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -4361,6 +4707,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -4382,11 +4729,13 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" }, "file_hash": { "type": "string", @@ -4482,7 +4831,8 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "minimum": 0 }, - "default": 0 + "default": 0, + "role": "user_id" }, { "name": "start", @@ -4512,7 +4862,8 @@ export const ACTIONS: CatalogAction[] = [ "user_id": { "type": "integer", "minimum": 0, - "default": 0 + "default": 0, + "x-role": "user_id" }, "start": { "type": "integer", @@ -4588,6 +4939,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -4602,7 +4954,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -4787,6 +5140,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "target_uin", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -4824,7 +5178,8 @@ export const ACTIONS: CatalogAction[] = [ "target_uin": { "type": "integer", "minimum": 1, - "description": "目标 QQ 号,省略则取机器人自己" + "description": "目标 QQ 号,省略则取机器人自己", + "x-role": "user_id" }, "pos": { "type": "integer", @@ -4883,7 +5238,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_record", "aliases": [], - "summary": "获取语音信息", + "summary": "获取语音信息;传 out_format 则服务端转码并附带 base64", "readOnly": true, "params": [ { @@ -4893,7 +5248,8 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "record" }, { "name": "file_id", @@ -4902,7 +5258,35 @@ export const ACTIONS: CatalogAction[] = [ "schema": { "type": "string" }, - "default": "" + "default": "", + "role": "file_id" + }, + { + "name": "out_format", + "type": "enum", + "required": false, + "values": [ + "mp3", + "amr", + "wma", + "m4a", + "spx", + "ogg", + "wav", + "flac" + ], + "schema": { + "enum": [ + "mp3", + "amr", + "wma", + "m4a", + "spx", + "ogg", + "wav", + "flac" + ] + } } ], "invariants": [], @@ -4911,11 +5295,25 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "file": { "type": "string", - "default": "" + "default": "", + "x-role": "record" }, "file_id": { "type": "string", - "default": "" + "default": "", + "x-role": "file_id" + }, + "out_format": { + "enum": [ + "mp3", + "amr", + "wma", + "m4a", + "spx", + "ogg", + "wav", + "flac" + ] } }, "additionalProperties": true @@ -5087,6 +5485,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -5101,7 +5500,8 @@ export const ACTIONS: CatalogAction[] = [ "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "user_id" } }, "required": [ @@ -5171,6 +5571,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -5181,6 +5582,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -5195,12 +5597,14 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" } }, "required": [ @@ -5231,6 +5635,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "target_uin", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -5246,7 +5651,8 @@ export const ACTIONS: CatalogAction[] = [ "minimum": 0 }, "desc": "说说发表时间(unix 秒),传真实值更可靠", - "default": 0 + "default": 0, + "role": "timestamp" } ], "invariants": [], @@ -5261,13 +5667,15 @@ export const ACTIONS: CatalogAction[] = [ "target_uin": { "type": "integer", "minimum": 1, - "description": "说说所属 QQ 号,省略则为机器人自己" + "description": "说说所属 QQ 号,省略则为机器人自己", + "x-role": "user_id" }, "abstime": { "type": "integer", "minimum": 0, "description": "说说发表时间(unix 秒),传真实值更可靠", - "default": 0 + "default": 0, + "x-role": "timestamp" } }, "required": [ @@ -5301,6 +5709,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -5312,6 +5721,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -5326,11 +5736,13 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -5350,6 +5762,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -5375,7 +5788,8 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "target_id": { "type": "integer", @@ -5399,6 +5813,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -5410,6 +5825,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -5424,11 +5840,13 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" } }, "required": [ @@ -5525,6 +5943,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -5535,6 +5954,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -5566,11 +5986,13 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" }, "parent_directory": { "type": "string", @@ -5638,6 +6060,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -5650,7 +6073,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" } }, "required": [ @@ -5729,6 +6153,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "image", "type": "string", "required": true, + "role": "image", "schema": { "type": "string", "minLength": 1 @@ -5741,7 +6166,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "image": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "image" } }, "required": [ @@ -5807,6 +6233,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -5817,6 +6244,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -5848,11 +6276,13 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" }, "current_parent_directory": { "type": "string", @@ -5882,6 +6312,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -5923,7 +6354,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "folder_id": { "type": "string", @@ -6001,6 +6433,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6010,6 +6443,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6031,11 +6465,13 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "phone_number": { "type": "string", @@ -6066,6 +6502,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6075,6 +6512,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6091,11 +6529,13 @@ export const ACTIONS: CatalogAction[] = [ }, "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -6154,6 +6594,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6196,7 +6637,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "character": { "type": "string", @@ -6236,6 +6678,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6248,7 +6691,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -6269,6 +6713,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6299,7 +6744,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "messages": { "description": "OneBot message: string | segment[] | object" @@ -6326,6 +6772,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6357,7 +6804,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "message": { "description": "OneBot message: string | segment[] | object" @@ -6385,6 +6833,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6407,7 +6856,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "times": { "type": "integer", @@ -6449,6 +6899,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6458,6 +6909,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6485,11 +6937,13 @@ export const ACTIONS: CatalogAction[] = [ }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "auto_escape": { "type": "boolean", @@ -6573,6 +7027,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6582,6 +7037,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -6594,11 +7050,13 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -6619,6 +7077,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6647,7 +7106,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "messages": { "description": "OneBot message: string | segment[] | object" @@ -6674,6 +7134,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6703,7 +7164,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "message": { "description": "OneBot message: string | segment[] | object" @@ -6724,7 +7186,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "send_qzone_msg", "aliases": [], - "summary": "发表一条纯文字说说(QQ 空间)", + "summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)", "readOnly": false, "params": [ { @@ -6736,6 +7198,19 @@ export const ACTIONS: CatalogAction[] = [ "minLength": 1 }, "desc": "说说正文" + }, + { + "name": "images", + "type": "string[]", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "desc": "图片数组(可选),支持 file:// http:// base64://;自动上传" } ], "invariants": [], @@ -6746,6 +7221,14 @@ export const ACTIONS: CatalogAction[] = [ "type": "string", "minLength": 1, "description": "说说正文" + }, + "images": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "description": "图片数组(可选),支持 file:// http:// base64://;自动上传" } }, "required": [ @@ -6763,11 +7246,12 @@ export const ACTIONS: CatalogAction[] = [ "params": [ { "name": "face_id", - "type": "uint", + "type": "int", "required": true, + "role": "face_id", "schema": { "type": "integer", - "minimum": 1 + "minimum": 0 } }, { @@ -6796,7 +7280,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "face_id": { "type": "integer", - "minimum": 1 + "minimum": 0, + "x-role": "face_id" }, "face_type": { "type": "integer", @@ -6870,6 +7355,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -6886,7 +7372,8 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -6951,6 +7438,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -6971,7 +7459,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "remark": { "type": "string" @@ -6995,6 +7484,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7019,7 +7509,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "add_type": { "type": "integer", @@ -7116,6 +7607,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7126,6 +7618,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -7149,12 +7642,14 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "enable": { "type": "boolean", @@ -7178,6 +7673,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7218,7 +7714,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -7279,6 +7776,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7289,6 +7787,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -7299,6 +7798,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "duration", "type": "int", "required": false, + "role": "duration", "schema": { "type": "integer", "minimum": 0 @@ -7313,17 +7813,20 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "duration": { "type": "integer", "minimum": 0, - "default": 1800 + "default": 1800, + "x-role": "duration" } }, "required": [ @@ -7344,6 +7847,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7354,6 +7858,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -7377,12 +7882,14 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "card": { "type": "string", @@ -7407,6 +7914,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7417,6 +7925,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -7440,12 +7949,14 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "reject_add_request": { "type": "boolean", @@ -7470,6 +7981,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7484,7 +7996,8 @@ export const ACTIONS: CatalogAction[] = [ "type": "array", "items": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "member_id" }, "minItems": 1 } @@ -7506,13 +8019,15 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "array", "items": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "member_id" }, "minItems": 1 }, @@ -7539,6 +8054,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7553,7 +8069,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -7573,6 +8090,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7596,7 +8114,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "group_name": { "type": "string", @@ -7620,6 +8139,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7630,6 +8150,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file", "type": "string", "required": true, + "role": "image", "schema": { "type": "string", "minLength": 1 @@ -7643,11 +8164,13 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "image" } }, "required": [ @@ -7668,6 +8191,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7677,6 +8201,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -7709,13 +8234,15 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "message_id": { "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "code": { "type": "string", @@ -7744,6 +8271,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7764,7 +8292,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "remark": { "type": "string" @@ -7788,6 +8317,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7820,7 +8350,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "robot_member_switch": { "type": "integer", @@ -7848,6 +8379,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7862,7 +8394,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -7884,6 +8417,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7898,7 +8432,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" } }, "required": [ @@ -7918,6 +8453,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7928,6 +8464,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "member_id", "schema": { "type": "integer", "minimum": 1 @@ -7951,12 +8488,14 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "user_id": { "type": "integer", "minimum": 1, - "description": "QQ 号" + "description": "QQ 号", + "x-role": "member_id" }, "special_title": { "type": "string", @@ -7981,6 +8520,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -7991,6 +8531,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -8006,13 +8547,15 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "message_id": { "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" } }, "required": [ @@ -8033,6 +8576,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8056,7 +8600,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "enable": { "type": "boolean", @@ -8080,6 +8625,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -8101,7 +8647,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "event_type": { "type": "integer", @@ -8125,6 +8672,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "message_id", "type": "messageId", "required": true, + "role": "message_id", "schema": { "type": "integer", "not": { @@ -8159,7 +8707,8 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "not": { "const": 0 - } + }, + "x-role": "message_id" }, "emoji_id": { "type": "string", @@ -8254,6 +8803,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file", "type": "string", "required": true, + "role": "image", "schema": { "type": "string", "minLength": 1 @@ -8266,7 +8816,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "image" } }, "required": [ @@ -8373,6 +8924,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8385,7 +8937,8 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "required": [ @@ -8418,6 +8971,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -8427,6 +8981,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8448,11 +9003,13 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "phone_number": { "type": "string", @@ -8463,6 +9020,39 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "test_download_stream", + "aliases": [], + "summary": "测试下载流(推送 10 个数据帧,验证流式传输,不触达 QQ)", + "returns": "流式帧:data_chunk*10 → data_complete(error=true 时以 error 帧结束)", + "readOnly": false, + "params": [ + { + "name": "error", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false, + "desc": "是否触发测试错误" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "error": { + "type": "boolean", + "description": "是否触发测试错误", + "default": false + } + }, + "additionalProperties": true + }, + "stream": true, + "category": "流式接口" + }, { "name": "trans_group_file", "aliases": [], @@ -8536,6 +9126,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "target_uin", "type": "uint", "required": false, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -8551,7 +9142,8 @@ export const ACTIONS: CatalogAction[] = [ "minimum": 0 }, "desc": "说说发表时间(unix 秒),传真实值更可靠", - "default": 0 + "default": 0, + "role": "timestamp" } ], "invariants": [], @@ -8566,13 +9158,15 @@ export const ACTIONS: CatalogAction[] = [ "target_uin": { "type": "integer", "minimum": 1, - "description": "说说所属 QQ 号,省略则为机器人自己" + "description": "说说所属 QQ 号,省略则为机器人自己", + "x-role": "user_id" }, "abstime": { "type": "integer", "minimum": 0, "description": "说说发表时间(unix 秒),传真实值更可靠", - "default": 0 + "default": 0, + "x-role": "timestamp" } }, "required": [ @@ -8582,6 +9176,182 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "空间" }, + { + "name": "upload_file_stream", + "aliases": [], + "summary": "以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)", + "returns": "流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_size/sha256)", + "readOnly": false, + "params": [ + { + "name": "stream_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + }, + "desc": "流 ID(客户端生成的 UUID,限 [A-Za-z0-9_-])" + }, + { + "name": "chunk_data", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "分块数据(Base64)" + }, + { + "name": "chunk_index", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "desc": "分块索引(从 0 开始)" + }, + { + "name": "total_chunks", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "总分块数(新流必填)" + }, + { + "name": "file_size", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "desc": "文件总大小(字节)" + }, + { + "name": "expected_sha256", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "期望的整文件 SHA256(校验)" + }, + { + "name": "is_complete", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "desc": "是否为最后一个分块/触发合并" + }, + { + "name": "filename", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "desc": "文件名" + }, + { + "name": "reset", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "desc": "重置并丢弃该流" + }, + { + "name": "verify_only", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "desc": "仅查询当前流状态" + }, + { + "name": "file_retention", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 300000, + "desc": "合并文件保留毫秒(0=不回收)" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "stream_id": { + "type": "string", + "minLength": 1, + "description": "流 ID(客户端生成的 UUID,限 [A-Za-z0-9_-])" + }, + "chunk_data": { + "type": "string", + "description": "分块数据(Base64)" + }, + "chunk_index": { + "type": "integer", + "minimum": 0, + "description": "分块索引(从 0 开始)" + }, + "total_chunks": { + "type": "integer", + "minimum": 1, + "description": "总分块数(新流必填)" + }, + "file_size": { + "type": "integer", + "minimum": 0, + "description": "文件总大小(字节)" + }, + "expected_sha256": { + "type": "string", + "description": "期望的整文件 SHA256(校验)" + }, + "is_complete": { + "type": "boolean", + "description": "是否为最后一个分块/触发合并" + }, + "filename": { + "type": "string", + "description": "文件名" + }, + "reset": { + "type": "boolean", + "description": "重置并丢弃该流" + }, + "verify_only": { + "type": "boolean", + "description": "仅查询当前流状态" + }, + "file_retention": { + "type": "integer", + "minimum": 0, + "description": "合并文件保留毫秒(0=不回收)", + "default": 300000 + } + }, + "required": [ + "stream_id" + ], + "additionalProperties": true + }, + "stream": true, + "category": "流式接口" + }, { "name": "upload_forward_msg", "aliases": [], @@ -8608,6 +9378,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8626,7 +9397,8 @@ export const ACTIONS: CatalogAction[] = [ }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "additionalProperties": true @@ -8659,6 +9431,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": false, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8677,7 +9450,8 @@ export const ACTIONS: CatalogAction[] = [ }, "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" } }, "additionalProperties": true @@ -8695,6 +9469,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8705,6 +9480,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file", "type": "string", "required": true, + "role": "file", "schema": { "type": "string", "minLength": 1 @@ -8754,11 +9530,13 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file" }, "name": { "type": "string", @@ -8794,6 +9572,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -8822,6 +9601,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file", "type": "string", "required": true, + "role": "image", "schema": { "type": "string", "minLength": 1 @@ -8835,7 +9615,8 @@ export const ACTIONS: CatalogAction[] = [ "group_id": { "type": "integer", "minimum": 1, - "description": "群号" + "description": "群号", + "x-role": "group_id" }, "album_id": { "type": "string", @@ -8847,7 +9628,8 @@ export const ACTIONS: CatalogAction[] = [ }, "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "image" } }, "required": [ @@ -8871,6 +9653,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "user_id", "type": "uint", "required": true, + "role": "user_id", "schema": { "type": "integer", "minimum": 1 @@ -8880,6 +9663,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file", "type": "string", "required": true, + "role": "file", "schema": { "type": "string", "minLength": 1 @@ -8910,11 +9694,13 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "user_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "user_id" }, "file": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file" }, "name": { "type": "string", @@ -8975,5 +9761,9 @@ export const CATEGORIES: CatalogCategory[] = [ { "category": "空间", "count": 7 + }, + { + "category": "流式接口", + "count": 6 } ]; diff --git a/packages/mcp/src/types.ts b/packages/mcp/src/types.ts index 96b2c9da..ed431e5b 100644 --- a/packages/mcp/src/types.ts +++ b/packages/mcp/src/types.ts @@ -11,6 +11,11 @@ export interface CatalogParam { default?: unknown; desc?: string; values?: ReadonlyArray; + /** Semantic role (group_id / user_id / member_id / image / face_id / …), + * orthogonal to `type`; drives smart-widget selection in the WebUI console. + * Kept as a loose string here so the package stays decoupled from onebot's + * FieldRole union. */ + role?: string; /** JSON Schema fragment for this single field. */ schema?: Record; } @@ -27,6 +32,9 @@ export interface CatalogAction { * read/write tool routing: read-only → query_action, else → invoke_action. * Classified at the source spec by what the action's `run` actually does. */ readOnly: boolean; + /** True for Stream API actions (multi-frame transport). Absent ⇒ ordinary + * single-response action. */ + stream?: boolean; params: CatalogParam[]; /** Cross-field invariants, e.g. "exactly one of: message_id | (group_id+user_id)". */ invariants: string[]; diff --git a/packages/onebot/package.json b/packages/onebot/package.json index ae54f5bf..aba2fc1c 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/onebot", - "version": "1.10.4", + "version": "1.11.0", "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/'`.", diff --git a/packages/onebot/src/action-docs.ts b/packages/onebot/src/action-docs.ts index 640da92a..e55a385e 100644 --- a/packages/onebot/src/action-docs.ts +++ b/packages/onebot/src/action-docs.ts @@ -12,7 +12,7 @@ // deferred product decision; this module produces format-agnostic data plus a // Markdown default. Point any renderer at `collectActionDocs()`. -import type { ActionDoc, ActionSpec, Field } from './action-kit'; +import type { ActionDoc } from './action-kit'; import { actions as infoActions } from './actions/info'; import { actions as messageActions } from './actions/message'; import { actions as friendActions } from './actions/friend'; @@ -23,8 +23,13 @@ import { actions as requestActions } from './actions/request'; import { actions as extendedActions } from './actions/extended'; import { actions as groupAlbumActions } from './actions/group-album'; import { actions as qzoneActions } from './actions/qzone'; +import { actions as streamFileActions } from './actions/stream-file'; +import { actions as streamDownloadActions } from './actions/stream-download'; -type AnySpec = ActionSpec>>; +// The doc collector only ever calls `describe()`, so any spec carrying it +// qualifies — this admits both `defineAction` (ActionSpec) and +// `defineStreamAction` (StreamActionSpec) results without coupling to either. +type AnySpec = { describe(): ActionDoc }; // Source file = domain category. Each doc is tagged so the MCP / UI can group. const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [ @@ -38,6 +43,7 @@ const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [ { category: '扩展', specs: extendedActions }, { category: '群相册', specs: groupAlbumActions }, { category: '空间', specs: qzoneActions }, + { category: '流式接口', specs: [...streamFileActions, ...streamDownloadActions] }, ]; /** Every declarative action's doc (with category), sorted by name. */ diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts index 7bd506b7..ff07281b 100644 --- a/packages/onebot/src/action-kit.ts +++ b/packages/onebot/src/action-kit.ts @@ -21,6 +21,7 @@ import { RETCODE, failedResponse } from './types'; import type { ApiResponse, JsonObject, JsonValue } from './types'; import type { ApiActionContext, ApiHandler } from './api-handler'; +import { type StreamSink, NOOP_SINK } from './streaming'; // ─────────────────────────── result currency ─────────────────────────── @@ -43,12 +44,33 @@ type Raw = JsonValue | typeof MISSING; * them into an action's `inputSchema` (consumed by docs / the MCP). */ export type JsonSchema = Record; +/** Semantic role of a param, orthogonal to `type` (which governs coercion). + * Two `uint` fields `group_id` and `user_id` coerce identically but mean + * different things — `role` is what a UI keys its picker/widget off of. + * Closed set: consumers (the WebUI debug console) switch on it exhaustively + * and fall back to the plain typed control for anything unrecognised. */ +export type FieldRole = + | 'group_id' + | 'user_id' + | 'member_id' // a group member's uin — its picker depends on a sibling group_id + | 'message_id' + | 'file_id' + | 'file' + | 'image' + | 'record' + | 'video' + | 'duration' + | 'timestamp' + | 'face_id'; + export interface FieldDoc { type: string; required: boolean; default?: JsonValue; desc?: string; values?: readonly (string | number)[]; + /** Semantic role driving UI widget selection; orthogonal to `type`. */ + role?: FieldRole; /** JSON Schema fragment for this field's value (constraints only; presence * and default are applied at the object level by `describe()`). */ schema?: JsonSchema; @@ -64,6 +86,10 @@ export interface Field { * numeric field is an error, not a silent fallback). */ default(value: T): Field; describe(text: string): Field; + /** Stamp a semantic role (escape hatch for params whose name lies, or to + * override a preset). Most call sites use the `f.groupId()`-style semantic + * constructors instead. */ + role(role: FieldRole): Field; /** Complete JSON Schema for this field's value (constraints + description + * default). Object-level required-ness is handled by `describe()`. */ toJsonSchema(): JsonSchema; @@ -103,10 +129,15 @@ class FieldImpl implements Field { return new FieldImpl(this.core, { ...this.doc, desc: text }); } + role(role: FieldRole): Field { + return new FieldImpl(this.core, { ...this.doc, role }); + } + toJsonSchema(): JsonSchema { const out: JsonSchema = { ...(this.doc.schema ?? {}) }; if (this.doc.desc) out.description = this.doc.desc; if (this.doc.default !== undefined) out.default = this.doc.default; + if (this.doc.role) out['x-role'] = this.doc.role; return out; } } @@ -147,6 +178,21 @@ function strSchema(opts: StrOpts): JsonSchema { return s; } +/** Coerce to string (numbers/booleans stringify; matches legacy `asString`), + * then apply emptiness / length bounds. Shared by `f.string()` and the + * string-valued semantic constructors. */ +function stringCore(opts: StrOpts): Core { + return (raw, field) => { + let s: string; + if (typeof raw === 'string') s = raw; + else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw); + else return err(field, 'expected a string'); + if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty'); + if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`); + return ok(s); + }; +} + function arrayField(el: Field, mustBeNonEmpty: boolean): Field & { nonEmpty(): Field } { const core: Core = (raw, field) => { if (!Array.isArray(raw)) return err(field, 'expected an array'); @@ -180,7 +226,59 @@ export const f = { /** OneBot message id: a non-zero integer. NEGATIVES ARE VALID (ids are a * signed int32 hash) — do NOT use `uint()` for message_id. */ messageId(): Field { - return new FieldImpl(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, schema: intSchema({ nonZero: true }) }); + return new FieldImpl(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, role: 'message_id', schema: intSchema({ nonZero: true }) }); + }, + // ── Semantic constructors (role-stamped) ── + // Each wraps a coercion primitive and stamps a `role` so the WebUI debug + // console renders the right picker. The Agent backfill replaces a bare + // `f.uint()` named `group_id` with `f.groupId()`, etc. — purely additive to + // coercion (a groupId still coerces exactly like a uint). + /** Group number (uint) → group picker. */ + groupId(): Field { + return new FieldImpl(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'group_id', schema: intSchema({ min: 1 }) }); + }, + /** Friend / stranger uin (uint) → friend picker. */ + userId(): Field { + return new FieldImpl(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'user_id', schema: intSchema({ min: 1 }) }); + }, + /** Group member's uin (uint) → member picker, linked to a sibling group_id. */ + memberId(): Field { + return new FieldImpl(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'member_id', schema: intSchema({ min: 1 }) }); + }, + /** Opaque file id (string) → file picker / history. */ + fileId(): Field { + return new FieldImpl(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'file_id', schema: strSchema({ allowEmpty: false }) }); + }, + // Media sources reject '' (an empty path/URL is meaningless) — this matches + // the `f.string({ allowEmpty: false })` they replace during backfill, so the + // swap preserves the empty-string guard. + /** Local path / URL / base64 of a generic file → FileSource control. */ + file(): Field { + return new FieldImpl(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'file', schema: strSchema({ allowEmpty: false }) }); + }, + /** Image source (path / URL / base64) → FileSource control. */ + image(): Field { + return new FieldImpl(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'image', schema: strSchema({ allowEmpty: false }) }); + }, + /** Voice/record source → FileSource control. */ + record(): Field { + return new FieldImpl(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'record', schema: strSchema({ allowEmpty: false }) }); + }, + /** Video source → FileSource control. */ + video(): Field { + return new FieldImpl(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'video', schema: strSchema({ allowEmpty: false }) }); + }, + /** Seconds (int ≥ 0) → duration control. */ + duration(): Field { + return new FieldImpl(intCore('an integer', { min: 0 }), { type: 'int', required: true, role: 'duration', schema: intSchema({ min: 0 }) }); + }, + /** Unix timestamp (int ≥ 0) → datetime control. */ + timestamp(): Field { + return new FieldImpl(intCore('an integer', { min: 0 }), { type: 'int', required: true, role: 'timestamp', schema: intSchema({ min: 0 }) }); + }, + /** QQ face id (non-negative int; face 0 is valid) → face grid. */ + faceId(): Field { + return new FieldImpl(intCore('a non-negative integer', { min: 0 }), { type: 'int', required: true, role: 'face_id', schema: intSchema({ min: 0 }) }); }, /** Finite number (fractions allowed). */ number(): Field { @@ -193,15 +291,7 @@ export const f = { /** String. Numbers/booleans stringify (matches legacy `asString`). Empty * allowed by default; `{ allowEmpty: false }` rejects ''. */ string(opts: StrOpts = {}): Field { - return new FieldImpl((raw, field) => { - let s: string; - if (typeof raw === 'string') s = raw; - else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw); - else return err(field, 'expected a string'); - if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty'); - if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`); - return ok(s); - }, { type: 'string', required: true, schema: strSchema(opts) }); + return new FieldImpl(stringCore(opts), { type: 'string', required: true, schema: strSchema(opts) }); }, /** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */ bool(): Field { @@ -338,6 +428,10 @@ export interface ActionDoc { /** True only for pure data-fetch actions (no side effects). Drives the MCP's * read/write tool routing; defaults to false (treated as a write). */ readOnly: boolean; + /** True for Stream API actions (`defineStreamAction`) — they push multiple + * frames through a sink, so a caller must use the streaming transport rather + * than a single request/response. Absent ⇒ ordinary single-response action. */ + stream?: boolean; params: ParamDoc[]; invariants: string[]; /** Composed JSON Schema for the whole params object (properties + required). */ @@ -445,6 +539,63 @@ export function defineAction(def: ActionDef): ActionSpec { }; } +// ─────────────────────────── defineStreamAction ─────────────────────────── +// A Stream API action (#163): same param contract + doc machinery as +// `defineAction`, but `run` additionally receives a `StreamSink` to push +// intermediate frames, and it registers via `registerStreamAction` so the +// network adapter streams its output. The handler's return value is still the +// terminal `ApiResponse` (the final frame). Reuses `defineAction` for +// parse/describe so the two stay in lock-step. + +interface StreamActionDef { + name: string | readonly [string, ...string[]]; + summary?: string; + returns?: string; + returnsSchema?: JsonSchema; + readOnly?: boolean; + params: S; + rules?: (r: RuleBuilders>) => readonly CrossFieldRule[]; + run: (p: InferParams, ctx: ApiActionContext, raw: JsonObject, sink: StreamSink) => Promise | ApiResponse; +} + +export interface StreamActionSpec { + readonly names: string[]; + readonly params: S; + parse(raw: JsonObject): CoerceResult>; + describe(): ActionDoc; + register(h: ApiHandler, ctx: ApiActionContext): void; +} + +export function defineStreamAction(def: StreamActionDef): StreamActionSpec { + // Borrow defineAction's parse + describe (run is never invoked — register + // below installs the sink-aware handler instead). + const base = defineAction({ + name: def.name, + summary: def.summary, + returns: def.returns, + returnsSchema: def.returnsSchema, + readOnly: def.readOnly, + params: def.params, + rules: def.rules, + run: () => failedResponse(RETCODE.INTERNAL_ERROR, 'stream action dispatched without a sink'), + }); + + return { + names: base.names, + params: def.params, + parse: base.parse, + describe: () => ({ ...base.describe(), stream: true }), + register: (h, ctx) => { + const handler = async (params: JsonObject, sink?: StreamSink): Promise => { + const r = base.parse(params); + if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r)); + return def.run(r.value, ctx, params, sink ?? NOOP_SINK); + }; + for (const name of base.names) h.registerStreamAction(name, handler); + }, + }; +} + // ─────────────────────────── presets ─────────────────────────── // `group_id` appears in 61/142 actions, `user_id` in 27 — these collapse the // dominant shape. The injected fields are surfaced in `describe()` so docs @@ -466,7 +617,7 @@ interface PresetDef { /** Pre-seeds `group_id` (uint, required). */ export function groupAction(def: PresetDef): ActionSpec> { - const params = { group_id: f.uint().describe('群号'), ...(def.params ?? {}) } as WithGroup; + const params = { group_id: f.groupId().describe('群号'), ...(def.params ?? {}) } as WithGroup; return defineAction({ ...def, params } as unknown as ActionDef>); } @@ -475,8 +626,10 @@ export function groupUserAction( def: PresetDef, ): ActionSpec> { const params = { - group_id: f.uint().describe('群号'), - user_id: f.uint().describe('QQ 号'), + group_id: f.groupId().describe('群号'), + // In a group action, the user_id is a member of *that* group — so its + // picker links to the sibling group_id (member_id role, not user_id). + user_id: f.memberId().describe('QQ 号'), ...(def.params ?? {}), } as WithGroupUser; return defineAction({ ...def, params } as unknown as ActionDef>); diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 56b06ce6..95e8b114 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -141,7 +141,7 @@ export const actions = [ name: 'send_like', summary: '点赞', params: { - user_id: f.uint(), + user_id: f.userId(), // 原实现用 `asNumber(times) || 1`,present 0 会被当作缺省 1。 times: f.int({ min: 0 }).default(1), }, @@ -155,8 +155,8 @@ export const actions = [ name: 'friend_poke', summary: '好友拍一拍', params: { - user_id: f.uint(), - target_id: f.uint().optional(), + user_id: f.userId(), + target_id: f.userId().optional(), }, run: async (p, ctx) => { await ctx.bridge.apis.interaction.sendPoke(false, p.user_id, p.target_id); @@ -177,8 +177,8 @@ export const actions = [ name: 'send_poke', summary: '拍一拍(群聊/私聊自动路由)', params: { - user_id: f.uint(), - group_id: f.uint().optional(), + user_id: f.userId(), + group_id: f.groupId().optional(), }, run: async (p, ctx) => { if (p.group_id) { @@ -233,7 +233,7 @@ export const actions = [ name: 'set_group_reaction', summary: '群聊表情回应', params: { - group_id: f.uint().optional(), + group_id: f.groupId().optional(), message_id: f.messageId(), code: f.string({ allowEmpty: false }), is_set: f.bool().default(true), @@ -272,7 +272,7 @@ export const actions = [ defineAction({ name: 'add_custom_face', summary: '添加收藏表情', - params: { file: f.string({ allowEmpty: false }) }, + params: { file: f.image() }, run: async (p, ctx) => { try { const emojiId = await ctx.bridge.apis.profile.addCustomFace(p.file); @@ -339,7 +339,7 @@ export const actions = [ // param-validation time (retcode 1400) before run() ever fires. Use a // plain signed int; `.default(0)` keeps absent/present-0 → "fetch latest" // (matches the original `asNumber(message_id) || 0`). `count` stays ≥0. - message_id: f.int().default(0), + message_id: f.int().default(0).role('message_id'), count: f.int({ min: 0 }).default(20), }, run: async (p, ctx) => { @@ -361,9 +361,9 @@ export const actions = [ required: ['messages'], }, params: { - user_id: f.uint(), + user_id: f.userId(), // Signed int32 hash, frequently negative — see get_group_msg_history. - message_id: f.int().default(0), + message_id: f.int().default(0).role('message_id'), count: f.int({ min: 0 }).default(20), }, run: async (p, ctx) => { @@ -378,7 +378,7 @@ export const actions = [ summary: '标记群消息已读', params: { message_id: f.messageId(), - group_id: f.uint().optional(), + group_id: f.groupId().optional(), }, run: async (p, ctx) => { const meta = ctx.getMessageMeta(p.message_id); @@ -400,7 +400,7 @@ export const actions = [ summary: '标记私聊消息已读', params: { message_id: f.messageId(), - user_id: f.uint().optional(), + user_id: f.userId().optional(), }, run: async (p, ctx) => { const meta = ctx.getMessageMeta(p.message_id); @@ -447,7 +447,7 @@ export const actions = [ summary: '发送群公告', params: { content: f.string({ allowEmpty: false }), - image: f.string().default(''), + image: f.string().default('').role('image'), pinned: f.raw(), type: f.raw(), confirm_required: f.raw(), @@ -490,7 +490,7 @@ export const actions = [ params: { messages: f.message().optional(), message: f.message().optional(), - group_id: f.uint().optional(), + group_id: f.groupId().optional(), }, run: async (p, ctx) => { const messages = p.messages ?? p.message; @@ -514,7 +514,7 @@ export const actions = [ params: { messages: f.message().optional(), message: f.message().optional(), - group_id: f.uint().optional(), + group_id: f.groupId().optional(), }, run: async (p, ctx) => { const messages = p.messages ?? p.message; @@ -531,8 +531,8 @@ export const actions = [ summary: '获取图片信息', readOnly: true, params: { - file: f.string().default(''), - file_id: f.string().default(''), + file: f.string().default('').role('image'), + file_id: f.string().default('').role('file_id'), }, run: async (p, ctx) => { const file = p.file || p.file_id; @@ -545,18 +545,32 @@ export const actions = [ defineAction({ name: 'get_record', - summary: '获取语音信息', + summary: '获取语音信息;传 out_format 则服务端转码并附带 base64', readOnly: true, params: { - file: f.string().default(''), - file_id: f.string().default(''), + file: f.string().default('').role('record'), + file_id: f.string().default('').role('file_id'), + // Optional server-side transcode (#165): SILK/AMR → the requested + // container, returned as `data.base64`. Absent ⇒ behaviour unchanged. + out_format: f.enum('mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac').optional(), }, run: async (p, ctx) => { const file = p.file || p.file_id; if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); const info = await ctx.getRecordInfo(file); - if (info) return okResponse(info); - return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache'); + if (!info) return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache'); + if (!p.out_format) return okResponse(info); + // Transcode from the record's download URL (fall back to file field). + const source = String(info.url || info.file || ''); + if (!source) return failedResponse(RETCODE.ACTION_FAILED, 'record has no downloadable source'); + try { + // Keep the original record info (file_size stays the source size, like + // NapCat) and just attach the transcoded payload. + const { base64 } = await ctx.bridge.apis.extras.convertRecord(source, p.out_format); + return okResponse({ ...info, out_format: p.out_format, base64 }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, `语音转码失败:${e instanceof Error ? e.message : String(e)}`); + } }, }), @@ -574,7 +588,7 @@ export const actions = [ required: ['text'], }, params: { - message_id: f.string().default(''), + message_id: f.string().default('').role('message_id'), }, // `raw` so message_id works whether the client sends a number or a string. run: async (_p, ctx, raw) => { @@ -684,7 +698,7 @@ export const actions = [ name: 'set_friend_remark', summary: '设置好友备注', params: { - user_id: f.uint(), + user_id: f.userId(), remark: f.string(), }, run: async (p, ctx) => { @@ -697,7 +711,7 @@ export const actions = [ name: 'set_group_remark', summary: '设置群备注', params: { - group_id: f.uint(), + group_id: f.groupId(), remark: f.string(), }, run: async (p, ctx) => { @@ -822,7 +836,7 @@ export const actions = [ name: 'set_diy_online_status', summary: '设置自定义在线状态', params: { - face_id: f.uint(), + face_id: f.faceId(), // 原实现用 `asNumber(face_type) || 1`,present 0 会被当作缺省 1。 face_type: f.int({ min: 0 }).default(1), wording: f.string().default(''), @@ -979,7 +993,7 @@ export const actions = [ summary: '转发单条消息给好友', params: { message_id: f.messageId(), - user_id: f.uint(), + user_id: f.userId(), }, run: async (p, ctx) => { try { @@ -996,7 +1010,7 @@ export const actions = [ summary: '转发单条消息到群', params: { message_id: f.messageId(), - group_id: f.uint(), + group_id: f.groupId(), }, run: async (p, ctx) => { try { @@ -1044,7 +1058,7 @@ export const actions = [ }, params: { // 原实现 user_id 经 asNumber,无校验(0 也透传)。 - user_id: f.int({ min: 0 }).default(0), + user_id: f.int({ min: 0 }).default(0).role('user_id'), start: f.int({ min: 0 }).default(0), count: f.int({ min: 0 }).default(10), }, @@ -1367,8 +1381,8 @@ export const actions = [ required: ['arkMsg'], }, params: { - user_id: f.uint().optional(), - group_id: f.uint().optional(), + user_id: f.userId().optional(), + group_id: f.groupId().optional(), phone_number: f.string().default(''), }, run: async (p, ctx) => { @@ -1398,8 +1412,8 @@ export const actions = [ required: ['arkMsg'], }, params: { - user_id: f.uint().optional(), - group_id: f.uint().optional(), + user_id: f.userId().optional(), + group_id: f.groupId().optional(), phone_number: f.string().default(''), }, run: async (p, ctx) => { @@ -1427,7 +1441,7 @@ export const actions = [ readOnly: true, returns: '服务端生成的群推荐 Ark 卡片 JSON 字符串。', returnsSchema: { type: 'string', description: '群 Ark 卡片 JSON 字符串' }, - params: { group_id: f.uint() }, + params: { group_id: f.groupId() }, run: async (p, ctx) => { try { return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id)); @@ -1442,7 +1456,7 @@ export const actions = [ readOnly: true, returns: '服务端生成的群推荐 Ark 卡片 JSON 字符串。', returnsSchema: { type: 'string', description: '群 Ark 卡片 JSON 字符串' }, - params: { group_id: f.uint() }, + params: { group_id: f.groupId() }, run: async (p, ctx) => { try { return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id)); @@ -1565,7 +1579,7 @@ export const actions = [ defineAction({ name: 'set_qq_avatar', summary: '设置 QQ 头像', - params: { file: f.string({ allowEmpty: false }) }, + params: { file: f.image() }, run: async (p, ctx) => { try { await ctx.bridge.apis.profile.setAvatar(p.file); @@ -1580,7 +1594,7 @@ export const actions = [ name: 'set_input_status', summary: '设置输入状态', params: { - user_id: f.uint(), + user_id: f.userId(), // event_type 可能为 0(取消输入状态);缺省也按 0 处理(与旧 asNumber 行为一致)。 event_type: f.int().default(0), }, @@ -1598,7 +1612,7 @@ export const actions = [ name: 'get_group_info_ex', summary: '获取群信息(扩展)', readOnly: true, - params: { group_id: f.uint() }, + params: { group_id: f.groupId() }, run: async (p, ctx) => { if (ctx.getGroupInfo) { return okResponse(await ctx.getGroupInfo(p.group_id)); @@ -1611,7 +1625,7 @@ export const actions = [ name: 'get_group_detail_info', summary: '获取群详细信息', readOnly: true, - params: { group_id: f.uint() }, + params: { group_id: f.groupId() }, run: async (p, ctx) => { if (ctx.getGroupInfo) { return okResponse(await ctx.getGroupInfo(p.group_id)); @@ -1644,8 +1658,8 @@ export const actions = [ summary: '获取文件信息(仅图片/语音缓存;群文件请用 get_group_file_url)', readOnly: true, params: { - file_id: f.string().default(''), - file: f.string().default(''), + file_id: f.string().default('').role('file_id'), + file: f.string().default('').role('file'), }, run: async (p, ctx) => { const fileId = p.file || p.file_id; @@ -1712,7 +1726,7 @@ export const actions = [ }, required: ['status', 'ext_status'], }, - params: { user_id: f.uint() }, + params: { user_id: f.userId() }, run: async (p, ctx) => { const status = await ctx.bridge.apis.extras.getStrangerStatus(p.user_id); if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status'); @@ -1934,7 +1948,7 @@ export const actions = [ }, required: ['texts', 'language'], }, - params: { image: f.string({ allowEmpty: false }) }, + params: { image: f.image() }, run: async (p, ctx) => { // A passed-in http(s) URL is used verbatim (NOT re-signed) — if it is a // stale CDN URL with an expired rkey the server fetch fails and surfaces @@ -2022,7 +2036,7 @@ export const actions = [ name: 'send_private_forward_msg', summary: '发送私聊合并转发', returns: '{ message_id, res_id, forward_id }', - params: { user_id: f.uint(), messages: f.message().optional(), message: f.message().optional() }, + params: { user_id: f.userId(), messages: f.message().optional(), message: f.message().optional() }, run: async (p, ctx, raw) => { const messages = p.messages ?? p.message; if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); @@ -2407,8 +2421,8 @@ export const actions = [ returns: '{ message_id }', params: { fileset_id: f.string({ allowEmpty: false }), - user_id: f.uint().optional(), - group_id: f.uint().optional(), + user_id: f.userId().optional(), + group_id: f.groupId().optional(), }, run: async (p, ctx) => { if (!p.user_id && !p.group_id) { diff --git a/packages/onebot/src/actions/friend.ts b/packages/onebot/src/actions/friend.ts index cbf878ff..49bb4fb2 100644 --- a/packages/onebot/src/actions/friend.ts +++ b/packages/onebot/src/actions/friend.ts @@ -46,7 +46,7 @@ export const actions = [ }, required: ['user_id', 'nickname', 'sex', 'age'], }, - params: { user_id: f.uint().describe('QQ 号') }, + params: { user_id: f.userId().describe('QQ 号') }, run: async (p, ctx) => { const userId = p.user_id; if (ctx.getStrangerInfo) { @@ -60,7 +60,7 @@ export const actions = [ defineAction({ name: 'delete_friend', summary: '删除好友', - params: { user_id: f.uint().describe('QQ 号'), block: f.bool().default(false) }, + params: { user_id: f.userId().describe('QQ 号'), block: f.bool().default(false) }, run: async (p, ctx) => { await ctx.bridge.apis.friend.delete(p.user_id, p.block); return okResponse(); diff --git a/packages/onebot/src/actions/group-admin.ts b/packages/onebot/src/actions/group-admin.ts index 19441311..ab91f520 100644 --- a/packages/onebot/src/actions/group-admin.ts +++ b/packages/onebot/src/actions/group-admin.ts @@ -16,7 +16,7 @@ export const actions = [ groupAction({ name: 'set_group_kick_members', summary: '批量踢出群成员', - params: { user_id: f.array(f.uint()).nonEmpty(), reject_add_request: f.bool().default(false) }, + params: { user_id: f.array(f.memberId()).nonEmpty(), reject_add_request: f.bool().default(false) }, run: async (p, ctx) => { await ctx.bridge.apis.groupAdmin.kickMembers(p.group_id, p.user_id, p.reject_add_request); return okResponse(); @@ -26,7 +26,7 @@ export const actions = [ groupUserAction({ name: 'set_group_ban', summary: '禁言群成员(duration=0 解除)', - params: { duration: f.int({ min: 0 }).default(1800) }, + params: { duration: f.duration().default(1800) }, run: async (p, ctx) => { await ctx.bridge.apis.groupAdmin.muteMember(p.group_id, p.user_id, p.duration); return okResponse(); @@ -118,7 +118,7 @@ export const actions = [ groupAction({ name: 'set_group_portrait', summary: '设置群头像', - params: { file: f.string({ allowEmpty: false }) }, + params: { file: f.image() }, run: async (p, ctx) => { try { await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file); diff --git a/packages/onebot/src/actions/group-album.ts b/packages/onebot/src/actions/group-album.ts index df022179..8698fe7b 100644 --- a/packages/onebot/src/actions/group-album.ts +++ b/packages/onebot/src/actions/group-album.ts @@ -91,7 +91,7 @@ export const actions = [ params: { album_id: f.string({ allowEmpty: false }), album_name: f.string({ allowEmpty: false }), - file: f.string({ allowEmpty: false }), + file: f.image(), }, run: async (p, ctx) => { try { diff --git a/packages/onebot/src/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts index fab90184..434b2df6 100644 --- a/packages/onebot/src/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -26,7 +26,7 @@ export const actions = [ // non-empty wins, else '/'. Both default '' so the `||` chain matches the // legacy `asString(folder) || asString(folder_id) || '/'`. params: { - file: f.string({ allowEmpty: false }), + file: f.file(), name: f.string().default(''), folder: f.string().default(''), folder_id: f.string().default(''), @@ -44,8 +44,8 @@ export const actions = [ summary: '上传私聊文件', returns: '{ file_id: string }', params: { - user_id: f.uint(), - file: f.string({ allowEmpty: false }), + user_id: f.userId(), + file: f.file(), name: f.string().default(''), upload_file: f.bool().default(true), }, @@ -67,7 +67,7 @@ export const actions = [ }, // busid is accepted but tolerant (see busidOr102): NapCat/LLBot ignore it, // so a present null/empty/non-numeric value must not 400 the request (#147). - params: { file_id: f.string({ allowEmpty: false }), busid: f.raw() }, + params: { file_id: f.fileId(), busid: f.raw() }, run: async (p, ctx) => { return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(p.group_id, p.file_id, busidOr102(p.busid)) }); }, @@ -183,7 +183,7 @@ export const actions = [ groupAction({ name: 'delete_group_file', summary: '删除群文件', - params: { file_id: f.string({ allowEmpty: false }) }, + params: { file_id: f.fileId() }, run: async (p, ctx) => { await ctx.bridge.apis.groupFile.delete(p.group_id, p.file_id); return okResponse(); @@ -194,7 +194,7 @@ export const actions = [ name: 'move_group_file', summary: '移动群文件', params: { - file_id: f.string({ allowEmpty: false }), + file_id: f.fileId(), parent_directory: f.string({ allowEmpty: false }), target_directory: f.string({ allowEmpty: false }), }, @@ -210,7 +210,7 @@ export const actions = [ name: 'rename_group_file', summary: '重命名群文件', params: { - file_id: f.string({ allowEmpty: false }), + file_id: f.fileId(), current_parent_directory: f.string().default('/'), new_name: f.string({ allowEmpty: false }), }, @@ -276,8 +276,8 @@ export const actions = [ // clients that only persist file_id, both user_id and file_hash are now // optional; file_hash falls through empty when absent. See issue #147. params: { - user_id: f.uint().optional(), - file_id: f.string({ allowEmpty: false }), + user_id: f.userId().optional(), + file_id: f.fileId(), file_hash: f.string().default(''), }, run: async (p, ctx) => { diff --git a/packages/onebot/src/actions/message.ts b/packages/onebot/src/actions/message.ts index eedf7b48..dfa589eb 100644 --- a/packages/onebot/src/actions/message.ts +++ b/packages/onebot/src/actions/message.ts @@ -47,8 +47,8 @@ export const actions = [ params: { message: f.message(), message_type: f.string().optional(), - group_id: f.uint().optional(), - user_id: f.uint().optional(), + group_id: f.groupId().optional(), + user_id: f.userId().optional(), auto_escape: f.bool().default(false), }, run: async (p, ctx) => { @@ -67,7 +67,7 @@ export const actions = [ name: 'send_private_msg', summary: '发送私聊消息', returns: '{ message_id: number }', - params: { user_id: f.uint(), message: f.message(), auto_escape: f.bool().default(false) }, + params: { user_id: f.userId(), message: f.message(), auto_escape: f.bool().default(false) }, run: async (p, ctx) => { const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape); return okResponse({ message_id: result.messageId }); diff --git a/packages/onebot/src/actions/qzone.ts b/packages/onebot/src/actions/qzone.ts index 92b77812..3650d022 100644 --- a/packages/onebot/src/actions/qzone.ts +++ b/packages/onebot/src/actions/qzone.ts @@ -3,6 +3,24 @@ import type { ApiActionContext, ApiHandler } from '../api-handler'; import type { JsonValue } from '../types'; import { RETCODE, failedResponse, okResponse } from '../types'; +async function uploadQzoneImages( + ctx: ApiActionContext, + images: string[], + select: (upload: { richval: string; url: string }) => string, +): Promise { + const parts: string[] = []; + for (let i = 0; i < images.length; i++) { + try { + const upload = await ctx.bridge.apis.qzone.uploadImageFromSource(images[i]); + parts.push(select(upload)); + } catch (error) { + const message = error instanceof Error ? error.message : 'unknown error'; + throw new Error(`第 ${i + 1} 张图片上传失败: ${message}`); + } + } + return parts.join('\t'); +} + export const actions = [ // get_qzone_msg_list — 获取 QQ 空间说说列表。无 go-cqhttp 标准,自定义命名。 // 默认取机器人自己的空间;传 target_uin 可查看指定账号(需有权限)。 @@ -36,7 +54,7 @@ export const actions = [ }, summary: '获取 QQ 空间说说列表(默认机器人自己的空间)', params: { - target_uin: f.uint().describe('目标 QQ 号,省略则取机器人自己').optional(), + target_uin: f.userId().describe('目标 QQ 号,省略则取机器人自己').optional(), pos: f.int({ min: 0 }).describe('起始偏移').default(0), num: f.int({ min: 1, max: 100 }).describe('本页数量').default(20), }, @@ -96,17 +114,24 @@ export const actions = [ }, }), - // send_qzone_msg — 发表一条纯文字说说。写操作,发到机器人自己的空间。 + // send_qzone_msg — 发表说说(纯文字或带图)。写操作,发到机器人自己的空间。 + // 传入 images 数组,自动上传并发布。 // 返回新说说的 tid(供后续 delete/comment/like 使用)。 // 注意:发说说为主动行为,高频会被 Qzone 风控,调用方需自行限流。 defineAction({ name: 'send_qzone_msg', - summary: '发表一条纯文字说说(QQ 空间)', + summary: '发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)', params: { content: f.string({ allowEmpty: false }).describe('说说正文'), + images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(), }, run: async (p, ctx) => { try { + if (p.images && p.images.length > 0) { + const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.richval); + const res = await ctx.bridge.apis.qzone.publish(p.content, 1, richval); + return okResponse(res as unknown as JsonValue); + } const res = await ctx.bridge.apis.qzone.publish(p.content); return okResponse(res as unknown as JsonValue); } catch (error) { @@ -142,8 +167,8 @@ export const actions = [ summary: '给一条说说点赞(QQ 空间)', params: { tid: f.string({ allowEmpty: false }).describe('说说 tid'), - target_uin: f.uint().describe('说说所属 QQ 号,省略则为机器人自己').optional(), - abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0), + target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(), + abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0).role('timestamp'), }, run: async (p, ctx) => { try { @@ -163,8 +188,8 @@ export const actions = [ summary: '取消对一条说说的点赞(QQ 空间;取消赞端点待真机核实)', params: { tid: f.string({ allowEmpty: false }).describe('说说 tid'), - target_uin: f.uint().describe('说说所属 QQ 号,省略则为机器人自己').optional(), - abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0), + target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(), + abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0).role('timestamp'), }, run: async (p, ctx) => { try { @@ -178,17 +203,24 @@ export const actions = [ }), // comment_qzone — 评论一条说说。target_uin=说说所属 QQ 号(省略=机器人自己空间)。 + // 传入 images 数组,自动上传获取直链(多图用 tab 拼接)。 // 写操作;高频评论会被 Qzone 风控,调用方需限流。 defineAction({ name: 'comment_qzone', - summary: '评论一条说说(QQ 空间)', + summary: '评论一条说说(QQ 空间,支持纯文字或带图;传 images 自动上传)', params: { tid: f.string({ allowEmpty: false }).describe('说说 tid'), content: f.string({ allowEmpty: false }).describe('评论内容'), - target_uin: f.uint().describe('说说所属 QQ 号,省略则为机器人自己').optional(), + target_uin: f.userId().describe('说说所属 QQ 号,省略则为机器人自己').optional(), + images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(), }, run: async (p, ctx) => { try { + if (p.images && p.images.length > 0) { + const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.url); + const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin, 1, richval); + return okResponse(res as unknown as JsonValue); + } const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin); return okResponse(res as unknown as JsonValue); } catch (error) { diff --git a/packages/onebot/src/actions/stream-download.ts b/packages/onebot/src/actions/stream-download.ts new file mode 100644 index 00000000..d9ff1fcb --- /dev/null +++ b/packages/onebot/src/actions/stream-download.ts @@ -0,0 +1,378 @@ +// Stream API download actions (#163) — NapCat-compatible server-push streaming. +// +// download_file_stream / _image_stream / _record_stream answer one request with +// many frames: a `file_info` header, then N `file_chunk` frames (base64), then a +// terminal `file_complete`. The bytes come from one of three sources, resolved +// from the `file` arg: +// • a local file UNDER the stream temp root (e.g. something a client just +// pushed via upload_file_stream) — streamed straight off disk; +// • an http(s) URL — fetched and re-streamed; +// • a cached image/voice id from a received message — resolved to its QQ CDN +// URL, then fetched. +// test_download_stream pushes 10 canned frames so a client can verify the +// streaming transport without touching QQ. +// +// Hardening beyond the NapCat original (which streams ANY local path and +// fetches ANY URL): local reads are fenced inside the stream temp root (no +// arbitrary-file read via a leaked token), and URL fetches are SSRF-guarded +// (no private/loopback/link-local targets) + size-capped. + +import fs from 'fs'; +import path from 'path'; +import net from 'net'; +import dns from 'dns/promises'; +import { resolveLocalFilePath } from '@snowluma/protocol/highway/utils'; +import { defineStreamAction, f } from '../action-kit'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types'; +import { type StreamSink, StreamStatus } from '../streaming'; +import { STREAM_ROOT } from './stream-file'; + +const DEFAULT_CHUNK_BYTES = 64 * 1024; +const MAX_CHUNK_REQUEST_BYTES = 16 * 1024 * 1024; // cap the client-requested chunk size +const MAX_DOWNLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB total +const FETCH_CONNECT_TIMEOUT_MS = 30_000; // TTFB only — cleared once headers arrive (not the whole transfer) +const IDLE_TIMEOUT_MS = 60_000; // abort if no chunk arrives for this long (anti-stall) +const MAX_REDIRECTS = 5; +const DOWNLOAD_USER_AGENT = + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'; + +class DownloadError extends Error {} + +// ─────────────────────────── source resolution ─────────────────────────── + +function isWithinStreamRoot(p: string): boolean { + // Resolve the root through any symlinks too (e.g. macOS /tmp → /private/tmp), + // so a realpath'd target compares against a realpath'd root — otherwise a + // legitimate file reads as "outside" purely from the tmpdir symlink. + let root = path.resolve(STREAM_ROOT); + try { root = fs.realpathSync(STREAM_ROOT); } catch { /* root may not exist yet */ } + const rel = path.relative(root, path.resolve(p)); + return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel); +} + +function isPrivateV4(o: number[]): boolean { + return ( + o[0] === 0 || o[0] === 127 || o[0] === 10 || + (o[0] === 192 && o[1] === 168) || + (o[0] === 172 && o[1] >= 16 && o[1] <= 31) || + (o[0] === 169 && o[1] === 254) || // link-local + (o[0] === 100 && o[1] >= 64 && o[1] <= 127) // CGNAT + ); +} + +/** Parse an IPv6 string (any form, incl. `::` compression and embedded IPv4) + * to its 16 bytes. `new URL().hostname` normalises v4-mapped addresses to hex + * (`::ffff:7f00:1`), so string matching is unreliable — we work on bytes. */ +function ipv6ToBytes(input: string): Uint8Array | null { + let s = input.replace(/^\[|\]$/g, ''); + if (net.isIP(s) !== 6) return null; + const v4m = /:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(s); // embedded IPv4 tail + if (v4m) { + const o = v4m[1].split('.').map(Number); + if (o.some((n) => n > 255)) return null; + s = s.slice(0, v4m.index) + ':' + `${((o[0] << 8) | o[1]).toString(16)}:${((o[2] << 8) | o[3]).toString(16)}`; + } + const halves = s.split('::'); + if (halves.length > 2) return null; + const head = halves[0] ? halves[0].split(':') : []; + const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : []; + let groups: string[]; + if (halves.length === 2) { + const missing = 8 - head.length - tail.length; + if (missing < 0) return null; + groups = [...head, ...new Array(missing).fill('0'), ...tail]; + } else { + groups = head; + } + if (groups.length !== 8) return null; + const bytes = new Uint8Array(16); + for (let i = 0; i < 8; i++) { + const g = parseInt(groups[i] || '0', 16); + if (Number.isNaN(g) || g < 0 || g > 0xffff) return null; + bytes[i * 2] = g >> 8; + bytes[i * 2 + 1] = g & 0xff; + } + return bytes; +} + +function isPrivateIp(ip: string): boolean { + const host = ip.replace(/^\[|\]$/g, ''); + const fam = net.isIP(host); + if (fam === 4) return isPrivateV4(host.split('.').map(Number)); + if (fam === 6) { + const b = ipv6ToBytes(host); + if (!b) return true; // unparseable IPv6 → treat as unsafe + if (b.every((x) => x === 0)) return true; // :: + if (b.slice(0, 15).every((x) => x === 0) && b[15] === 1) return true; // ::1 + if ((b[0] & 0xfe) === 0xfc) return true; // fc00::/7 unique-local + if (b[0] === 0xfe && (b[1] & 0xc0) === 0x80) return true; // fe80::/10 link-local + // v4-mapped ::ffff:a.b.c.d / v4-compatible ::a.b.c.d + if (b.slice(0, 10).every((x) => x === 0) && ((b[10] === 0xff && b[11] === 0xff) || (b[10] === 0 && b[11] === 0))) { + return isPrivateV4([b[12], b[13], b[14], b[15]]); + } + // NAT64 64:ff9b::/96 + if (b[0] === 0x00 && b[1] === 0x64 && b[2] === 0xff && b[3] === 0x9b && b.slice(4, 12).every((x) => x === 0)) { + return isPrivateV4([b[12], b[13], b[14], b[15]]); + } + return false; + } + return false; +} + +/** Parse + SSRF-guard a URL: http(s) only, and neither the literal host nor any + * DNS-resolved address may be private/loopback/link-local. Not bulletproof + * against DNS rebinding, but blocks the obvious metadata-endpoint / internal + * service reach. */ +async function assertSafeUrl(raw: string): Promise { + let u: URL; + try { u = new URL(raw); } catch { throw new DownloadError('invalid URL'); } + if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new DownloadError('only http(s) URLs are allowed'); + const host = u.hostname.replace(/^\[|\]$/g, ''); + if (net.isIP(host)) { + if (isPrivateIp(host)) throw new DownloadError('refusing to fetch a private/loopback address'); + return u; + } + let addrs: Array<{ address: string }>; + try { addrs = await dns.lookup(host, { all: true }); } catch { throw new DownloadError(`cannot resolve host: ${host}`); } + for (const a of addrs) { + if (isPrivateIp(a.address)) throw new DownloadError('refusing to fetch a host that resolves to a private address'); + } + return u; +} + +interface DownloadSource { + name: string; + size: number; // 0 when unknown + iterable: AsyncIterable; + /** Force the underlying source closed (idle-timeout watchdog / abort). */ + abort?: () => void; +} + +const asStr = (v: JsonValue | undefined): string => (typeof v === 'string' ? v : ''); +const asNum = (v: JsonValue | undefined): number => { + const n = Number(v); + return Number.isFinite(n) && n > 0 ? n : 0; +}; + +/** Follow redirects MANUALLY, SSRF-guarding every hop. Default fetch follows + * redirects automatically and would NOT re-check the target, so a public URL + * could 302 to a private/metadata address — re-validating each Location closes + * that. Each hop gets a TTFB-only timeout (cleared once headers arrive, so a + * legitimate slow/large body isn't cut mid-transfer); the final hop's + * AbortController is returned so the caller's idle watchdog can kill a stalled + * body. (DNS rebinding between our check and undici's own connect remains a + * known residual — it needs connect-time peer-IP validation to fully close.) */ +async function fetchGuarded(rawUrl: string): Promise<{ resp: Response; abort: () => void }> { + let current = rawUrl; + for (let hop = 0; hop <= MAX_REDIRECTS; hop++) { + const u = await assertSafeUrl(current); + const ac = new AbortController(); + const t = setTimeout(() => ac.abort(), FETCH_CONNECT_TIMEOUT_MS); + let resp: Response; + try { + resp = await fetch(u, { headers: { 'User-Agent': DOWNLOAD_USER_AGENT }, redirect: 'manual', signal: ac.signal }); + } finally { + clearTimeout(t); + } + if (resp.status >= 300 && resp.status < 400) { + const loc = resp.headers.get('location'); + await resp.body?.cancel().catch(() => { /* ignore */ }); + if (!loc) throw new DownloadError(`download failed: ${resp.status} redirect without Location`); + current = new URL(loc, u).toString(); + continue; + } + return { resp, abort: () => ac.abort() }; + } + throw new DownloadError('download failed: too many redirects'); +} + +async function openUrl(rawUrl: string, name: string, knownSize: number): Promise { + const { resp, abort } = await fetchGuarded(rawUrl); + if (!resp.ok) { + await resp.body?.cancel().catch(() => { /* ignore */ }); + throw new DownloadError(`download failed: HTTP ${resp.status}`); + } + const declared = Number(resp.headers.get('content-length') ?? ''); + const size = (Number.isFinite(declared) && declared > 0 ? declared : 0) || knownSize; + if (!resp.body) throw new DownloadError('download failed: empty response body'); + return { name: name || urlBasename(rawUrl), size, iterable: resp.body as unknown as AsyncIterable, abort }; +} + +function urlBasename(u: string): string { + try { + const name = path.basename(new URL(u).pathname); + return name && name !== '/' ? decodeURIComponent(name) : 'download.bin'; + } catch { return 'download.bin'; } +} + +async function resolveDownload( + target: string, + ctx: ApiActionContext, + prefer: 'auto' | 'image' | 'record', + chunkSize: number, +): Promise { + // 1. local file — but ONLY a real existing file, fenced inside the stream + // temp root. `resolveLocalFilePath` returns the input verbatim for any + // non-URL string (including cached-media ids), so we must NOT treat a + // non-existent "path" as local — that would shadow the cached-media branch + // below (the whole point of the *_image/_record_stream actions). + const local = resolveLocalFilePath(target); + if (local) { + let st: fs.Stats | null = null; + try { st = fs.statSync(local); } catch { st = null; } + if (st?.isFile()) { + // Fence against the *real* path so a symlink inside the root can't point + // out (lexical resolve alone would follow it). + let real = local; + try { real = fs.realpathSync(local); } catch { /* keep lexical */ } + if (!isWithinStreamRoot(real)) throw new DownloadError('local downloads are restricted to the stream temp directory'); + const rs = fs.createReadStream(real, { highWaterMark: chunkSize }); + return { name: path.basename(real), size: st.size, iterable: rs, abort: () => rs.destroy() }; + } + } + + // 2. explicit http(s) URL. + if (/^https?:\/\//i.test(target)) return openUrl(target, '', 0); + + // 3. cached image / voice id → QQ CDN URL. + let info: JsonObject | null = null; + if (prefer !== 'record') info = await ctx.getImageInfo(target); + if (!info && prefer !== 'image') info = await ctx.getRecordInfo(target); + if (info) { + const url = asStr(info.url) || asStr(info.file); + if (/^https?:\/\//i.test(url)) return openUrl(url, asStr(info.file_name), asNum(info.file_size)); + } + + throw new DownloadError('file not found (expected a stream-dir path, an http(s) URL, or a cached image/voice id)'); +} + +// ─────────────────────────── push engine ─────────────────────────── + +async function streamChunks( + sink: StreamSink, + iterable: AsyncIterable, + totalSize: number, + dataType: string, + abort?: () => void, +): Promise<{ totalChunks: number; totalBytes: number }> { + let index = 0; + let bytesRead = 0; + // Anti-stall: if no chunk arrives for IDLE_TIMEOUT_MS, force the source closed + // so a server that sends headers then hangs can't pin a socket forever (the + // sink's own liveness check only fires when we actually send a frame). + let idle: NodeJS.Timeout | null = null; + const armIdle = (): void => { + if (idle) clearTimeout(idle); + idle = setTimeout(() => { abort?.(); }, IDLE_TIMEOUT_MS); + if (idle.unref) idle.unref(); + }; + armIdle(); + try { + for await (const part of iterable) { + armIdle(); + const buf = Buffer.isBuffer(part) ? part : Buffer.from(part); + bytesRead += buf.length; + if (bytesRead > MAX_DOWNLOAD_BYTES) throw new DownloadError(`download exceeds size limit (${MAX_DOWNLOAD_BYTES} bytes)`); + const b64 = buf.toString('base64'); + await sink.send({ + type: StreamStatus.Stream, + data_type: dataType, + index, + data: b64, + size: buf.length, + progress: totalSize > 0 ? Math.min(100, Math.round((bytesRead / totalSize) * 100)) : 0, + base64_size: b64.length, + }); + index++; + } + } finally { + if (idle) clearTimeout(idle); + } + return { totalChunks: index, totalBytes: bytesRead }; +} + +async function runDownload( + target: string, + chunkSizeReq: number | undefined, + ctx: ApiActionContext, + sink: StreamSink, + prefer: 'auto' | 'image' | 'record', +): Promise { + if (!target) throw new DownloadError('file is required'); + let chunkSize = chunkSizeReq && chunkSizeReq > 0 ? chunkSizeReq : DEFAULT_CHUNK_BYTES; + if (chunkSize > MAX_CHUNK_REQUEST_BYTES) chunkSize = MAX_CHUNK_REQUEST_BYTES; + + const src = await resolveDownload(target, ctx, prefer, chunkSize); + await sink.send({ + type: StreamStatus.Stream, + data_type: 'file_info', + file_name: src.name, + file_size: src.size, + chunk_size: chunkSize, + }); + const { totalChunks, totalBytes } = await streamChunks(sink, src.iterable, src.size, 'file_chunk', src.abort); + return okResponse({ + type: StreamStatus.Response, + data_type: 'file_complete', + file_name: src.name, + total_chunks: totalChunks, + total_bytes: totalBytes, + message: 'Download completed', + }); +} + +// ─────────────────────────── action definitions ─────────────────────────── + +const downloadParams = { + file: f.string().optional().describe('文件路径(限 stream 临时目录)/ http(s) URL').role('file'), + file_id: f.string().optional().describe('文件 ID(缓存的图片/语音 id)').role('file_id'), + chunk_size: f.int({ min: 1 }).optional().describe('分块大小(字节,默认 64KB)'), +}; + +const downloadFileStream = defineStreamAction({ + name: 'download_file_stream', + summary: '以流式方式下载文件(stream 目录本地文件 / URL / 缓存媒体)', + returns: '流式帧:file_info → file_chunk* → file_complete', + params: downloadParams, + run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'auto'), +}); + +const downloadFileImageStream = defineStreamAction({ + name: 'download_file_image_stream', + summary: '以流式方式下载图片(缓存图片 id / URL / stream 目录本地文件)', + returns: '流式帧:file_info → file_chunk* → file_complete', + params: downloadParams, + run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'image'), +}); + +const downloadFileRecordStream = defineStreamAction({ + name: 'download_file_record_stream', + summary: '以流式方式下载语音(缓存语音 id / URL / stream 目录本地文件)', + returns: '流式帧:file_info → file_chunk* → file_complete', + params: downloadParams, + run: (p, ctx, _raw, sink) => runDownload(p.file || p.file_id || '', p.chunk_size, ctx, sink, 'record'), +}); + +const testDownloadStream = defineStreamAction({ + name: 'test_download_stream', + summary: '测试下载流(推送 10 个数据帧,验证流式传输,不触达 QQ)', + returns: '流式帧:data_chunk*10 → data_complete(error=true 时以 error 帧结束)', + params: { error: f.bool().default(false).describe('是否触发测试错误') }, + run: async (p, _ctx, _raw, sink) => { + for (let i = 0; i < 10; i++) { + await sink.send({ type: StreamStatus.Stream, data: `Index-> ${i + 1}`, data_type: 'data_chunk' }); + } + if (p.error) throw new DownloadError('This is a test error'); + return okResponse({ type: StreamStatus.Response, data_type: 'data_complete', data: 'Stream transmission complete' }); + }, +}); + +export const actions = [downloadFileStream, downloadFileImageStream, downloadFileRecordStream, testDownloadStream]; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + for (const a of actions) a.register(h, ctx); +} + +// Exposed for tests. +export const __test = { resolveDownload, isWithinStreamRoot, isPrivateIp, assertSafeUrl, streamChunks, runDownload }; diff --git a/packages/onebot/src/actions/stream-file.ts b/packages/onebot/src/actions/stream-file.ts new file mode 100644 index 00000000..889d2a0a --- /dev/null +++ b/packages/onebot/src/actions/stream-file.ts @@ -0,0 +1,369 @@ +// Stream API file actions (#163) — NapCat-compatible chunked file transfer. +// +// upload_file_stream: a client (possibly on another machine) pushes a file to +// the bot in base64 chunks across repeated calls keyed by `stream_id`; the bot +// reassembles them into a local temp file and returns its path, which the +// client then feeds to a normal send action. This sidesteps the HTTP 2 MB body +// cap and the "client and bot share a filesystem" assumption of plain file:// +// sends. Reassembly streams chunk-by-chunk to disk (no whole-file +// Buffer.concat) so an arbitrarily large upload won't OOM the bot. +// +// clean_stream_temp_file: wipe the stream temp dirs (upload + download), scoped +// so it never touches unrelated temp files. +// +// Hardening over the NapCat original (which has all of these holes): stream_id +// is allowlist-validated + every derived path is fenced inside the upload dir +// (no path traversal); total_chunks/chunk/stream/byte counts are all bounded +// (no single-request OOM or disk/fd exhaustion); chunk indices are claimed +// synchronously (no double-count race); state is namespaced per account. + +import os from 'os'; +import path from 'path'; +import fs from 'fs'; +import { createHash } from 'crypto'; +import { createLogger } from '@snowluma/common/logger'; +import { defineAction, defineStreamAction, f } from '../action-kit'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { okResponse, type ApiResponse } from '../types'; +import { StreamStatus } from '../streaming'; + +const log = createLogger('OneBot.Stream'); + +export const STREAM_ROOT = path.join(os.tmpdir(), 'snowluma-stream'); +export const STREAM_UPLOAD_DIR = path.join(STREAM_ROOT, 'upload'); +export const STREAM_DOWNLOAD_DIR = path.join(STREAM_ROOT, 'download'); + +const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000; // idle stream reaped after 10 min +const DEFAULT_RETENTION_MS = 5 * 60 * 1000; // reassembled file auto-deleted after 5 min + +// Resource caps (DoS guards — the whole point of the disk-streaming design is +// blown if a single request can still OOM, and an unbounded server can be +// flooded with streams/chunks/bytes). +const MAX_CONCURRENT_STREAMS = 64; +const MAX_CHUNKS = 200_000; // also bounds the completion scan +const MAX_CHUNK_BYTES = 32 * 1024 * 1024; // one decoded chunk +const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB cumulative per stream + +// stream_id / account key allowlist: filename-safe, no separators, no dots +// (so no `.`/`..` traversal token can ever reach a path segment). +const SAFE_ID_RE = /^[A-Za-z0-9_-]{1,128}$/; + +class StreamError extends Error {} + +function validateStreamId(id: string): void { + if (!SAFE_ID_RE.test(id)) throw new StreamError('invalid stream_id (allowed: 1-128 chars of A-Z a-z 0-9 _ -)'); +} + +/** Account namespace for the in-memory map + on-disk dirs. Empty (tests / no + * login) → flat, un-namespaced. Sanitised so it can't widen the path either. */ +function accountKey(ctx?: ApiActionContext): string { + let raw = ''; + try { raw = String(ctx?.getLoginInfo?.().userId ?? ''); } catch { raw = ''; } + return raw.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 64); +} + +/** Belt-and-braces: assert a derived path stays inside the upload dir even if + * the allowlist above is ever weakened. */ +function assertWithin(root: string, target: string): void { + const rel = path.relative(root, target); + if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) { + throw new StreamError('resolved stream path escapes the upload directory'); + } +} + +// ─────────────────────────── upload state ─────────────────────────── + +interface UploadState { + /** Client-facing stream_id (echoed in frames). */ + id: string; + /** Internal map key — `:` or just `` when un-namespaced. */ + key: string; + filename: string; + totalChunks: number; + /** Indices CLAIMED (sync, before the write await) — drives dedup + byte + * accounting so two concurrent calls for one index can't double-count. */ + claimed: Set; + /** Indices actually FLUSHED to disk (added after the write resolves) — drives + * completion + the reported count, so completion can't fire while a chunk + * file is still being written (which would read a truncated part). Neither + * set is pre-allocated to total_chunks (that would defeat the no-OOM goal). */ + written: Set; + bytesWritten: number; + fileSize?: number; + expectedSha256?: string; + tempDir: string; + finalPath: string; + fileRetention: number; + timeoutId: NodeJS.Timeout; +} + +/** Process-wide. Key is account-namespaced so two accounts (same process) can't + * collide on a shared/non-UUID stream_id. */ +const uploads = new Map(); + +function reapTimer(key: string): NodeJS.Timeout { + const t = setTimeout(() => { cleanupUpload(key, true); }, UPLOAD_TIMEOUT_MS); + if (typeof t.unref === 'function') t.unref(); // don't pin the event loop on a stalled upload + return t; +} + +function cleanupUpload(key: string, deleteFinal: boolean): void { + const state = uploads.get(key); + if (!state) return; + clearTimeout(state.timeoutId); + try { fs.rmSync(state.tempDir, { recursive: true, force: true }); } catch { /* best effort */ } + if (deleteFinal) { + try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ } + } + uploads.delete(key); +} + +function safeFilename(name: string | undefined, id: string): string { + const base = (name ?? '') + .replace(/[/\\]/g, '_') // no directory separators + .replace(/\.\.+/g, '_') // no `..` traversal tokens + .replace(/^\.+/, '') // no leading dots + .trim(); + return base || `upload_${id}`; +} + +function createUpload(p: UploadParams, account: string): UploadState { + if (!p.total_chunks || p.total_chunks <= 0) throw new StreamError('total_chunks required for new stream'); + if (p.total_chunks > MAX_CHUNKS) throw new StreamError(`total_chunks exceeds limit (${MAX_CHUNKS})`); + if (p.file_size !== undefined && p.file_size > MAX_UPLOAD_BYTES) throw new StreamError(`file_size exceeds limit (${MAX_UPLOAD_BYTES} bytes)`); + if (uploads.size >= MAX_CONCURRENT_STREAMS) throw new StreamError(`too many concurrent upload streams (${MAX_CONCURRENT_STREAMS})`); + + const filename = safeFilename(p.filename, p.stream_id); + const dirRoot = account ? path.join(STREAM_UPLOAD_DIR, account) : STREAM_UPLOAD_DIR; + const tempDir = path.join(dirRoot, p.stream_id); + const finalPath = path.join(dirRoot, `${p.stream_id}__${filename}`); + assertWithin(STREAM_UPLOAD_DIR, tempDir); + assertWithin(STREAM_UPLOAD_DIR, finalPath); + fs.mkdirSync(tempDir, { recursive: true }); + + const key = account ? `${account}:${p.stream_id}` : p.stream_id; + const state: UploadState = { + id: p.stream_id, + key, + filename, + totalChunks: p.total_chunks, + claimed: new Set(), + written: new Set(), + bytesWritten: 0, + fileSize: p.file_size, + expectedSha256: p.expected_sha256, + tempDir, + finalPath, + fileRetention: p.file_retention, + timeoutId: reapTimer(key), + }; + uploads.set(key, state); + return state; +} + +function statusFrame(state: UploadState, status: string): ApiResponse { + return okResponse({ + type: StreamStatus.Stream, + stream_id: state.id, + status, + received_chunks: state.written.size, + total_chunks: state.totalChunks, + }); +} + +function writeChunkToStream(stream: fs.WriteStream, buf: Buffer): Promise { + return new Promise((resolve, reject) => { + stream.write(buf, (err) => (err ? reject(err) : resolve())); + }); +} + +async function completeUpload(state: UploadState): Promise { + if (state.written.size !== state.totalChunks) { + const missing: number[] = []; + for (let i = 0; i < state.totalChunks && missing.length < 16; i++) { + if (!state.written.has(i)) missing.push(i); + } + const more = state.totalChunks - state.written.size > missing.length ? '…' : ''; + throw new StreamError(`incomplete stream: missing ${state.totalChunks - state.written.size} chunk(s) [${missing.join(',')}${more}]`); + } + + // Stream each chunk file into the final file in order, hashing as we go — one + // chunk in memory at a time, never the whole payload. + const hash = createHash('sha256'); + const out = fs.createWriteStream(state.finalPath); + try { + for (let i = 0; i < state.totalChunks; i++) { + const buf = await fs.promises.readFile(path.join(state.tempDir, `${i}.chunk`)); + hash.update(buf); + await writeChunkToStream(out, buf); + } + await new Promise((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve()))); + } catch (err) { + out.destroy(); + try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ } + throw err; + } + + const sha256 = hash.digest('hex'); + if (state.expectedSha256 && sha256 !== state.expectedSha256) { + try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ } + throw new StreamError(`sha256 mismatch (expected ${state.expectedSha256}, got ${sha256})`); + } + + const finalPath = state.finalPath; + const fileSize = fs.statSync(finalPath).size; + const received = state.written.size; + const total = state.totalChunks; + const retention = state.fileRetention; + + // Drop chunk parts + in-memory state but KEEP the reassembled file. + cleanupUpload(state.key, false); + if (retention > 0) { + const t = setTimeout(() => { + fs.rm(finalPath, { force: true }, (err) => { + if (err) log.warn('failed to delete retained stream file %s: %s', finalPath, err.message); + }); + }, retention); + if (typeof t.unref === 'function') t.unref(); + } + + return okResponse({ + type: StreamStatus.Response, + stream_id: state.id, + status: 'file_complete', + received_chunks: received, + total_chunks: total, + file_path: finalPath, + file_size: fileSize, + sha256, + }); +} + +async function handleUpload(p: UploadParams, account = ''): Promise { + validateStreamId(p.stream_id); + const key = account ? `${account}:${p.stream_id}` : p.stream_id; + + if (p.reset) { + cleanupUpload(key, true); + // NapCat surfaces reset as an error frame; mirror it for client parity. + throw new StreamError('Stream reset completed'); + } + + if (p.verify_only) { + const state = uploads.get(key); + if (!state) throw new StreamError('stream not found'); + return statusFrame(state, 'file_created'); + } + + const state = uploads.get(key) ?? createUpload(p, account); + // Metadata may arrive on the creating call or any later one (e.g. the client + // only knows the whole-file sha256 when it sends `is_complete`). + if (p.expected_sha256 !== undefined) state.expectedSha256 = p.expected_sha256; + if (p.file_size !== undefined) state.fileSize = p.file_size; + + if (p.chunk_data !== undefined && p.chunk_index !== undefined) { + const index = p.chunk_index; + if (index < 0 || index >= state.totalChunks) throw new StreamError(`invalid chunk index: ${index}`); + if (state.claimed.has(index)) return statusFrame(state, 'chunk_received'); // duplicate / in-flight — idempotent + + const buf = Buffer.from(p.chunk_data, 'base64'); + if (buf.length > MAX_CHUNK_BYTES) throw new StreamError(`chunk exceeds size limit (${MAX_CHUNK_BYTES} bytes)`); + if (state.bytesWritten + buf.length > MAX_UPLOAD_BYTES) throw new StreamError(`stream exceeds total size limit (${MAX_UPLOAD_BYTES} bytes)`); + + // Claim the index synchronously (before the write await) so two concurrent + // calls for the same index can't both pass the dedup check or double-count + // bytes. `written` is only set AFTER the bytes hit disk, so completion can + // never fire while this chunk file is still being written. + state.claimed.add(index); + state.bytesWritten += buf.length; + try { + await fs.promises.writeFile(path.join(state.tempDir, `${index}.chunk`), buf); + } catch (err) { + state.claimed.delete(index); + state.bytesWritten -= buf.length; + throw err; + } + state.written.add(index); + clearTimeout(state.timeoutId); + state.timeoutId = reapTimer(state.key); + return statusFrame(state, 'chunk_received'); + } + + if (p.is_complete || state.written.size === state.totalChunks) { + return completeUpload(state); + } + + return statusFrame(state, 'file_created'); +} + +// ─────────────────────────── action definitions ─────────────────────────── + +const uploadParams = { + stream_id: f.string({ allowEmpty: false }).describe('流 ID(客户端生成的 UUID,限 [A-Za-z0-9_-])'), + chunk_data: f.string().optional().describe('分块数据(Base64)'), + chunk_index: f.int({ min: 0 }).optional().describe('分块索引(从 0 开始)'), + total_chunks: f.int({ min: 1 }).optional().describe('总分块数(新流必填)'), + file_size: f.int({ min: 0 }).optional().describe('文件总大小(字节)'), + expected_sha256: f.string().optional().describe('期望的整文件 SHA256(校验)'), + is_complete: f.bool().optional().describe('是否为最后一个分块/触发合并'), + filename: f.string().optional().describe('文件名'), + reset: f.bool().optional().describe('重置并丢弃该流'), + verify_only: f.bool().optional().describe('仅查询当前流状态'), + file_retention: f.int({ min: 0 }).default(DEFAULT_RETENTION_MS).describe('合并文件保留毫秒(0=不回收)'), +}; + +type UploadParams = { + stream_id: string; + chunk_data: string | undefined; + chunk_index: number | undefined; + total_chunks: number | undefined; + file_size: number | undefined; + expected_sha256: string | undefined; + is_complete: boolean | undefined; + filename: string | undefined; + reset: boolean | undefined; + verify_only: boolean | undefined; + file_retention: number; +}; + +const uploadFileStream = defineStreamAction({ + name: 'upload_file_stream', + summary: '以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)', + returns: '流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_size/sha256)', + params: uploadParams, + run: (p, ctx) => handleUpload(p, accountKey(ctx)), +}); + +function cleanDir(dir: string): number { + let removed = 0; + let entries: string[]; + try { entries = fs.readdirSync(dir); } catch { return 0; } // dir absent → nothing to clean + for (const name of entries) { + try { fs.rmSync(path.join(dir, name), { recursive: true, force: true }); removed++; } catch (err) { + log.warn('failed to remove stream temp %s: %s', path.join(dir, name), err instanceof Error ? err.message : String(err)); + } + } + return removed; +} + +const cleanStreamTempFile = defineAction({ + name: 'clean_stream_temp_file', + summary: '清理流式传输临时文件(仅清理 stream 上传/下载目录)', + returns: '{ message, removed }', + params: {}, + run: () => { + const removed = cleanDir(STREAM_UPLOAD_DIR) + cleanDir(STREAM_DOWNLOAD_DIR); + // Active uploads' chunk dirs may have been wiped — drop their state too. + for (const k of [...uploads.keys()]) cleanupUpload(k, false); + return okResponse({ message: 'success', removed }); + }, +}); + +export const actions = [uploadFileStream, cleanStreamTempFile]; + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + for (const a of actions) a.register(h, ctx); +} + +// Exposed for tests. +export const __test = { uploads, handleUpload, cleanDir, validateStreamId, STREAM_UPLOAD_DIR, MAX_CONCURRENT_STREAMS, MAX_CHUNKS }; diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index 1e958e16..743c393b 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -11,9 +11,12 @@ import { register as registerInfo } from './actions/info'; import { register as registerMessage } from './actions/message'; import { register as registerQzone } from './actions/qzone'; import { register as registerRequest } from './actions/request'; +import { register as registerStreamFile } from './actions/stream-file'; +import { register as registerStreamDownload } from './actions/stream-download'; import type { ForwardPreviewMeta } from './modules/message-actions'; import type { JsonObject, JsonValue, MessageMeta } from './types'; import { RETCODE, failedResponse } from './types'; +import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from './streaming'; const moduleLog = createLogger('Bridge.Action'); @@ -80,7 +83,7 @@ export interface ApiActionContext { fetchPttText: (messageId: number) => Promise<{ text: string }>; } -type ActionHandler = (params: JsonObject) => Promise; +type ActionHandler = (params: JsonObject, sink?: StreamSink) => Promise; /** A handled-action record handed to debug observers. */ export interface ActionRecord { @@ -93,6 +96,9 @@ export type ActionObserver = (rec: ActionRecord) => void; export class ApiHandler { private readonly handlers = new Map(); + /** Names that answer with a multi-frame Stream API response (#163). The + * network adapter consults this BEFORE dispatch to pick streaming output. */ + private readonly streamActions = new Set(); private readonly log: Logger; /** Debug-stream taps — notified after every handled action. Attached * on-demand (ref-counted) by the WebUI debug stream. */ @@ -116,13 +122,27 @@ export class ApiHandler { registerExtended(this, context); registerGroupAlbum(this, context); registerQzone(this, context); + registerStreamFile(this, context); + registerStreamDownload(this, context); } registerAction(action: string, handler: ActionHandler): void { this.handlers.set(action, handler); } - async handle(action: string, params: JsonObject): Promise { + /** Register a Stream API action — dispatched exactly like a normal action, + * but flagged so adapters stream its frames (the handler receives a sink). */ + registerStreamAction(action: string, handler: ActionHandler): void { + this.handlers.set(action, handler); + this.streamActions.add(action); + } + + /** Whether `action` answers with a multi-frame Stream API response. */ + isStreamAction(action: string): boolean { + return this.streamActions.has(action); + } + + async handle(action: string, params: JsonObject, sink?: StreamSink): Promise { const handler = this.handlers.get(action); if (!handler) { this.log.debug('unknown action %s', action); @@ -134,15 +154,16 @@ export class ApiHandler { // the wrap + id allocation when trace is actually live, so the default // path stays allocation-free. if (getLogLevel() !== 'trace') { - return this.runAction(action, handler, params); + return this.runAction(action, handler, params, sink); } - return runWithRequestId(nextRequestId(), () => this.runAction(action, handler, params)); + return runWithRequestId(nextRequestId(), () => this.runAction(action, handler, params, sink)); } private async runAction( action: string, handler: ActionHandler, params: JsonObject, + sink?: StreamSink, ): Promise { // Terse breadcrumb to the log file (debug, always persisted): lets the // operator grep "what did the bot get asked to do" in post-mortems. @@ -154,7 +175,7 @@ export class ApiHandler { const startedAt = Date.now(); let response: import('./types').ApiResponse; try { - response = await handler(params); + response = await handler(params, sink); this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]); } catch (error) { // Action failures are almost always param-shape problems coming @@ -185,33 +206,52 @@ export class ApiHandler { } } - async processRequest(rawRequest: string): Promise { - if (!rawRequest.trim()) { - return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request')); - } + /** WS dispatch supporting Stream API multi-frame responses. A normal action + * emits exactly one frame; a stream action emits each intermediate frame + * then the terminal frame — every frame carries the request's echo. `emit` + * writes one JSON string per frame; awaiting it lets the transport apply + * backpressure. `isAlive`, when supplied, is checked before each stream + * frame — returning false aborts the action (e.g. the client disconnected), + * so a dead client can't make a download keep pumping frames into the void. */ + async processStreamRequest( + rawRequest: string, + emit: (json: string) => void | Promise, + isAlive?: () => boolean, + ): Promise { + const bad = (): void => { void emit(JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'))); }; + if (!rawRequest.trim()) { bad(); return; } + let action: string; + let params: JsonObject; + let echo: JsonValue | undefined; try { const parsed = JSON.parse(rawRequest) as unknown; - if (!isJsonObject(parsed)) { - return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request')); - } - - const action = asString(parsed.action); - if (!action) { - return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request')); - } - - const params = isJsonObject(parsed.params) ? parsed.params : {}; - const echo = parsed.echo; - const response = await this.handle(action, params); - if (echo !== undefined) { - response.echo = toJsonValue(echo); - } - - return JSON.stringify(response); + if (!isJsonObject(parsed)) { bad(); return; } + const a = asString(parsed.action); + if (!a) { bad(); return; } + action = a; + params = isJsonObject(parsed.params) ? parsed.params : {}; + echo = parsed.echo !== undefined ? toJsonValue(parsed.echo) : undefined; } catch { - return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request')); + bad(); + return; } + + if (!this.isStreamAction(action)) { + const response = await this.handle(action, params); + if (echo !== undefined) response.echo = echo; + await emit(JSON.stringify(response)); + return; + } + + const sink: StreamSink = { + send: async (frame) => { + if (isAlive && !isAlive()) throw new Error('stream transport closed'); + await emit(JSON.stringify(wrapStreamFrame(frame, echo))); + }, + }; + const response = await this.handle(action, params, sink); + await emit(JSON.stringify(wrapStreamTerminal(response, echo))); } } diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 35f9b7fc..93a94d9d 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -73,6 +73,16 @@ export class OneBotInstance { invokeAction(action: string, params: JsonObject): Promise { return this.apiHandler.handle(action, params); } + /** Drive an action through the streaming seam (debug tester, stream actions). + * `rawRequest` is a `{action, params, echo?}` JSON string; `emit` receives + * each frame as a JSON string. Non-stream actions emit a single frame. */ + invokeStream( + rawRequest: string, + emit: (json: string) => void | Promise, + isAlive?: () => boolean, + ): Promise { + return this.apiHandler.processStreamRequest(rawRequest, emit, isAlive); + } constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig, globalSettings: GlobalSettings) { this.uin = uin; diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index e2d4da1c..1fa44697 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -583,6 +583,19 @@ export async function sendPrivateMessage( let allFileElements = elements.filter(e => e.type === 'file'); let nonFileElements = elements.filter(e => e.type !== 'file'); + // [#145] A video above QQ's ~100 MB video-resource cap (MAX_VIDEO_SIZE) + // uploads "successfully" but renders as 视频已过期 on the receiver — the + // server accepts the bytes yet never produces a valid video resource. The + // on-error fallback below can't catch it (the oversized upload doesn't + // throw), so route known-oversized videos to the file path up front. + { + const pre = splitVideoFileFallback(nonFileElements, false); + if (pre.fileEls.length > 0) { + allFileElements = [...allFileElements, ...pre.fileEls]; + nonFileElements = pre.remaining; + } + } + let lastReceipt: Awaited> | undefined; if (nonFileElements.length > 0) { try { @@ -690,6 +703,16 @@ export async function sendGroupMessage( let allFileElements = elements.filter(e => e.type === 'file'); let nonFileElements = elements.filter(e => e.type !== 'file'); + // [#145] Route known-oversized videos (> MAX_VIDEO_SIZE) to the file path + // up front — they upload as a video without error but render expired. + { + const pre = splitVideoFileFallback(nonFileElements, false); + if (pre.fileEls.length > 0) { + allFileElements = [...allFileElements, ...pre.fileEls]; + nonFileElements = pre.remaining; + } + } + let lastReceipt: Awaited> | undefined; if (nonFileElements.length > 0) { try { diff --git a/packages/onebot/src/network/http-server-adapter.ts b/packages/onebot/src/network/http-server-adapter.ts index e683d087..b617df8e 100644 --- a/packages/onebot/src/network/http-server-adapter.ts +++ b/packages/onebot/src/network/http-server-adapter.ts @@ -5,8 +5,10 @@ import { type Server, type ServerResponse, } from 'http'; +import type { ApiHandler } from '../api-handler'; import type { DispatchPayload } from '../event-filter'; -import type { HttpServerNetwork, JsonObject, JsonValue } from '../types'; +import type { ApiResponse, HttpServerNetwork, JsonObject, JsonValue } from '../types'; +import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from '../streaming'; import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter'; import { isAuthorized, normalizePath } from './utils'; @@ -181,6 +183,13 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter return; } + // Stream API (#163): answer with chunked multi-frame output — each frame + // a JSON envelope delimited by `\r\n\r\n`, terminated by the final frame. + if (this.ctx.api.isStreamAction(action)) { + await streamHttpResponse(res, this.ctx.api, action, params as JsonObject, echo as JsonValue | undefined); + return; + } + const response = await this.ctx.api.handle(action, params as JsonObject); if (echo !== undefined) { response.echo = echo as JsonValue; @@ -212,7 +221,41 @@ function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Prom } function writeJson(res: ServerResponse, statusCode: number, data: unknown): void { + // A streaming response may already have flushed headers (and even ended); a + // late error must not double-send and trip ERR_HTTP_HEADERS_SENT. + if (res.headersSent || res.writableEnded) return; res.statusCode = statusCode; res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.end(JSON.stringify(data)); } + +/** Stream a multi-frame Stream API response (#163): chunked transfer (no + * Content-Length → Node frames it), each frame a JSON envelope delimited by + * `\r\n\r\n`, the action's terminal response written last. Matches NapCat: + * the body is `\r\n\r\n`-joined JSON objects, NOT a single JSON document, so + * no `application/json` Content-Type is claimed. Each `res.write` is awaited + * (flush callback) for backpressure, and the sink aborts the action once the + * client disconnects so a big download stops pumping into a dead socket. */ +async function streamHttpResponse( + res: ServerResponse, + api: ApiHandler, + action: string, + params: JsonObject, + echo: JsonValue | undefined, +): Promise { + res.statusCode = 200; + const writeFrame = (frame: ApiResponse): Promise => + new Promise((resolve) => { + if (res.writableEnded || res.destroyed) { resolve(); return; } + res.write(JSON.stringify(frame) + '\r\n\r\n', () => resolve()); + }); + const sink: StreamSink = { + send: async (frame) => { + if (res.writableEnded || res.destroyed) throw new Error('stream client disconnected'); + await writeFrame(wrapStreamFrame(frame, echo)); + }, + }; + const response = await api.handle(action, params, sink); + await writeFrame(wrapStreamTerminal(response, echo)); + if (!res.writableEnded && !res.destroyed) res.end(); +} diff --git a/packages/onebot/src/network/utils.ts b/packages/onebot/src/network/utils.ts index c65c7c87..64458964 100644 --- a/packages/onebot/src/network/utils.ts +++ b/packages/onebot/src/network/utils.ts @@ -31,6 +31,19 @@ export function safeSend(socket: WebSocket, payload: string, onError?: (err: Err }); } +/** Backpressure-aware send: resolves only once `ws` has flushed `payload` to + * the socket (the `send` callback fires post-write), so a streaming producer + * that awaits this won't outrun a slow client and balloon the send buffer. + * Never rejects — a closed socket or send error resolves quietly (the stream + * sink handles liveness/abort separately so a dead client can't crash the + * per-message handler with an unhandled rejection). */ +export function safeSendAsync(socket: WebSocket, payload: string): Promise { + return new Promise((resolve) => { + if (socket.readyState !== 1 /* WebSocket.OPEN */) { resolve(); return; } + socket.send(payload, () => resolve()); + }); +} + export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void { if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return; socket.close(code, reason); diff --git a/packages/onebot/src/network/ws-client-adapter.ts b/packages/onebot/src/network/ws-client-adapter.ts index c68f0049..59682996 100644 --- a/packages/onebot/src/network/ws-client-adapter.ts +++ b/packages/onebot/src/network/ws-client-adapter.ts @@ -8,7 +8,7 @@ import { } from '../event-filter'; import type { JsonObject, WsClientNetwork, WsRole } from '../types'; import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter'; -import { rawDataToString, safeClose, safeSend } from './utils'; +import { rawDataToString, safeClose, safeSend, safeSendAsync } from './utils'; const moduleLog = createLogger('OneBot.WS-Client'); const DEFAULT_RECONNECT_INTERVAL_MS = 5000; @@ -146,8 +146,13 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { if (this.role !== 'Api' && this.role !== 'Universal') return; const text = rawDataToString(raw); if (!text) return; - const response = await this.ctx.api.processRequest(text); - safeSend(socket, response); + // Stream API (#163): one frame for a normal action, N for a streaming one. + // Async send = backpressure; liveness check aborts on disconnect. + await this.ctx.api.processStreamRequest( + text, + (frame) => safeSendAsync(socket, frame), + () => socket.readyState === 1, + ); } private sendBootstrapMetaEvents(socket: WebSocket): void { diff --git a/packages/onebot/src/network/ws-server-adapter.ts b/packages/onebot/src/network/ws-server-adapter.ts index 1904b32f..b2f2056f 100644 --- a/packages/onebot/src/network/ws-server-adapter.ts +++ b/packages/onebot/src/network/ws-server-adapter.ts @@ -9,7 +9,7 @@ import { } from '../event-filter'; import type { JsonObject, WsRole, WsServerNetwork } from '../types'; import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter'; -import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils'; +import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend, safeSendAsync } from './utils'; const moduleLog = createLogger('OneBot.WS-Server'); @@ -119,7 +119,9 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { this.connections.set(socket, conn); socket.on('message', (raw: Buffer) => { - void this.handleApiMessage(socket, role, raw); + void this.handleApiMessage(socket, role, raw).catch((err) => { + this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err)); + }); }); socket.on('close', () => this.connections.delete(socket)); socket.on('error', (err: Error) => { @@ -135,8 +137,15 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { if (role !== 'Api' && role !== 'Universal') return; const text = rawDataToString(raw); if (!text) return; - const response = await this.ctx.api.processRequest(text); - safeSend(socket, response); + // Stream API (#163) emits multiple frames per request; processStreamRequest + // sends one frame for a normal action and N for a streaming one. The async + // send applies backpressure (awaits flush); the liveness check aborts a + // streaming action once the client goes away. + await this.ctx.api.processStreamRequest( + text, + (frame) => safeSendAsync(socket, frame), + () => socket.readyState === 1, + ); } private sendBootstrapMetaEvents(socket: WebSocket): void { diff --git a/packages/onebot/src/streaming.ts b/packages/onebot/src/streaming.ts new file mode 100644 index 00000000..80d03aa3 --- /dev/null +++ b/packages/onebot/src/streaming.ts @@ -0,0 +1,75 @@ +// streaming — Stream API plumbing (#163, NapCat-compatible). +// +// A handful of OneBot actions ("Stream API") answer a single request with +// MANY response frames instead of one: an upload acks each chunk, a download +// pushes the file out chunk-by-chunk. SnowLuma's normal dispatch is strictly +// one-request → one-response, so streaming needs a small seam: +// +// • a `StreamSink` the action calls to emit intermediate frames, and +// • per-adapter wiring that writes each frame on the wire (HTTP chunked / +// repeated WS messages) instead of closing after the first. +// +// Wire format mirrors NapCat exactly so its client scripts work unchanged: +// every frame is an OB11 envelope carrying `stream:'stream-action'`, and the +// frame `data` is a StreamPacket whose `type` is one of stream/response/error. + +import type { ApiResponse, JsonValue } from './types'; + +/** Marks an OB11 envelope as one frame of a streaming response. */ +export const STREAM_MARK = 'stream-action'; + +/** Frame `type` discriminator carried inside each frame's `data`. */ +export enum StreamStatus { + /** An intermediate chunk frame (transfer in progress). */ + Stream = 'stream', + /** The terminal frame — the stream finished successfully. */ + Response = 'response', + /** A stream was reset / aborted by the caller. */ + Reset = 'reset', + /** The terminal frame — the stream failed. */ + Error = 'error', +} + +/** A sink an action uses to push intermediate stream frames. Each `send` + * carries the raw frame DATA (a StreamPacket: `{ type, data_type, ... }`); + * the network adapter wraps it in an OB11 envelope + the stream marker and + * flushes it on the wire. The action's eventual return value is the terminal + * frame, so do NOT `send` the final result through the sink. */ +export interface StreamSink { + send(frame: JsonValue): Promise; +} + +/** Fallback sink for when a stream action is invoked over a transport that + * can't stream (or by a plain client): intermediate frames are dropped, the + * terminal response is still returned normally. */ +export const NOOP_SINK: StreamSink = { send: async () => { /* dropped */ } }; + +/** Wrap a raw stream-frame `data` payload into an OB11 envelope carrying the + * stream marker (mirrors NapCat's `OB11Response.ok(data, echo, true)`). The + * empty `message`/`wording` pair matches NapCat — clients reading either key + * on an intermediate frame get `''`, never `undefined`. */ +export function wrapStreamFrame(data: JsonValue, echo: JsonValue | undefined): ApiResponse { + const frame: ApiResponse = { status: 'ok', retcode: 0, data, message: '', wording: '', stream: STREAM_MARK }; + if (echo !== undefined) frame.echo = echo; + return frame; +} + +/** Turn an action's terminal `ApiResponse` into the final streaming frame: + * attach the stream marker + echo, mirror `wording` into `message` (NapCat + * sets both), and — on failure — normalise `data` to an error packet + * (`{ type:'error' }`) so NapCat clients see the error `type` while the + * human-readable reason stays in `message`/`wording`. + * + * Contract: on success the action's `data` MUST carry `type:'response'` (the + * client treats that frame as the stream terminator). Stream actions are + * responsible for that, mirroring NapCat's `BaseDownloadStream`. */ +export function wrapStreamTerminal(response: ApiResponse, echo: JsonValue | undefined): ApiResponse { + const frame: ApiResponse = { ...response, stream: STREAM_MARK }; + if (echo !== undefined) frame.echo = echo; + if (response.status === 'failed') { + frame.data = { type: StreamStatus.Error, data_type: 'error' }; + } + frame.message = frame.wording ?? ''; + if (frame.wording === undefined) frame.wording = ''; + return frame; +} diff --git a/packages/onebot/src/types.ts b/packages/onebot/src/types.ts index 2859ef5f..57e99feb 100644 --- a/packages/onebot/src/types.ts +++ b/packages/onebot/src/types.ts @@ -7,6 +7,13 @@ export interface ApiResponse { data: JsonValue; echo?: JsonValue; wording?: string; + /** Mirror of `wording` carried on Stream API frames — NapCat puts the + * message text in BOTH `message` and `wording`, so clients reading either + * key work. Only set on stream frames. */ + message?: string; + /** Only set on Stream API frames — `'stream-action'`. Marks an envelope as + * one frame of a multi-frame streaming response (NapCat Stream API wire). */ + stream?: string; } export interface OneBotRequest { diff --git a/packages/onebot/tests/action-kit.test.ts b/packages/onebot/tests/action-kit.test.ts index 02a3d4cb..f36e68ce 100644 --- a/packages/onebot/tests/action-kit.test.ts +++ b/packages/onebot/tests/action-kit.test.ts @@ -167,7 +167,7 @@ describe('run raw escape hatch — original params as 3rd arg', () => { describe('toJsonSchema / inputSchema (for the MCP)', () => { it('emits a JSON Schema fragment per coercer', () => { expect(f.uint().toJsonSchema()).toEqual({ type: 'integer', minimum: 1 }); - expect(f.messageId().toJsonSchema()).toEqual({ type: 'integer', not: { const: 0 } }); + expect(f.messageId().toJsonSchema()).toEqual({ type: 'integer', not: { const: 0 }, 'x-role': 'message_id' }); expect(f.int({ min: 0 }).default(1800).toJsonSchema()).toEqual({ type: 'integer', minimum: 0, default: 1800 }); expect(f.string({ allowEmpty: false }).toJsonSchema()).toEqual({ type: 'string', minLength: 1 }); expect(f.bool().toJsonSchema()).toEqual({ type: 'boolean' }); @@ -217,4 +217,44 @@ describe('describe — doc metadata for self-generated docs (D4)', () => { const duration = doc.params.find((p) => p.name === 'duration'); expect(duration).toMatchObject({ type: 'int', required: false, default: 1800, desc: 'seconds; 0 unmutes' }); }); + + it('stamps semantic roles on preset-injected fields (group_id / member-like user_id)', () => { + const doc = spec.describe(); + expect(doc.params.find((p) => p.name === 'group_id')?.role).toBe('group_id'); + // In a group action the user_id is a member of that group → member_id role. + expect(doc.params.find((p) => p.name === 'user_id')?.role).toBe('member_id'); + expect(doc.stream).toBeUndefined(); + }); +}); + +describe('FieldRole — semantic constructors and .role()', () => { + it('semantic constructors coerce like their primitive but carry a role', () => { + expect(f.groupId().doc).toMatchObject({ type: 'uint', role: 'group_id' }); + expect(f.userId().doc).toMatchObject({ type: 'uint', role: 'user_id' }); + expect(f.memberId().doc).toMatchObject({ type: 'uint', role: 'member_id' }); + expect(f.image().doc).toMatchObject({ type: 'string', role: 'image' }); + expect(f.duration().doc).toMatchObject({ type: 'int', role: 'duration' }); + // Coercion is unchanged: a groupId still validates exactly like a uint. + const g = f.groupId().coerce('123', 'group_id'); + expect(g.ok && g.value).toBe(123); + const bad = f.groupId().coerce('0', 'group_id'); + expect(bad.ok).toBe(false); + }); + + it('.role() overrides/stamps a role and survives optional()/default()', () => { + expect(f.uint().role('group_id').doc.role).toBe('group_id'); + expect(f.uint().role('group_id').optional().doc.role).toBe('group_id'); + expect(f.string().role('file').default('').doc.role).toBe('file'); + }); + + it("surfaces role through describe() params and toJsonSchema's x-role", () => { + const spec = defineAction({ + name: 'demo', + params: { gid: f.groupId(), pic: f.image() }, + run: () => okResponse(), + }); + const doc = spec.describe(); + expect(doc.params.find((p) => p.name === 'gid')?.role).toBe('group_id'); + expect(f.groupId().toJsonSchema()).toMatchObject({ 'x-role': 'group_id' }); + }); }); diff --git a/packages/onebot/tests/http-server-content-type.test.ts b/packages/onebot/tests/http-server-content-type.test.ts index 49207745..f3d350ad 100644 --- a/packages/onebot/tests/http-server-content-type.test.ts +++ b/packages/onebot/tests/http-server-content-type.test.ts @@ -18,6 +18,7 @@ function fakeCtx(handleFn: (action: string, params: Record) => const data = handleFn(action, params); return { status: 'ok', retcode: 0, data }; }), + isStreamAction: () => false, } as any, buildLifecycleEvent: vi.fn(() => ({})), buildHeartbeatEvent: vi.fn(() => ({})), diff --git a/packages/onebot/tests/message-parser.test.ts b/packages/onebot/tests/message-parser.test.ts index d35c6e72..42d75b34 100644 --- a/packages/onebot/tests/message-parser.test.ts +++ b/packages/onebot/tests/message-parser.test.ts @@ -326,15 +326,13 @@ describe('parseMessage', () => { }], { bridge, groupId: 123456 }); // The video main file carries real bytes but the server fast-paths it - // (fileExist:true, no uKey) — #145's forceFullOnFastPath re-issues the - // OIDB request with fast-upload disabled, so two packets go out. - expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2); + // (fileExist:true, no uKey). The send trusts that single fast-path + // response — the old forceFullOnFastPath retry was removed (proven + // ineffective, see #145), so exactly ONE OIDB request goes out. + expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1); expect(bridge.sendRawPacket).toHaveBeenNthCalledWith(1, 'OidbSvcTrpcTcp.0x11ea_100', expect.any(Uint8Array)); - expect(bridge.sendRawPacket).toHaveBeenNthCalledWith(2, 'OidbSvcTrpcTcp.0x11ea_100', expect.any(Uint8Array)); const firstReq = protobuf_decode>(bridge.sendRawPacket.mock.calls[0]![1] as Uint8Array); - const secondReq = protobuf_decode>(bridge.sendRawPacket.mock.calls[1]![1] as Uint8Array); expect(firstReq.body.upload.tryFastUploadCompleted).toBe(true); - expect(secondReq.body.upload.tryFastUploadCompleted ?? false).toBe(false); expect(protoElems).toHaveLength(1); expect(protoElems[0].commonElem?.serviceType).toBe(48); expect(protoElems[0].commonElem?.businessType).toBe(21); diff --git a/packages/onebot/tests/network-bootstrap-meta.test.ts b/packages/onebot/tests/network-bootstrap-meta.test.ts index 9befb0c6..cb26808c 100644 --- a/packages/onebot/tests/network-bootstrap-meta.test.ts +++ b/packages/onebot/tests/network-bootstrap-meta.test.ts @@ -68,7 +68,7 @@ import type { JsonObject, WsClientNetwork, WsServerNetwork } from '../src/types' function ctx(): NetworkAdapterContext { return { uin: '10001', - api: { processRequest: async () => '' } as never, + api: { processStreamRequest: async () => {} } as never, buildLifecycleEvent: (sub) => ({ post_type: 'meta_event', meta_event_type: 'lifecycle', sub_type: sub }), buildHeartbeatEvent: () => ({ post_type: 'meta_event', meta_event_type: 'heartbeat', interval: 5000 }), }; diff --git a/packages/onebot/tests/network-manager.test.ts b/packages/onebot/tests/network-manager.test.ts index a7de011f..758ed382 100644 --- a/packages/onebot/tests/network-manager.test.ts +++ b/packages/onebot/tests/network-manager.test.ts @@ -52,7 +52,7 @@ class FakeAdapter extends IOneBotNetworkAdapter { const NULL_CTX: NetworkAdapterContext = { uin: '10001', - api: { handle: async () => ({ status: 'failed', retcode: 0, data: null }), processRequest: async () => '' } as never, + api: { handle: async () => ({ status: 'failed', retcode: 0, data: null }), processStreamRequest: async () => {} } as never, buildLifecycleEvent: () => ({}), buildHeartbeatEvent: () => ({}), }; diff --git a/packages/onebot/tests/qzone-actions.test.ts b/packages/onebot/tests/qzone-actions.test.ts new file mode 100644 index 00000000..1289a988 --- /dev/null +++ b/packages/onebot/tests/qzone-actions.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import { ApiHandler, type ApiActionContext } from '../src/api-handler'; + +function makeHandler(qzone: Record): ApiHandler { + const bridge = { apis: { qzone } } as unknown as BridgeInterface; + const ctx = { bridge } as ApiActionContext; + return new ApiHandler(ctx); +} + +describe('qzone actions', () => { + it('send_qzone_msg uploads images and publishes richvals joined with tab', async () => { + const uploadImageFromSource = vi.fn() + .mockResolvedValueOnce({ richval: 'RV1', url: 'URL1' }) + .mockResolvedValueOnce({ richval: 'RV2', url: 'URL2' }); + const publish = vi.fn().mockResolvedValue({ tid: 'T1', time: 1 }); + const handler = makeHandler({ uploadImageFromSource, publish }); + + const res = await handler.handle('send_qzone_msg', { + content: 'hello', + images: ['file:///a.jpg', 'file:///b.jpg'], + }); + + expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { tid: 'T1', time: 1 } }); + expect(uploadImageFromSource).toHaveBeenNthCalledWith(1, 'file:///a.jpg'); + expect(uploadImageFromSource).toHaveBeenNthCalledWith(2, 'file:///b.jpg'); + expect(publish).toHaveBeenCalledWith('hello', 1, 'RV1\tRV2'); + }); + + it('comment_qzone uploads images and comments direct urls joined with tab', async () => { + const uploadImageFromSource = vi.fn() + .mockResolvedValueOnce({ richval: 'RV1', url: 'URL1' }) + .mockResolvedValueOnce({ richval: 'RV2', url: 'URL2' }); + const comment = vi.fn().mockResolvedValue({ comment_id: 'C1' }); + const handler = makeHandler({ uploadImageFromSource, comment }); + + const res = await handler.handle('comment_qzone', { + tid: 'T1', + content: 'nice', + target_uin: 20002, + images: ['file:///a.jpg', 'file:///b.jpg'], + }); + + expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { comment_id: 'C1' } }); + expect(comment).toHaveBeenCalledWith('T1', 'nice', 20002, 1, 'URL1\tURL2'); + }); + + it('returns a clear error and skips publish when one image upload fails', async () => { + const uploadImageFromSource = vi.fn() + .mockResolvedValueOnce({ richval: 'RV1', url: 'URL1' }) + .mockRejectedValueOnce(new Error('network down')); + const publish = vi.fn(); + const handler = makeHandler({ uploadImageFromSource, publish }); + + const res = await handler.handle('send_qzone_msg', { + content: 'hello', + images: ['file:///a.jpg', 'file:///b.jpg'], + }); + + expect(res).toMatchObject({ status: 'failed', retcode: 1200 }); + expect(res.wording).toContain('第 2 张图片上传失败: network down'); + expect(publish).not.toHaveBeenCalled(); + }); + +}); diff --git a/packages/onebot/tests/stream-download.test.ts b/packages/onebot/tests/stream-download.test.ts new file mode 100644 index 00000000..0fff50e1 --- /dev/null +++ b/packages/onebot/tests/stream-download.test.ts @@ -0,0 +1,116 @@ +// Phase 3 — download stream actions (#163): server-push multi-frame. +import { describe, it, expect, afterEach } from 'vitest'; +import fs from 'fs'; +import path from 'path'; +import { ApiHandler, type ApiActionContext } from '../src/api-handler'; +import { __test } from '../src/actions/stream-download'; +import { STREAM_DOWNLOAD_DIR, __test as fileTest } from '../src/actions/stream-file'; + +const parse = (frames: string[]) => frames.map((f) => JSON.parse(f) as Record); + +afterEach(() => { + fileTest.cleanDir(STREAM_DOWNLOAD_DIR); +}); + +describe('test_download_stream', () => { + it('pushes 10 data frames then a data_complete terminal', async () => { + const h = new ApiHandler({} as ApiActionContext); + expect(h.isStreamAction('test_download_stream')).toBe(true); + + const frames: string[] = []; + await h.processStreamRequest(JSON.stringify({ action: 'test_download_stream', params: {}, echo: 'T' }), (j) => frames.push(j)); + + const got = parse(frames); + expect(got).toHaveLength(11); + expect(got[0]).toMatchObject({ stream: 'stream-action', echo: 'T', data: { type: 'stream', data_type: 'data_chunk', data: 'Index-> 1' } }); + expect(got[9]).toMatchObject({ data: { data: 'Index-> 10' } }); + expect(got[10]).toMatchObject({ status: 'ok', data: { type: 'response', data_type: 'data_complete', data: 'Stream transmission complete' } }); + }); + + it('error=true streams the 10 frames then terminates with an error frame', async () => { + const h = new ApiHandler({} as ApiActionContext); + const frames: string[] = []; + await h.processStreamRequest(JSON.stringify({ action: 'test_download_stream', params: { error: true } }), (j) => frames.push(j)); + const got = parse(frames); + expect(got).toHaveLength(11); + expect(got[9]).toMatchObject({ data: { data_type: 'data_chunk' } }); + expect(got[10]).toMatchObject({ status: 'failed', data: { type: 'error' } }); + }); +}); + +describe('download_file_stream (local, fenced)', () => { + it('streams file_info → file_chunk* → file_complete and reassembles exactly', async () => { + fs.mkdirSync(STREAM_DOWNLOAD_DIR, { recursive: true }); + const fp = path.join(STREAM_DOWNLOAD_DIR, 'dl.bin'); + const content = Buffer.from('snowluma stream download payload '.repeat(4000)); // ~128 KB → multiple 64 KB chunks + fs.writeFileSync(fp, content); + + const h = new ApiHandler({} as ApiActionContext); + const frames: string[] = []; + await h.processStreamRequest(JSON.stringify({ action: 'download_file_stream', params: { file: fp, chunk_size: 65536 }, echo: 'D' }), (j) => frames.push(j)); + + const got = parse(frames); + expect(got[0]).toMatchObject({ stream: 'stream-action', echo: 'D', data: { data_type: 'file_info', file_name: 'dl.bin', file_size: content.length, chunk_size: 65536 } }); + + const chunks = got.filter((p) => p.data?.data_type === 'file_chunk'); + expect(chunks.length).toBeGreaterThan(1); + // indices are sequential and progress is monotonic + chunks.forEach((c, i) => expect(c.data.index).toBe(i)); + + const last = got[got.length - 1]; + expect(last).toMatchObject({ status: 'ok', data: { type: 'response', data_type: 'file_complete', total_bytes: content.length, total_chunks: chunks.length } }); + + const reassembled = Buffer.concat(chunks.map((c) => Buffer.from(c.data.data, 'base64'))); + expect(reassembled.equals(content)).toBe(true); + }); + + it('refuses an arbitrary local path outside the stream root [arbitrary-read guard]', async () => { + await expect(__test.resolveDownload('/etc/passwd', {} as ApiActionContext, 'auto', 65536)).rejects.toThrow(/restricted to the stream temp/i); + await expect(__test.resolveDownload('file:///etc/hosts', {} as ApiActionContext, 'auto', 65536)).rejects.toThrow(/restricted to the stream temp/i); + + // and end-to-end the dispatch surfaces it as an error frame, not a leak + const h = new ApiHandler({} as ApiActionContext); + const frames: string[] = []; + await h.processStreamRequest(JSON.stringify({ action: 'download_file_stream', params: { file: '/etc/passwd' } }), (j) => frames.push(j)); + expect(parse(frames).at(-1)).toMatchObject({ status: 'failed', data: { type: 'error' } }); + }); +}); + +describe('SSRF guard', () => { + it('classifies private/loopback/link-local addresses (incl. normalized v4-mapped IPv6) [C2]', () => { + const priv = [ + '127.0.0.1', '10.0.0.5', '192.168.1.1', '172.16.0.1', '169.254.1.1', '0.0.0.0', '100.64.0.1', + '::1', 'fc00::1', 'fd12::1', 'fe80::1', + '::ffff:127.0.0.1', '::ffff:169.254.169.254', // dotted v4-mapped + '::ffff:7f00:1', '::ffff:a9fe:a9fe', // hex v4-mapped (what `new URL` produces) + '::127.0.0.1', '64:ff9b::7f00:1', // v4-compatible, NAT64-mapped loopback + ]; + for (const ip of priv) expect(__test.isPrivateIp(ip), ip).toBe(true); + for (const ip of ['8.8.8.8', '1.1.1.1', '203.0.113.4', '2606:4700:4700::1111', '::ffff:8.8.8.8']) { + expect(__test.isPrivateIp(ip), ip).toBe(false); + } + }); + + it('rejects non-http(s) schemes and private/loopback URL targets — incl. v4-mapped literals [C1/C2]', async () => { + await expect(__test.assertSafeUrl('ftp://example.com/x')).rejects.toThrow(/http\(s\)/i); + await expect(__test.assertSafeUrl('file:///etc/passwd')).rejects.toThrow(/http\(s\)/i); + await expect(__test.assertSafeUrl('http://127.0.0.1/x')).rejects.toThrow(/private\/loopback/i); + await expect(__test.assertSafeUrl('http://[::1]/x')).rejects.toThrow(/private\/loopback/i); + // v4-mapped IPv6 literal → new URL normalizes hostname to hex; must still block + await expect(__test.assertSafeUrl('http://[::ffff:127.0.0.1]/x')).rejects.toThrow(/private\/loopback/i); + await expect(__test.assertSafeUrl('http://[::ffff:169.254.169.254]/meta')).rejects.toThrow(/private\/loopback/i); + await expect(__test.assertSafeUrl('http://localhost/x')).rejects.toThrow(/private/i); + }); +}); + +describe('cached image/voice id resolution reaches the media branch [M1]', () => { + it('a cache id flows past the local check to getImageInfo (then SSRF-guards its URL)', async () => { + const ctx = { + getImageInfo: async () => ({ url: 'http://10.0.0.7/cached.png', file: '', file_name: 'cached.png', file_size: '9' }), + getRecordInfo: async () => null, + } as unknown as ApiActionContext; + // 'abc123.image' is not a real file → must NOT be rejected as "restricted"; + // it reaches getImageInfo, whose private URL is then blocked by the SSRF guard. + await expect(__test.resolveDownload('abc123.image', ctx, 'image', 65536)).rejects.toThrow(/private/i); + }); +}); diff --git a/packages/onebot/tests/stream-file.test.ts b/packages/onebot/tests/stream-file.test.ts new file mode 100644 index 00000000..a20d688e --- /dev/null +++ b/packages/onebot/tests/stream-file.test.ts @@ -0,0 +1,184 @@ +// Phase 2 — upload_file_stream + clean_stream_temp_file (#163). +import { describe, it, expect, afterEach } from 'vitest'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { createHash } from 'crypto'; +import { ApiHandler, type ApiActionContext } from '../src/api-handler'; +import { __test, STREAM_UPLOAD_DIR } from '../src/actions/stream-file'; + +const { handleUpload, cleanDir, uploads } = __test; +type UP = Parameters[0]; + +const b64 = (s: string | Buffer): string => Buffer.from(s).toString('base64'); + +// Fill every optional key so the direct handleUpload calls satisfy the type. +function mk(p: Partial & { stream_id: string }): UP { + return { + chunk_data: undefined, chunk_index: undefined, total_chunks: undefined, + file_size: undefined, expected_sha256: undefined, is_complete: undefined, + filename: undefined, reset: undefined, verify_only: undefined, + file_retention: 0, ...p, + }; +} + +afterEach(() => { + cleanDir(STREAM_UPLOAD_DIR); + uploads.clear(); +}); + +describe('upload_file_stream', () => { + it('reassembles ordered chunks into a file with correct content + sha256', async () => { + const id = 'up-ordered'; + const parts = ['hello ', 'streamed ', 'world!']; + const full = parts.join(''); + const sha = createHash('sha256').update(full).digest('hex'); + + let r = await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 0, chunk_data: b64(parts[0]) })); + expect(r.data).toMatchObject({ type: 'stream', status: 'chunk_received', received_chunks: 1, total_chunks: 3 }); + await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 1, chunk_data: b64(parts[1]) })); + r = await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 2, chunk_data: b64(parts[2]) })); + expect(r.data).toMatchObject({ received_chunks: 3 }); + + r = await handleUpload(mk({ stream_id: id, total_chunks: 3, is_complete: true, expected_sha256: sha })); + const data = r.data as Record; + expect(data).toMatchObject({ type: 'response', status: 'file_complete', total_chunks: 3, file_size: full.length, sha256: sha }); + expect(fs.readFileSync(String(data.file_path), 'utf8')).toBe(full); + // state dropped after completion, chunk dir gone + expect(uploads.has(id)).toBe(false); + }); + + it('accepts out-of-order chunks and dedups repeats idempotently', async () => { + const id = 'up-ooo'; + await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 2, chunk_data: b64('C') })); + await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 0, chunk_data: b64('A') })); + // duplicate of an already-received chunk → no double count + const dup = await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 2, chunk_data: b64('C') })); + expect(dup.data).toMatchObject({ received_chunks: 2 }); + await handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 1, chunk_data: b64('B') })); + const r = await handleUpload(mk({ stream_id: id, total_chunks: 3, is_complete: true })); + expect(fs.readFileSync(String((r.data as Record).file_path), 'utf8')).toBe('ABC'); + }); + + it('rejects completion with a missing chunk', async () => { + const id = 'up-missing'; + await handleUpload(mk({ stream_id: id, total_chunks: 2, chunk_index: 0, chunk_data: b64('only') })); + await expect(handleUpload(mk({ stream_id: id, total_chunks: 2, is_complete: true }))).rejects.toThrow(/missing/i); + }); + + it('rejects a sha256 mismatch and deletes the bad file', async () => { + const id = 'up-sha'; + await handleUpload(mk({ stream_id: id, total_chunks: 1, chunk_index: 0, chunk_data: b64('data') })); + await expect(handleUpload(mk({ stream_id: id, total_chunks: 1, is_complete: true, expected_sha256: 'deadbeef' }))).rejects.toThrow(/sha256 mismatch/i); + // A failed completion keeps the stream (client can reset+retry; the reaper + // reclaims it if abandoned), but the corrupt merged file is deleted. + expect(uploads.has(id)).toBe(true); + expect(fs.existsSync(uploads.get(id)!.finalPath)).toBe(false); + }); + + it('rejects an out-of-range chunk index and a new stream without total_chunks', async () => { + await expect(handleUpload(mk({ stream_id: 'up-oob', total_chunks: 2, chunk_index: 5, chunk_data: b64('x') }))).rejects.toThrow(/invalid chunk index/i); + await expect(handleUpload(mk({ stream_id: 'up-no-total', chunk_index: 0, chunk_data: b64('x') }))).rejects.toThrow(/total_chunks required/i); + }); + + it('reset discards the stream (surfaced as an error, NapCat parity)', async () => { + const id = 'up-reset'; + await handleUpload(mk({ stream_id: id, total_chunks: 2, chunk_index: 0, chunk_data: b64('x') })); + expect(uploads.has(id)).toBe(true); + await expect(handleUpload(mk({ stream_id: id, reset: true }))).rejects.toThrow(/reset/i); + expect(uploads.has(id)).toBe(false); + }); + + it('verify_only reports status, errors on unknown stream', async () => { + const id = 'up-verify'; + await handleUpload(mk({ stream_id: id, total_chunks: 4, chunk_index: 0, chunk_data: b64('x') })); + const r = await handleUpload(mk({ stream_id: id, verify_only: true })); + expect(r.data).toMatchObject({ type: 'stream', received_chunks: 1, total_chunks: 4 }); + await expect(handleUpload(mk({ stream_id: 'nope', verify_only: true }))).rejects.toThrow(/not found/i); + }); + + it('strips path separators from filename (no temp-dir escape)', async () => { + const id = 'up-escape'; + await handleUpload(mk({ stream_id: id, total_chunks: 1, chunk_index: 0, chunk_data: b64('x'), filename: '../../evil.sh' })); + const r = await handleUpload(mk({ stream_id: id, total_chunks: 1, is_complete: true })); + const fp = String((r.data as Record).file_path); + expect(path.dirname(fp)).toBe(STREAM_UPLOAD_DIR); + expect(fp).not.toContain('..'); + }); +}); + +describe('upload_file_stream hardening', () => { + it('rejects path-traversal / illegal stream_id (no escape) [C1]', async () => { + const evil = ['../../../../tmp/victim', '..', 'a/b', 'a\\b', 'with space', 'x'.repeat(129), '', 'dot.dot']; + for (const id of evil) { + await expect(handleUpload(mk({ stream_id: id, total_chunks: 1, chunk_index: 0, chunk_data: b64('x') }))).rejects.toThrow(/invalid stream_id/i); + } + // a benign traversal attempt left nothing outside the upload dir + expect(fs.existsSync('/tmp/victim')).toBe(false); + // validateStreamId accepts UUID-ish ids, rejects separators/dots + expect(() => __test.validateStreamId('uuid-1234-5678_ABCdef')).not.toThrow(); + expect(() => __test.validateStreamId('../x')).toThrow(); + expect(() => __test.validateStreamId('a/b')).toThrow(); + expect(() => __test.validateStreamId('a.b')).toThrow(); + }); + + it('rejects total_chunks above the cap [M1]', async () => { + await expect(handleUpload(mk({ stream_id: 'up-huge', total_chunks: __test.MAX_CHUNKS + 1, chunk_index: 0, chunk_data: b64('x') }))).rejects.toThrow(/total_chunks exceeds limit/i); + }); + + it('caps concurrent streams [M2]', async () => { + for (let i = 0; i < __test.MAX_CONCURRENT_STREAMS; i++) { + await handleUpload(mk({ stream_id: `cap-${i}`, total_chunks: 2, chunk_index: 0, chunk_data: b64('x') })); + } + await expect(handleUpload(mk({ stream_id: 'cap-overflow', total_chunks: 2, chunk_index: 0, chunk_data: b64('x') }))).rejects.toThrow(/too many concurrent/i); + }); + + it('counts a concurrently-duplicated chunk index only once [M3]', async () => { + const id = 'up-race'; + const [a, b] = await Promise.all([ + handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 0, chunk_data: b64('A') })), + handleUpload(mk({ stream_id: id, total_chunks: 3, chunk_index: 0, chunk_data: b64('A') })), + ]); + expect(a.status).toBe('ok'); + expect(b.status).toBe('ok'); + expect(uploads.get(id)!.written.size).toBe(1); + expect(uploads.get(id)!.claimed.size).toBe(1); + }); +}); + +describe('upload_file_stream via the streaming dispatch', () => { + it('emits a stream-marked chunk frame end-to-end', async () => { + const h = new ApiHandler({} as ApiActionContext); + expect(h.isStreamAction('upload_file_stream')).toBe(true); + + const frames: string[] = []; + await h.processStreamRequest( + JSON.stringify({ action: 'upload_file_stream', params: { stream_id: 'ws-up', total_chunks: 1, chunk_index: 0, chunk_data: b64('hi') }, echo: 'E' }), + (j) => frames.push(j), + ); + expect(frames).toHaveLength(1); + expect(JSON.parse(frames[0])).toMatchObject({ + status: 'ok', stream: 'stream-action', echo: 'E', + data: { type: 'stream', status: 'chunk_received', received_chunks: 1, total_chunks: 1 }, + }); + }); +}); + +describe('clean_stream_temp_file', () => { + it('removes stream temp entries and is scoped to the stream dirs', async () => { + fs.mkdirSync(STREAM_UPLOAD_DIR, { recursive: true }); + const f1 = path.join(STREAM_UPLOAD_DIR, 'leftover.bin'); + fs.writeFileSync(f1, 'junk'); + // an unrelated temp file outside the stream dir must survive + const outside = path.join(os.tmpdir(), `snowluma-stream-unrelated-${Date.now()}.txt`); + fs.writeFileSync(outside, 'keep'); + + const h = new ApiHandler({} as ApiActionContext); + const r = await h.handle('clean_stream_temp_file', {}); + expect(r.status).toBe('ok'); + expect((r.data as Record).message).toBe('success'); + expect(fs.existsSync(f1)).toBe(false); + expect(fs.existsSync(outside)).toBe(true); + fs.rmSync(outside, { force: true }); + }); +}); diff --git a/packages/onebot/tests/streaming.test.ts b/packages/onebot/tests/streaming.test.ts new file mode 100644 index 00000000..6f4818bc --- /dev/null +++ b/packages/onebot/tests/streaming.test.ts @@ -0,0 +1,167 @@ +// Phase 1 — Stream API plumbing (#163). Verifies the dispatch seam: +// defineStreamAction registers a streaming handler, processStreamRequest +// emits N intermediate frames + a terminal frame (all echo-tagged, marked +// `stream:'stream-action'`), normal actions stay single-frame, and failures +// terminate with an error frame. Wire format mirrors NapCat's Stream API. +import { describe, it, expect } from 'vitest'; +import { ApiHandler, type ApiActionContext } from '../src/api-handler'; +import { defineAction, defineStreamAction, f } from '../src/action-kit'; +import { okResponse, failedResponse } from '../src/types'; +import { wrapStreamFrame, wrapStreamTerminal, STREAM_MARK } from '../src/streaming'; + +function newHandler(): ApiHandler { + // The real register* run lazily (handlers capture ctx, never call it at + // registration), so an empty ctx is enough to exercise the dispatch seam. + return new ApiHandler({} as ApiActionContext); +} + +const parse = (frames: string[]) => frames.map((f) => JSON.parse(f) as Record); + +describe('Stream API plumbing', () => { + it('streams N intermediate frames + a terminal frame, all echo-tagged', async () => { + const h = newHandler(); + defineStreamAction({ + name: 'demo_stream', + params: { n: f.uint() }, + run: async (p, _ctx, _raw, sink) => { + for (let i = 0; i < p.n; i++) await sink.send({ type: 'stream', index: i }); + return okResponse({ type: 'response', total: p.n }); + }, + }).register(h, {} as ApiActionContext); + + const frames: string[] = []; + await h.processStreamRequest( + JSON.stringify({ action: 'demo_stream', params: { n: 2 }, echo: 'e1' }), + (j) => frames.push(j), + ); + + const got = parse(frames); + expect(got).toHaveLength(3); + expect(got[0]).toMatchObject({ status: 'ok', retcode: 0, stream: STREAM_MARK, echo: 'e1', data: { type: 'stream', index: 0 } }); + expect(got[1]).toMatchObject({ stream: STREAM_MARK, echo: 'e1', data: { type: 'stream', index: 1 } }); + expect(got[2]).toMatchObject({ status: 'ok', stream: STREAM_MARK, echo: 'e1', data: { type: 'response', total: 2 } }); + }); + + it('marks the action as a stream action; normal actions are not', () => { + const h = newHandler(); + defineStreamAction({ name: 'demo_stream', params: {}, run: () => okResponse({ type: 'response' }) }).register(h, {} as ApiActionContext); + defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }).register(h, {} as ApiActionContext); + expect(h.isStreamAction('demo_stream')).toBe(true); + expect(h.isStreamAction('demo_normal')).toBe(false); + expect(h.isStreamAction('nope')).toBe(false); + }); + + it('a normal action through processStreamRequest emits exactly one un-marked frame', async () => { + const h = newHandler(); + defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }).register(h, {} as ApiActionContext); + + const frames: string[] = []; + await h.processStreamRequest(JSON.stringify({ action: 'demo_normal', params: {}, echo: 'e2' }), (j) => frames.push(j)); + + expect(frames).toHaveLength(1); + const r = parse(frames)[0]; + expect(r).toMatchObject({ status: 'ok', echo: 'e2', data: { ok: true } }); + expect(r.stream).toBeUndefined(); + }); + + it('a throwing stream action terminates with a single error frame', async () => { + const h = newHandler(); + defineStreamAction({ + name: 'demo_boom', + params: {}, + run: async () => { throw new Error('boom'); }, + }).register(h, {} as ApiActionContext); + + const frames: string[] = []; + await h.processStreamRequest(JSON.stringify({ action: 'demo_boom', params: {}, echo: 'e3' }), (j) => frames.push(j)); + + expect(frames).toHaveLength(1); + expect(parse(frames)[0]).toMatchObject({ + status: 'failed', stream: STREAM_MARK, echo: 'e3', wording: 'boom', data: { type: 'error', data_type: 'error' }, + }); + }); + + it('emits already-sent frames before the terminal error when a stream throws mid-way', async () => { + const h = newHandler(); + defineStreamAction({ + name: 'demo_partial', + params: {}, + run: async (_p, _ctx, _raw, sink) => { + await sink.send({ type: 'stream', index: 0 }); + throw new Error('mid'); + }, + }).register(h, {} as ApiActionContext); + + const frames: string[] = []; + await h.processStreamRequest(JSON.stringify({ action: 'demo_partial', params: {} }), (j) => frames.push(j)); + + const got = parse(frames); + expect(got).toHaveLength(2); + expect(got[0]).toMatchObject({ stream: STREAM_MARK, data: { type: 'stream', index: 0 } }); + expect(got[1]).toMatchObject({ status: 'failed', data: { type: 'error' } }); + }); + + it('stream param validation fails terminate with an error frame', async () => { + const h = newHandler(); + defineStreamAction({ name: 'demo_needs', params: { n: f.uint() }, run: () => okResponse({ type: 'response' }) }).register(h, {} as ApiActionContext); + + const frames: string[] = []; + await h.processStreamRequest(JSON.stringify({ action: 'demo_needs', params: {} }), (j) => frames.push(j)); + expect(frames).toHaveLength(1); + expect(parse(frames)[0]).toMatchObject({ status: 'failed', stream: STREAM_MARK, data: { type: 'error' } }); + }); + + it('aborts a stream when isAlive turns false (client disconnect)', async () => { + const h = newHandler(); + let sent = 0; + defineStreamAction({ + name: 'demo_abort', + params: {}, + run: async (_p, _ctx, _raw, sink) => { + for (let i = 0; i < 5; i++) { await sink.send({ type: 'stream', index: i }); sent++; } + return okResponse({ type: 'response' }); + }, + }).register(h, {} as ApiActionContext); + + const frames: string[] = []; + let alive = true; + await h.processStreamRequest( + JSON.stringify({ action: 'demo_abort', params: {} }), + (j) => { frames.push(j); if (frames.length >= 2) alive = false; }, + () => alive, + ); + + expect(sent).toBeLessThan(5); // loop aborted once the client "left" + const got = parse(frames); + expect(got[got.length - 1]).toMatchObject({ status: 'failed', data: { type: 'error' } }); + }); + + it('wrapStreamFrame / wrapStreamTerminal shape (NapCat message+wording mirror)', () => { + expect(wrapStreamFrame({ type: 'stream', x: 1 }, 'e')).toEqual({ + status: 'ok', retcode: 0, data: { type: 'stream', x: 1 }, message: '', wording: '', stream: STREAM_MARK, echo: 'e', + }); + // no echo → no echo key + expect(wrapStreamFrame({ type: 'stream' }, undefined)).toEqual({ + status: 'ok', retcode: 0, data: { type: 'stream' }, message: '', wording: '', stream: STREAM_MARK, + }); + // failed terminal → data normalised to an error packet; reason in BOTH message + wording + expect(wrapStreamTerminal(failedResponse(1404, 'nope'), 'e')).toMatchObject({ + status: 'failed', retcode: 1404, message: 'nope', wording: 'nope', stream: STREAM_MARK, echo: 'e', + data: { type: 'error', data_type: 'error' }, + }); + // ok terminal → data passes through, message/wording empty + expect(wrapStreamTerminal(okResponse({ type: 'response', a: 1 }), undefined)).toMatchObject({ + status: 'ok', stream: STREAM_MARK, message: '', data: { type: 'response', a: 1 }, + }); + }); + + it('malformed stream requests emit one bad-request frame', async () => { + const h = newHandler(); + const frames: string[] = []; + await h.processStreamRequest('not json', (j) => frames.push(j)); + await h.processStreamRequest('', (j) => frames.push(j)); + await h.processStreamRequest(JSON.stringify({ params: {} }), (j) => frames.push(j)); // no action + expect(frames).toHaveLength(3); + for (const f of parse(frames)) expect(f).toMatchObject({ status: 'failed' }); + }); +}); diff --git a/packages/onebot/tests/ws-client-stale-close.test.ts b/packages/onebot/tests/ws-client-stale-close.test.ts index 18d2108d..49407ca2 100644 --- a/packages/onebot/tests/ws-client-stale-close.test.ts +++ b/packages/onebot/tests/ws-client-stale-close.test.ts @@ -70,7 +70,7 @@ import type { WsClientNetwork } from '../src/types'; function ctx(): NetworkAdapterContext { return { uin: '10001', - api: { processRequest: async () => '' } as never, + api: { processStreamRequest: async () => {} } as never, buildLifecycleEvent: () => ({}), buildHeartbeatEvent: () => ({}), }; diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index fad0accc..1dbdc780 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proto-defs", - "version": "1.10.4", + "version": "1.11.0", "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).", @@ -91,6 +91,10 @@ "./oidb-actions/ocr": { "types": "./src/oidb-actions/ocr.ts", "default": "./src/oidb-actions/ocr.ts" + }, + "./oidb-actions/sys-faces": { + "types": "./src/oidb-actions/sys-faces.ts", + "default": "./src/oidb-actions/sys-faces.ts" } }, "scripts": { diff --git a/packages/proto-defs/src/oidb-actions/base.ts b/packages/proto-defs/src/oidb-actions/base.ts index dd7b0e18..d5a27a32 100644 --- a/packages/proto-defs/src/oidb-actions/base.ts +++ b/packages/proto-defs/src/oidb-actions/base.ts @@ -109,7 +109,10 @@ export interface OidbRenameMember { body?: pb<3, OidbRenameMemberBody>; } export interface OidbRenameGroupBody { - targetName?: pb<1, string>; + // The group name lives at tag 3, NOT tag 1 — tags 1/2 make the server reject + // 0x89a_15 with OIDB error 1006 (#173). Confirmed against Lagrange's + // OidbSvcTrpcTcp0x89A_15Body (ProtoMember(3) TargetName). + targetName?: pb<3, string>; } export interface OidbRenameGroup { groupUin?: pb<1, uint_32>; diff --git a/packages/proto-defs/src/oidb-actions/sys-faces.ts b/packages/proto-defs/src/oidb-actions/sys-faces.ts new file mode 100644 index 00000000..b291c5f3 --- /dev/null +++ b/packages/proto-defs/src/oidb-actions/sys-faces.ts @@ -0,0 +1,61 @@ +// 0x9154_1 — system face / emoji catalog (sysface) protobuf shapes. +// +// Mirrors Lagrange.Core's FetchFullSysFacesService response: one round-trip +// returns every pack — common faces, "big"/super animated faces, and the +// magic-face pack. Each emoji carries its `aniSticker*` metadata, which the +// send path uses to pick the right wire encoding for a face id (classic +// FaceElem vs CommonElem 37/33). See protocol/oidb-services/sys-faces. + +import type { pb, pb_repeated, int_32 } from '@snowluma/proton'; + +export interface OidbFaceResourceUrl { + baseUrl?: pb<1, string>; + advUrl?: pb<2, string>; +} + +export interface OidbFaceEmoji { + qSid?: pb<1, string>; + qDes?: pb<2, string>; + emCode?: pb<3, string>; + qCid?: pb<4, int_32>; + aniStickerType?: pb<5, int_32>; + aniStickerPackId?: pb<6, int_32>; + aniStickerId?: pb<7, int_32>; + url?: pb<8, OidbFaceResourceUrl>; + emojiNameAlias?: pb_repeated<9, string>; + unknown10?: pb<10, int_32>; + aniStickerWidth?: pb<13, int_32>; + aniStickerHeight?: pb<14, int_32>; +} + +export interface OidbFaceEmojiList { + emojiPackName?: pb<1, string>; + emojiDetail?: pb_repeated<2, OidbFaceEmoji>; +} + +export interface OidbFaceContent { + emojiList?: pb_repeated<1, OidbFaceEmojiList>; + resourceUrl?: pb<2, OidbFaceResourceUrl>; +} + +export interface OidbFaceMagicContentList { + emojiList?: pb_repeated<2, OidbFaceEmoji>; +} + +export interface OidbFaceMagicContent { + field1?: pb<1, OidbFaceMagicContentList>; + resourceUrl?: pb<2, OidbFaceResourceUrl>; +} + +export interface OidbFetchSysFacesReq { + field1?: pb<1, int_32>; + field2?: pb<2, int_32>; + field3?: pb<3, string>; +} + +export interface OidbFetchSysFacesResp { + field1?: pb<1, int_32>; + commonFace?: pb<2, OidbFaceContent>; + specialBigFace?: pb<3, OidbFaceContent>; + specialMagicFace?: pb<4, OidbFaceMagicContent>; +} diff --git a/packages/proto-defs/src/ptt-trans.ts b/packages/proto-defs/src/ptt-trans.ts index 3290d581..b5460317 100644 --- a/packages/proto-defs/src/ptt-trans.ts +++ b/packages/proto-defs/src/ptt-trans.ts @@ -1,4 +1,4 @@ -import type { pb, uint_32, uint_64, bytes } from '@snowluma/proton'; +import type { pb, uint_32, uint_64 } from '@snowluma/proton'; /** * Voice-to-text (语音转文字) request/response protobufs for the @@ -28,7 +28,11 @@ export interface C2CPttTransItem { size?: pb<6, uint_32>; // element 45405 (bytes) format?: pb<7, uint_32>; // element 45907 (voice codec) eventType?: pb<8, uint_32>; // element 45921 - md5?: pb<9, bytes>; // element 45406 (raw 16-byte md5) + // QQ NT (EncodeC2CPtt) hex-encodes the md5 to a 32-char lowercase string + // before sending it (verified in wrapper.linux.node: field 9 = sub_7A02D80 + // = bytes→hex). Sending the raw 16 bytes makes the server reject with + // errCode -1079. So this is a hex STRING, not bytes. + md5?: pb<9, string>; // element 45406 (32-char lowercase hex) } export interface GroupPttTransItem { @@ -36,7 +40,7 @@ export interface GroupPttTransItem { senderUin?: pb<2, uint_64>; groupUin?: pb<3, uint_64>; fileId?: pb<4, uint_32>; // element 45903 (group ptt numeric file id) - md5?: pb<5, bytes>; // element 45406 + md5?: pb<5, string>; // element 45406 (32-char lowercase hex, see C2C note) duration?: pb<6, uint_32>; // element 45906 size?: pb<7, uint_32>; // element 45405 format?: pb<8, uint_32>; // element 45907 diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 2c62f7ee..741295bb 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/protocol", - "version": "1.10.4", + "version": "1.11.0", "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/'`.", diff --git a/packages/protocol/src/element-builder.ts b/packages/protocol/src/element-builder.ts index dbc36354..2b28ffb7 100644 --- a/packages/protocol/src/element-builder.ts +++ b/packages/protocol/src/element-builder.ts @@ -2,11 +2,12 @@ import type { MarkdownData, MentionExtraSend, } from '@snowluma/proto-defs/action'; -import type { Elem, GroupFileExtra, MarketFacePbReserve } from '@snowluma/proto-defs/element'; +import type { Elem, GroupFileExtra, MarketFacePbReserve, QFaceExtra, QSmallFaceExtra } 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 { sysFaceStore } from './sys-face-store'; import type { MessageElement } from './events'; import { uploadImageMsgInfo } from './highway/image-upload'; import { hexToBytes } from './highway/pipeline'; @@ -39,10 +40,45 @@ function makeTextElem(text: string): ProtoElem { }; } -function makeFaceElem(faceId: number): ProtoElem { - return { - face: { index: faceId }, - }; +// QQ-NT splits face ids across three wire encodings. The legacy FaceElem only +// renders classic small faces; newer "super" / animated faces sent that way are +// silently remapped by the server (e.g. 424→168, issue #168). The split is +// data-driven off the system-face catalog (0x9154_1, see sys-face-store): +// super (animated, aniSticker not pack (1,1)) → CommonElem 37 + QFaceExtra +// other id ≥ 260 → CommonElem 33 + QSmallFaceExtra +// classic id < 260 → legacy FaceElem +function makeFaceElem(faceId: number, ctx?: SendContext): ProtoElem { + // Keep the catalog warm so subsequent super-face sends are classified even if + // this one raced ahead of the first fetch. + if (ctx) sysFaceStore.ensureWarm(ctx.bridge); + + const wire = sysFaceStore.classify(faceId); + if (wire.kind === 'super') { + return { + commonElem: { + serviceType: 37, + pbElem: protobuf_encode({ + packId: wire.packId, + stickerId: wire.stickerId, + qsid: faceId, + sourceType: 1, + stickerType: wire.stickerType, + randomType: 1, + }), + businessType: 1, + }, + }; + } + if (wire.kind === 'small') { + return { + commonElem: { + serviceType: 33, + pbElem: protobuf_encode({ faceId, preview: '', preview2: '' }), + businessType: 1, + }, + }; + } + return { face: { index: faceId } }; } function resolveMentionDisplay(ctx: SendContext | undefined, targetUin: number): string { @@ -414,7 +450,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte break; case 'face': - if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId)); + if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId, ctx)); break; case 'mface': diff --git a/packages/protocol/src/highway/ffmpeg-addon.ts b/packages/protocol/src/highway/ffmpeg-addon.ts index c4b69ce5..52de8d3a 100644 --- a/packages/protocol/src/highway/ffmpeg-addon.ts +++ b/packages/protocol/src/highway/ffmpeg-addon.ts @@ -152,3 +152,64 @@ export async function encodeSilk(inputFile: string, tempDir: string): Promise; + +/** Default ceiling on the transcoded output read into memory for base64. SILK→ + * WAV/FLAC is a decompressing direction, so cap it even though real voices are + * tiny. Generous; overridable via deps. */ +const DEFAULT_MAX_AUDIO_OUTPUT = 256 * 1024 * 1024; // 256 MiB + +/** + * Transcode raw audio bytes (a QQ voice SILK/AMR) to `format`, returning the + * result as base64 + byte size. Writes the input + output to temp files (the + * native addon is file-based), always cleaning them up. `deps` injects a fake + * addon / tmp dir for tests. Throws on an unsupported format or a failed + * conversion (e.g. the binary lacks SILK decode). + */ +export async function convertAudioBytes( + bytes: Uint8Array, + format: string, + deps: { addon?: AudioConvertAddon; tmpDir?: string; maxOutputBytes?: number } = {}, +): Promise<{ base64: string; size: number }> { + if (!isAudioOutFormat(format)) { + throw new Error(`unsupported out_format: ${format} (expected one of ${AUDIO_OUT_FORMATS.join(', ')})`); + } + const addon = deps.addon ?? getFFmpegAddon(); + const maxOut = deps.maxOutputBytes ?? DEFAULT_MAX_AUDIO_OUTPUT; + const dir = deps.tmpDir ?? path.join(os.tmpdir(), 'snowluma-rec'); + fs.mkdirSync(dir, { recursive: true }); + const id = crypto.randomBytes(8).toString('hex'); + const inPath = path.join(dir, `${id}.in`); + const outPath = path.join(dir, `${id}.${format}`); + try { + await fs.promises.writeFile(inPath, bytes); + const res = await addon.convertFile(inPath, outPath, format); + if (!res?.success || !fs.existsSync(outPath)) throw new Error('audio conversion failed'); + // Bound the output before reading it into memory (decompressing direction). + const stat = await fs.promises.stat(outPath); + if (stat.size > maxOut) throw new Error(`converted audio too large: ${stat.size} > ${maxOut}`); + const out = await fs.promises.readFile(outPath); + return { base64: out.toString('base64'), size: out.length }; + } finally { + // Await cleanup so no temp file lingers past the call (the bytes are + // already in memory by now). allSettled → a missing file never throws. + await Promise.allSettled([ + fs.promises.rm(inPath, { force: true }), + fs.promises.rm(outPath, { force: true }), + ]); + } +} diff --git a/packages/protocol/src/highway/pipeline.ts b/packages/protocol/src/highway/pipeline.ts index 7692a194..a2e20e80 100644 --- a/packages/protocol/src/highway/pipeline.ts +++ b/packages/protocol/src/highway/pipeline.ts @@ -51,16 +51,6 @@ export interface MediaSubFileUpload { * Omit if the caller guarantees bytes always exist (e.g. video thumb * always has FALLBACK_THUMB bytes). */ fastOnlyError?: string; - /** When true and the server fast-paths THIS sub-file (returns no uKey) - * even though we hold real bytes for it, `runNtv2Upload` re-issues the - * whole OIDB request with `tryFastUploadCompleted: false` to force a - * fresh full upload. Video sets this on the main file: group/c2c video - * resources expire server-side, so a fast-path hit can reference a - * stale object the receiver renders as "资源已过期". The thumb leaves - * this off — a cached thumb is harmless and not worth re-pushing the - * whole (potentially 100 MB) main video for. Forwarding paths carry no - * bytes (`bytes.length === 0`), so this never fires for them. */ - forceFullOnFastPath?: boolean; } export interface NtV2UploadParams { @@ -195,24 +185,18 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise => { + // Run whatever PUTs the given `upload` response asks for. + const runPuts = async (upload: NTV2UploadRespBody): Promise => { let didPut = false; - let staleFastPath = false; for (const sub of uploads) { const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source]; const uKey = target?.uKey ?? ''; // No uKey: the server fast-pathed this sub-file (or msgInfo is absent - // entirely). When we actually hold bytes for it, the server is - // reusing a cached resource — surface it, and flag a stale fast-path - // when the caller asked us to distrust it for this sub-file. + // entirely) — it already holds (or claims to hold) the resource, so + // there are no bytes to push for it. if (!uKey || !upload.msgInfo) { if (!uKey && upload.msgInfo && sub.bytes.length > 0) { log.debug('%s fast-upload hit for sub=%s (server reusing cached resource)', label, String(sub.source)); - if (sub.forceFullOnFastPath) staleFastPath = true; } continue; } @@ -241,26 +225,19 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise; + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, _p: Params): OidbFetchSysFacesReq => ({ + field1: 0, + field2: 7, + field3: '0', + }); + + export const deserialize = (_ctx: Deps, body: OidbFetchSysFacesResp): SysFacePackEntry[] => { + const packs: SysFacePackEntry[] = []; + + // common + special-big share the same content shape. + for (const content of [body.commonFace, body.specialBigFace]) { + for (const list of content?.emojiList ?? []) { + packs.push({ + packName: list.emojiPackName ?? '', + emojis: (list.emojiDetail ?? []).map(emojiToEntry), + }); + } + } + + // Magic faces arrive as a single un-named bundle — Lagrange tags it + // "MagicFace" client-side, so we match for parity. + const magicEmojis = body.specialMagicFace?.field1?.emojiList ?? []; + if (magicEmojis.length > 0) { + packs.push({ packName: 'MagicFace', emojis: magicEmojis.map(emojiToEntry) }); + } + + return packs; + }; + + 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, FetchSysFaces, params); +} + +/** Walk a pack list to find an emoji by its numeric face ID, or null. */ +export function findFaceEntity(packs: SysFacePackEntry[], faceId: number): SysFaceEntry | null { + const idStr = String(faceId); + for (const pack of packs) { + for (const emoji of pack.emojis) { + if (emoji.qSid === idStr) return emoji; + } + } + return null; +} + +/** True when `faceId` is an animated "super face" — has both aniStickerType + * and aniStickerPackId set, and is NOT the (1,1) pack (the regular static + * emojis). Matches Lagrange's `GetUniqueSuperQSids` filter. Super faces ride + * CommonElem serviceType 37 (QFaceExtra); the (1,1) ones ride serviceType 33. */ +export function isSuperFaceEntry(emoji: SysFaceEntry): boolean { + if (emoji.aniStickerType == null || emoji.aniStickerPackId == null) return false; + return !(emoji.aniStickerType === 1 && emoji.aniStickerPackId === 1); +} + +export function isSuperFaceId(packs: SysFacePackEntry[], faceId: number): boolean { + const emoji = findFaceEntity(packs, faceId); + return emoji !== null && isSuperFaceEntry(emoji); +} diff --git a/packages/protocol/src/sys-face-store.ts b/packages/protocol/src/sys-face-store.ts new file mode 100644 index 00000000..5e92853e --- /dev/null +++ b/packages/protocol/src/sys-face-store.ts @@ -0,0 +1,93 @@ +// Process-wide cache of QQ's system-face catalog (fetched once via 0x9154_1), +// used by the send path to pick a face id's wire encoding. The catalog is the +// same for every account, so a single shared store is fetched lazily and reused. +// +// `classify` is synchronous (the element builder is sync); a face sent before +// the catalog is warm falls back to an id-range guess. `ensureWarm` kicks off +// the one-shot fetch — call it proactively at login so the first super-face +// send is already classified. + +import { createLogger } from '@snowluma/common/logger'; +import { + FetchSysFaces, + isSuperFaceEntry, + type SysFaceEntry, + type SysFacePackEntry, +} from './oidb-services/sys-faces/fetch-sys-faces'; +import type { OidbSender } from './oidb-service'; + +const log = createLogger('SysFace'); + +/** Wire encoding a face id maps to. `classic` → legacy FaceElem; `small` → + * CommonElem serviceType 33 (QSmallFaceExtra); `super` → CommonElem + * serviceType 37 (QFaceExtra) for animated/super faces. */ +export type FaceWire = + | { kind: 'classic' } + | { kind: 'small' } + | { kind: 'super'; packId: string; stickerId: string; stickerType: number }; + +/** Pure classification: a super face (per the catalog entry) → `super` with its + * pack/sticker ids; otherwise an id-range guess (`< 260` = classic, else + * small). Used both warm (entry from the catalog) and cold (entry undefined). */ +export function faceWireFor(entry: SysFaceEntry | null | undefined, faceId: number): FaceWire { + if (entry && isSuperFaceEntry(entry)) { + return { + kind: 'super', + packId: String(entry.aniStickerPackId ?? 1), + stickerId: String(entry.aniStickerId ?? 0), + stickerType: entry.aniStickerType ?? 0, + }; + } + return faceId < 260 ? { kind: 'classic' } : { kind: 'small' }; +} + +const RETRY_COOLDOWN_MS = 30_000; + +class SysFaceStore { + private byId: Map | null = null; + private inflight: Promise | null = null; + private lastFailedAt = 0; + + /** Index a fetched catalog (also used by tests to seed without a network). */ + load(packs: SysFacePackEntry[]): void { + this.byId = buildIndex(packs); + } + + /** Synchronous classification. Falls back to an id-range guess when the + * catalog isn't warm yet or the id is unknown. */ + classify(faceId: number): FaceWire { + return faceWireFor(this.byId?.get(String(faceId)), faceId); + } + + /** Fire-and-forget one-shot warm. Coalesces concurrent callers; backs off + * briefly after a failure so a flaky fetch isn't hammered per message. */ + ensureWarm(sender: OidbSender): void { + if (this.byId || this.inflight) return; + if (Date.now() - this.lastFailedAt < RETRY_COOLDOWN_MS) return; + this.inflight = FetchSysFaces.invoke(sender) + .then((packs) => { + this.load(packs); + log.info('system face catalog loaded: %d faces', this.byId?.size ?? 0); + }) + .catch((err) => { + this.lastFailedAt = Date.now(); + log.warn('failed to load system face catalog: %s', err instanceof Error ? err.message : String(err)); + }) + .finally(() => { + this.inflight = null; + }); + } +} + +function buildIndex(packs: SysFacePackEntry[]): Map { + const map = new Map(); + for (const pack of packs) { + for (const emoji of pack.emojis) { + if (emoji.qSid) map.set(emoji.qSid, emoji); + } + } + return map; +} + +/** Shared, process-wide catalog (the face set is account-independent). */ +export const sysFaceStore = new SysFaceStore(); diff --git a/packages/protocol/src/web/qzone.ts b/packages/protocol/src/web/qzone.ts index 468be817..a17a066c 100644 --- a/packages/protocol/src/web/qzone.ts +++ b/packages/protocol/src/web/qzone.ts @@ -80,6 +80,55 @@ export function parseQzoneJson(text: string): T { return JSON.parse(s.slice(start, end + 1)) as T; } +function assertRichParams(richType?: number, richval?: string): void { + const hasRichType = richType !== undefined; + const hasRichval = richval !== undefined && richval.trim() !== ''; + if (hasRichType !== hasRichval) { + throw new Error('richType and richval must be provided together'); + } + if (richType !== undefined && (!Number.isInteger(richType) || richType < 1)) { + throw new Error('richType must be a positive integer'); + } +} + +function normalizeQzoneImageBase64(input: string): string { + let text = input.trim(); + if (/^base64:\/\//i.test(text)) { + text = text.slice(9).trim(); + } + if (/^data:/i.test(text)) { + const comma = text.indexOf(','); + if (comma === -1) { + throw new Error('imageBase64 data URI is missing base64 payload'); + } + text = text.slice(comma + 1); + } + + const compact = text.replace(/ /g, '+').replace(/[\r\n\t]/g, ''); + if (!compact) { + throw new Error('imageBase64 is required'); + } + if (!/^[A-Za-z0-9+/]+={0,2}$/.test(compact)) { + throw new Error('imageBase64 is not valid base64'); + } + const firstPadding = compact.indexOf('='); + if (firstPadding !== -1 && /[^=]/.test(compact.slice(firstPadding))) { + throw new Error('imageBase64 is not valid base64'); + } + + const unpadded = compact.replace(/=+$/, ''); + const remainder = unpadded.length % 4; + if (remainder === 1) { + throw new Error('imageBase64 is not valid base64'); + } + const base64 = unpadded + '='.repeat((4 - remainder) % 4); + const bytes = Buffer.from(base64, 'base64'); + if (bytes.length === 0) { + throw new Error('imageBase64 is empty'); + } + return base64; +} + /** Pick the largest picture URL variant a feed picture offers. */ function pickPicUrl(pic: RawPic): string | undefined { return pic.url3 || pic.url2 || pic.url1 || pic.smallurl || undefined; @@ -331,10 +380,14 @@ export interface QzonePublishResult { } /** - * Publish a text-only 说说 via taotao.qzone.qq.com's emotion_cgi_publish_v6 - * CGI (proxied through h5.qzone.qq.com). POSTs a form-urlencoded body with + * Publish a 说说 via taotao.qzone.qq.com's emotion_cgi_publish_v6 CGI + * (proxied through h5.qzone.qq.com). POSTs a form-urlencoded body with * `g_tk` in the query, on the bot's own space (`hostUin`). * + * `richType` / `richval`: for image posts, set `richType=1` and pass the + * richval string(s) from {@link uploadQzoneImage} (multi-image: join with + * `\t`). Omit both for text-only posts. + * * Errors PROPAGATE: a transport failure, a non-zero Qzone `code` (its error * envelope, e.g. content rejected / rate-limited), or a success body that * carries no `tid` all throw — we never report a publish as succeeded @@ -344,6 +397,8 @@ export async function publishQzoneMsg( cookieObject: Record, hostUin: string, content: string, + richType?: number, + richval?: string, ): Promise { if (!cookieObject || typeof cookieObject !== 'object') { throw new Error('cookieObject is required'); @@ -351,6 +406,7 @@ export async function publishQzoneMsg( if (!content) { throw new Error('content is required'); } + assertRichParams(richType, richval); const bkn = getBknFromCookie(cookieObject); const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=${bkn}`; @@ -358,8 +414,8 @@ export async function publishQzoneMsg( syn_tweet_verson: '1', paramstr: '1', pic_template: '', - richtype: '', - richval: '', + richtype: richType !== undefined ? String(richType) : '', + richval: richval ?? '', special_url: '', subrichtype: '', con: content, @@ -546,6 +602,172 @@ export async function setQzoneLike( } } +// ─────────────── 上传图片 (upload image) — cgi_upload_image ─────────────── +// Uploads an image to Qzone's hosting and returns metadata for use in +// publish/comment. The image is POSTed as base64 to up.qzone.qq.com +// (bypassing the h5 proxy — the upload CGI is NOT behind +// h5.qzone.qq.com/proxy). Body is form-urlencoded with `base64=1` and the +// base64 payload in `picfile`. Response is a JSONP wrapper (parsed with the +// shared tolerant parser) carrying `albumid`, `lloc`, `height`, `width`, +// `type`, and `url`. The `richval` (for publish's richval param) is +// constructed as `,albumid,lloc,sloc,type,height,width,,height,width` — the +// double height/width mirrors the PHP impl. WRITE OP — rate-limit (though +// upload itself is not风控'd like publish, batching huge uploads is impolite). +// Confirmed against php-qzone/qzone.class.php:97-172. + +interface RawUploadImageResponse { + code?: number; + subcode?: number; + message?: string; + data?: { + albumid?: string; + lloc?: string; + url?: string; + type?: number; + height?: number; + width?: number; + }; +} + +/** Result of uploading an image to Qzone. */ +export interface QzoneUploadImageResult { + [key: string]: JsonValue; + /** Richval string for publish's `richval` param (multi-image: join with `\t`). */ + richval: string; + /** Direct URL to the uploaded image. */ + url: string; + albumid: string; + lloc: string; + type: number; + width: number; + height: number; +} + +/** + * Upload an image from a source (file:// / http:// / base64://) to Qzone + * hosting. Loads the image via {@link loadBinarySource}, converts to base64, + * and uploads via {@link uploadQzoneImage}. + * + * `source` supports: + * - `file://` local file path + * - `http://` or `https://` remote URL + * - `base64://` base64-encoded data (with or without data-URI prefix) + * + * Errors PROPAGATE from both the load step and the upload step. + */ +export async function uploadQzoneImageFromSource( + cookieObject: Record, + hostUin: string, + source: string, +): Promise { + if (/^base64:\/\//i.test(source)) { + return uploadQzoneImage(cookieObject, hostUin, source); + } + // Import loadBinarySource at function level to avoid circular deps + const { loadBinarySource } = await import('../highway/utils'); + const loaded = await loadBinarySource(source, 'qzone-image'); + const base64 = Buffer.from(loaded.bytes).toString('base64'); + return uploadQzoneImage(cookieObject, hostUin, base64); +} + +/** + * Upload an image (as base64) to Qzone hosting via up.qzone.qq.com's + * cgi_upload_image CGI. Returns metadata including the `richval` string + * (for use in {@link publishQzoneMsg}'s richval param) and the direct URL. + * Multi-image publish: call this once per image and join the richval strings + * with `\t`. + * + * `imageBase64` is the raw base64-encoded image bytes; a data-URI prefix is + * tolerated and stripped. Errors PROPAGATE: invalid base64, a transport + * failure, a non-zero Qzone `code`/`subcode`, or a success body missing + * required fields all throw. + */ +export async function uploadQzoneImage( + cookieObject: Record, + hostUin: string, + imageBase64: string, +): Promise { + if (!cookieObject || typeof cookieObject !== 'object') { + throw new Error('cookieObject is required'); + } + if (!imageBase64) { + throw new Error('imageBase64 is required'); + } + const base64 = normalizeQzoneImageBase64(imageBase64); + + const skey = cookieObject['skey'] || ''; + const pskey = cookieObject['p_skey'] || ''; + const bkn = getBknFromCookie(cookieObject); + + const url = `https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${bkn}`; + const body = new URLSearchParams({ + filename: 'filename', + uin: hostUin, + skey, + zzpaneluin: hostUin, + p_uin: hostUin, + p_skey: pskey, + uploadtype: '1', + albumtype: '7', + exttype: '0', + refer: 'shuoshuo', + output_type: 'jsonhtml', + charset: 'utf-8', + output_charset: 'utf-8', + upload_hd: '1', + hd_width: '2048', + hd_height: '10000', + hd_quality: '96', + backUrls: `http://upbak.photo.qzone.qq.com/cgi-bin/upload/cgi_upload_image,http://119.147.64.75/cgi-bin/upload/cgi_upload_image&url=https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${bkn}`, + base64: '1', + jsonhtml_callback: 'callback', + picfile: base64, + qzreferrer: `https://user.qzone.qq.com/${hostUin}/main`, + }).toString(); + + const text = await RequestUtil.HttpGetText(url, 'POST', body, { + Cookie: cookieToString(cookieObject), + 'Content-Type': 'application/x-www-form-urlencoded', + }); + + // Response is `` — slice + // from the first `{` to the last `}` (same as parseQzoneJson, but the + // wrapper shape differs slightly). + let jsonText = text.trim(); + const callbackStart = jsonText.indexOf('callback'); + if (callbackStart !== -1) { + jsonText = jsonText.slice(callbackStart); + } + const data = parseQzoneJson(jsonText); + + if (typeof data.code === 'number' && data.code !== 0) { + log.warn('uploadQzoneImage: non-zero code (uin=%s) code=%d msg=%s', hostUin, data.code, data.message); + throw new Error(`qzone upload image failed: code=${data.code} ${data.message ?? ''}`.trim()); + } + if (typeof data.subcode === 'number' && data.subcode !== 0) { + log.warn('uploadQzoneImage: non-zero subcode (uin=%s) subcode=%d msg=%s', hostUin, data.subcode, data.message); + throw new Error(`qzone upload image failed: subcode=${data.subcode} ${data.message ?? ''}`.trim()); + } + if (!data.data || !data.data.albumid || !data.data.lloc || !data.data.url) { + log.warn('uploadQzoneImage: missing required fields in response (uin=%s)', hostUin); + throw new Error('上传图片失败:响应缺少必要字段'); + } + + const { albumid, lloc, url: imageUrl, type, height, width } = data.data; + const sloc = lloc; // lloc and sloc are identical in the wire format + const richval = `,${albumid},${lloc},${sloc},${type ?? 0},${height ?? 0},${width ?? 0},,${height ?? 0},${width ?? 0}`; + + return { + richval, + url: imageUrl, + albumid, + lloc, + type: type ?? 0, + width: width ?? 0, + height: height ?? 0, + }; +} + // ─────────────── 评论说说 (comment) — emotion_cgi_re_feeds ─────────────── // Posts a comment on a 说说 owned by `hostUin`, as the bot (`selfUin`). Same // form-POST mechanics + param family (paramstr/richtype/richval) as @@ -576,7 +798,15 @@ export interface QzoneCommentResult { /** * Comment on a 说说 (`tid`, owned by `hostUin`) as the bot (`selfUin`) via - * taotao.qzone.qq.com's emotion_cgi_re_feeds CGI (proxied through h5.qzone). + * taotao.qzone.qq.com's emotion_cgi_re_feeds CGI (proxied through + * h5.qzone.qq.com, matching php-qzone's working request). + * + * `richType` / `richval`: for image comments, set `richType=1` and pass the + * direct image URL from {@link uploadQzoneImage}'s `url` field (NOT the + * richval string — comment uses the direct URL, unlike publish which uses + * richval). Multi-image comments use direct URLs joined with `\t`. Omit both + * for text-only comments. + * * Resolves with the new comment id (best-effort) on success; THROWS on a * transport failure or a non-zero Qzone `code`/`subcode` (e.g. comments * disabled, no permission, or auth failure). @@ -587,6 +817,8 @@ export async function commentQzoneMsg( hostUin: string, tid: string, content: string, + richType?: number, + richval?: string, ): Promise { if (!cookieObject || typeof cookieObject !== 'object') { throw new Error('cookieObject is required'); @@ -597,6 +829,7 @@ export async function commentQzoneMsg( if (!content) { throw new Error('content is required'); } + assertRichParams(richType, richval); const bkn = getBknFromCookie(cookieObject); const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_re_feeds?g_tk=${bkn}`; @@ -606,14 +839,14 @@ export async function commentQzoneMsg( inCharset: 'utf-8', outCharset: 'utf-8', hostUin, - format: 'fs', + format: 'json', ref: 'feeds', topicId: `${hostUin}_${tid}__1`, feedsType: '100', private: '0', paramstr: '1', - richtype: '', - richval: '', + richtype: richType !== undefined ? String(richType) : '', + richval: richval ?? '', isSignIn: '', uin: selfUin, content, diff --git a/packages/protocol/tests/highway/audio-transcode.test.ts b/packages/protocol/tests/highway/audio-transcode.test.ts new file mode 100644 index 00000000..0fd975e6 --- /dev/null +++ b/packages/protocol/tests/highway/audio-transcode.test.ts @@ -0,0 +1,67 @@ +import { afterAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'fs'; +import os from 'os'; +import path from 'path'; +import { AUDIO_OUT_FORMATS, convertAudioBytes, isAudioOutFormat } from '@snowluma/protocol/highway/ffmpeg-addon'; + +// convertAudioBytes is the pure (#165) transcode seam: write input → addon +// convertFile → read output as base64 → always clean up temp files. The native +// addon is file-based and can't run in CI, so a fake addon stands in. + +const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'sl-audio-test-')); +afterAll(() => rmSync(tmpDir, { recursive: true, force: true })); + +/** Fake addon: writes deterministic bytes to the output path and reports ok. */ +const fakeOk = { + convertFile: async (_in: string, out: string, _fmt: string) => { + writeFileSync(out, Buffer.from('WAVDATA')); // stand-in converted payload + return { success: true }; + }, +}; + +describe('isAudioOutFormat / AUDIO_OUT_FORMATS', () => { + it('accepts exactly NapCat\'s allowlist', () => { + expect([...AUDIO_OUT_FORMATS]).toEqual(['mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac']); + expect(isAudioOutFormat('wav')).toBe(true); + expect(isAudioOutFormat('WAV')).toBe(false); // case-sensitive + expect(isAudioOutFormat('opus')).toBe(false); + expect(isAudioOutFormat('')).toBe(false); + }); +}); + +describe('convertAudioBytes', () => { + it('transcodes and returns base64 + size of the addon output', async () => { + const r = await convertAudioBytes(new Uint8Array([1, 2, 3]), 'wav', { addon: fakeOk, tmpDir }); + expect(Buffer.from(r.base64, 'base64').toString()).toBe('WAVDATA'); + expect(r.size).toBe('WAVDATA'.length); + }); + + it('rejects an unsupported format before touching the addon', async () => { + let called = false; + const spy = { convertFile: async () => { called = true; return { success: true }; } }; + await expect(convertAudioBytes(new Uint8Array([1]), 'opus', { addon: spy, tmpDir })).rejects.toThrow(/unsupported out_format/); + expect(called).toBe(false); + }); + + it('throws and cleans up when the addon reports failure', async () => { + const fakeFail = { convertFile: async () => ({ success: false }) }; + await expect(convertAudioBytes(new Uint8Array([9]), 'mp3', { addon: fakeFail, tmpDir })).rejects.toThrow(/conversion failed/); + // no leftover temp files for this run + const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.mp3') || n.endsWith('.in')); + expect(leftover).toEqual([]); + }); + + it('rejects (and cleans up) when the output exceeds the cap', async () => { + await expect( + convertAudioBytes(new Uint8Array([1]), 'wav', { addon: fakeOk, tmpDir, maxOutputBytes: 3 }), + ).rejects.toThrow(/too large/); + const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.wav') || n.endsWith('.in')); + expect(leftover).toEqual([]); + }); + + it('cleans up the temp input + output on success too', async () => { + await convertAudioBytes(new Uint8Array([4, 5]), 'flac', { addon: fakeOk, tmpDir }); + const leftover = readdirSync(tmpDir).filter((n) => n.endsWith('.flac') || n.endsWith('.in')); + expect(leftover).toEqual([]); + }); +}); diff --git a/packages/protocol/tests/sys-faces.test.ts b/packages/protocol/tests/sys-faces.test.ts new file mode 100644 index 00000000..6a92661a --- /dev/null +++ b/packages/protocol/tests/sys-faces.test.ts @@ -0,0 +1,104 @@ +import { describe, it, expect } from 'vitest'; +import { protobuf_decode } from '@snowluma/proton'; +import type { QFaceExtra, QSmallFaceExtra } from '@snowluma/proto-defs/element'; +import { + FetchSysFaces, + findFaceEntity, + isSuperFaceEntry, + isSuperFaceId, + type SysFaceEntry, + type SysFacePackEntry, +} from '../src/oidb-services/sys-faces/fetch-sys-faces'; +import { faceWireFor, sysFaceStore } from '../src/sys-face-store'; +import { buildSendElems } from '../src/element-builder'; + +function entry(qSid: string, aniStickerType: number | null, aniStickerPackId: number | null, aniStickerId: number | null): SysFaceEntry { + return { + qSid, qDes: '', emCode: '', qCid: null, + aniStickerType, aniStickerPackId, aniStickerId, + url: null, emojiNameAlias: [], aniStickerWidth: null, aniStickerHeight: null, + }; +} + +// 392 is a real non-(1,1) super face; 424 is a real (1,1) "new small" face. +const CATALOG: SysFacePackEntry[] = [ + { packName: '经典', emojis: [entry('14', null, null, null)] }, + { packName: '超级表情', emojis: [ + entry('392', 3, 2, 38), // super → CommonElem 37 + entry('424', 1, 1, 52), // (1,1) → small → CommonElem 33 + entry('358', 2, 1, 33), // super (packId 1 but type 2) → CommonElem 37 + ] }, +]; + +describe('isSuperFaceEntry / isSuperFaceId — the (1,1) rule', () => { + it('treats only non-(1,1) aniSticker faces as super', () => { + expect(isSuperFaceEntry(entry('x', 3, 2, 1))).toBe(true); + expect(isSuperFaceEntry(entry('x', 2, 1, 1))).toBe(true); // type≠1 + expect(isSuperFaceEntry(entry('x', 1, 2, 1))).toBe(true); // pack≠1 + expect(isSuperFaceEntry(entry('x', 1, 1, 52))).toBe(false); // the (1,1) pack + expect(isSuperFaceEntry(entry('x', null, null, null))).toBe(false); // not aniSticker + }); + + it('isSuperFaceId walks the packs by id', () => { + expect(isSuperFaceId(CATALOG, 392)).toBe(true); + expect(isSuperFaceId(CATALOG, 424)).toBe(false); + expect(isSuperFaceId(CATALOG, 14)).toBe(false); + expect(isSuperFaceId(CATALOG, 99999)).toBe(false); // unknown + }); + + it('findFaceEntity returns the matching emoji or null', () => { + expect(findFaceEntity(CATALOG, 392)?.qSid).toBe('392'); + expect(findFaceEntity(CATALOG, 99999)).toBeNull(); + }); +}); + +describe('faceWireFor — classification', () => { + it('super face → super wire with pack/sticker ids', () => { + expect(faceWireFor(entry('392', 3, 2, 38), 392)).toEqual({ + kind: 'super', packId: '2', stickerId: '38', stickerType: 3, + }); + }); + it('(1,1) face → small/classic by id range, not super', () => { + expect(faceWireFor(entry('424', 1, 1, 52), 424)).toEqual({ kind: 'small' }); + }); + it('cold (no catalog entry) → id-range guess', () => { + expect(faceWireFor(undefined, 14)).toEqual({ kind: 'classic' }); // < 260 + expect(faceWireFor(undefined, 424)).toEqual({ kind: 'small' }); // ≥ 260 + expect(faceWireFor(null, 100)).toEqual({ kind: 'classic' }); + }); +}); + +describe('FetchSysFaces.deserialize', () => { + it('flattens common + big + magic packs', () => { + const packs = FetchSysFaces.deserialize({} as never, { + commonFace: { emojiList: [{ emojiPackName: '经典', emojiDetail: [{ qSid: '14' }] }] }, + specialBigFace: { emojiList: [{ emojiPackName: '超级', emojiDetail: [{ qSid: '392', aniStickerType: 3, aniStickerPackId: 2 }] }] }, + specialMagicFace: { field1: { emojiList: [{ qSid: '999' }] } }, + } as never); + expect(packs.map((p) => p.packName)).toEqual(['经典', '超级', 'MagicFace']); + expect(packs[1].emojis[0].aniStickerType).toBe(3); + }); +}); + +describe('makeFaceElem (via buildSendElems) — three-way wire encoding', () => { + const ctx = { bridge: {} as never }; + + it('encodes each face id by its catalog classification', async () => { + sysFaceStore.load(CATALOG); // warm → ensureWarm no-ops, classify uses the catalog + + const [superElem] = await buildSendElems([{ type: 'face', faceId: 392 }], ctx); + expect(superElem.commonElem?.serviceType).toBe(37); + const big = protobuf_decode(superElem.commonElem!.pbElem!); + expect(big.qsid).toBe(392); + expect(big.packId).toBe('2'); + expect(big.stickerId).toBe('38'); + + const [smallElem] = await buildSendElems([{ type: 'face', faceId: 424 }], ctx); + expect(smallElem.commonElem?.serviceType).toBe(33); + const small = protobuf_decode(smallElem.commonElem!.pbElem!); + expect(small.faceId).toBe(424); + + const [classicElem] = await buildSendElems([{ type: 'face', faceId: 14 }], ctx); + expect(classicElem.face?.index).toBe(14); + }); +}); diff --git a/packages/protocol/tests/web/qzone-upload.test.ts b/packages/protocol/tests/web/qzone-upload.test.ts new file mode 100644 index 00000000..2844fa90 --- /dev/null +++ b/packages/protocol/tests/web/qzone-upload.test.ts @@ -0,0 +1,105 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { uploadQzoneImage, uploadQzoneImageFromSource } from '../../src/web/qzone'; +import { RequestUtil } from '../../src/web/request-util'; + +const cookies = { p_skey: 'PSK', skey: 'SK', uin: 'o10000', p_uin: 'o10000' }; +const expectedGtk = (() => { + let h = 5381; + for (const c of 'PSK') h += (h << 5) + c.charCodeAt(0); + return (h & 0x7fffffff).toString(); +})(); + +const successBody = ``; + +describe('qzone / uploadQzoneImage', () => { + afterEach(() => vi.restoreAllMocks()); + + it('POSTs the upload form and returns richval + direct url', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(successBody); + + const out = await uploadQzoneImage(cookies, '10000', 'AQID'); + + expect(out).toEqual({ + richval: ',12345,abc123,abc123,22,800,600,,800,600', + url: 'https://example.qzone.qq.com/image.jpg', + albumid: '12345', + lloc: 'abc123', + type: 22, + width: 600, + height: 800, + }); + + const [url, method, body, headers] = spy.mock.calls[0]!; + expect(url).toBe(`https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image?g_tk=${expectedGtk}`); + expect(method).toBe('POST'); + const h = headers as Record; + expect(h['Content-Type']).toBe('application/x-www-form-urlencoded'); + expect(h.Cookie).toContain('p_skey=PSK'); + expect(h.Cookie).toContain('skey=SK'); + + const form = new URLSearchParams(body as string); + expect(form.get('uin')).toBe('10000'); + expect(form.get('p_uin')).toBe('10000'); + expect(form.get('p_skey')).toBe('PSK'); + expect(form.get('base64')).toBe('1'); + expect(form.get('jsonhtml_callback')).toBe('callback'); + expect(form.get('picfile')).toBe('AQID'); + expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000/main'); + }); + + it('accepts base64:// data-URI sources and strips the prefix before upload', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(successBody); + + await uploadQzoneImageFromSource(cookies, '10000', 'base64://data:image/png;base64,AQID'); + + const form = new URLSearchParams(spy.mock.calls[0]![2] as string); + expect(form.get('picfile')).toBe('AQID'); + }); + + it('defaults optional image metadata to 0 when the upload succeeds without it', async () => { + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue( + 'callback({"code":0,"data":{"albumid":"12345","lloc":"abc123","url":"https://example.qzone.qq.com/image.jpg"}});', + ); + + await expect(uploadQzoneImage(cookies, '10000', 'AQID')).resolves.toMatchObject({ + richval: ',12345,abc123,abc123,0,0,0,,0,0', + type: 0, + width: 0, + height: 0, + }); + }); + + it('rejects invalid base64 before any request', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText'); + + await expect(uploadQzoneImage(cookies, '10000', 'not base64?')).rejects.toThrow('valid base64'); + expect(spy).not.toHaveBeenCalled(); + }); + + it('throws on non-zero code or subcode from Qzone', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText'); + + spy.mockResolvedValueOnce('callback({"code":-1,"message":"upload failed"});'); + await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('code=-1'); + + spy.mockResolvedValueOnce('callback({"code":0,"subcode":-2,"message":"sub failed"});'); + await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('subcode=-2'); + }); + + it('throws when the success response lacks required upload fields', async () => { + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('callback({"code":0,"data":{"albumid":"12345"}});'); + + await expect(uploadQzoneImage(cookies, '10000', 'AQID')).rejects.toThrow('响应缺少必要字段'); + }); +}); diff --git a/packages/protocol/tests/web/qzone.test.ts b/packages/protocol/tests/web/qzone.test.ts index d39ed22b..c58a1fed 100644 --- a/packages/protocol/tests/web/qzone.test.ts +++ b/packages/protocol/tests/web/qzone.test.ts @@ -222,6 +222,19 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => { expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000'); }); + it('threads image richType/richval into the publish form', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue( + '{"code":0,"t1_tid":"NEWTID","t1_time":"1700000000"}', + ); + const richval = ',12345,abc,abc,22,800,600,,800,600\t,12346,def,def,22,640,480,,640,480'; + + await publishQzoneMsg(cookies, '10000', 'with images', 1, richval); + + const form = new URLSearchParams(spy.mock.calls[0]![2] as string); + expect(form.get('richtype')).toBe('1'); + expect(form.get('richval')).toBe(richval); + }); + it('falls back to tid/now for alternate client builds', async () => { vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"tid":"ALT","now":1700000001}'); await expect(publishQzoneMsg(cookies, '10000', 'hi')).resolves.toEqual({ tid: 'ALT', time: 1700000001 }); @@ -233,6 +246,13 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => { expect(spy).not.toHaveBeenCalled(); }); + it('rejects incomplete publish rich params before any request', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText'); + await expect(publishQzoneMsg(cookies, '10000', 'hi', 1)).rejects.toThrow('richType and richval'); + await expect(publishQzoneMsg(cookies, '10000', 'hi', undefined, ',123')).rejects.toThrow('richType and richval'); + expect(spy).not.toHaveBeenCalled(); + }); + it('throws on a non-zero qzone code (rejected/rate-limited)', async () => { vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-10000,"message":"too frequent"}'); await expect(publishQzoneMsg(cookies, '10000', 'hi')).rejects.toThrow('code=-10000'); @@ -378,7 +398,7 @@ describe('qzone / commentQzoneMsg (HTTP layer)', () => { expect(form.get('uin')).toBe('10000'); expect(form.get('hostUin')).toBe('20002'); expect(form.get('content')).toBe('说得好 & 顶'); - expect(form.get('format')).toBe('fs'); + expect(form.get('format')).toBe('json'); // qzreferrer carries the commenter's own space (matches the impls) expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000'); // the re_feeds param family (3/3 impls) the publish sibling also sends @@ -387,6 +407,17 @@ describe('qzone / commentQzoneMsg (HTTP layer)', () => { expect(form.get('paramstr')).toBe('1'); }); + it('threads image direct-url richval into the comment form', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"commentid":987}'); + const richval = 'https://example.qzone.qq.com/a.jpg\thttps://example.qzone.qq.com/b.jpg'; + + await commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'pics', 1, richval); + + const form = new URLSearchParams(spy.mock.calls[0]![2] as string); + expect(form.get('richtype')).toBe('1'); + expect(form.get('richval')).toBe(richval); + }); + it('resolves with empty comment_id on success when the response carries no id (field name varies)', async () => { vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0}'); await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi')).resolves.toEqual({ comment_id: '' }); @@ -404,6 +435,13 @@ describe('qzone / commentQzoneMsg (HTTP layer)', () => { expect(spy).not.toHaveBeenCalled(); }); + it('rejects incomplete comment rich params before any request', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText'); + await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi', 1)).rejects.toThrow('richType and richval'); + await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi', undefined, 'https://example.com/img.jpg')).rejects.toThrow('richType and richval'); + expect(spy).not.toHaveBeenCalled(); + }); + it('throws on a non-zero code (comments disabled / no permission)', async () => { vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-3000,"message":"forbidden"}'); await expect(commentQzoneMsg(cookies, '10000', '20002', 'TIDX', 'hi')).rejects.toThrow('comment failed: code=-3000'); diff --git a/packages/proton/package.json b/packages/proton/package.json index a7803090..11757c82 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proton", - "version": "1.10.4", + "version": "1.11.0", "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/runtime/package.json b/packages/runtime/package.json index eba13724..56018e8f 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/runtime", - "version": "1.10.4", + "version": "1.11.0", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index de032102..167311e2 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.10.4", + "version": "1.11.0", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index 683fb298..ccab21bd 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.10.4", + "version": "1.11.0", "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 b93f90f7..8a9b46f5 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/websocket", - "version": "1.10.4", + "version": "1.11.0", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 633f0645..a577b1eb 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -2,7 +2,7 @@ "license": "SEE LICENSE IN LICENSE", "name": "webui", "private": true, - "version": "1.10.4", + "version": "1.11.0", "type": "module", "scripts": { "dev": "vite", diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index 7e3ade0b..f1a380b3 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -7,6 +7,8 @@ import { LoginPage } from '@/components/pages/login-page'; import { ChangePasswordPage } from '@/components/pages/change-password-page'; import { ConsentPage } from '@/components/pages/consent-page'; import { ApiProvider, createApiClient, useApi, type ApiClient } from '@/lib/api'; +import { DebugTaskProvider } from '@/contexts/DebugTaskContext'; +import { TaskBadge } from '@/components/debug/task-badge'; import type { AgreementsPayload } from '@/lib/api/types'; import { appRouter } from '@/router'; @@ -132,7 +134,10 @@ function AuthBoundary() { return ( - {view} + + {view} + + ); } diff --git a/packages/webui/src/components/debug/action-tester.tsx b/packages/webui/src/components/debug/action-tester.tsx new file mode 100644 index 00000000..fd7916db --- /dev/null +++ b/packages/webui/src/components/debug/action-tester.tsx @@ -0,0 +1,382 @@ +// ActionTester — the debug console's centrepiece. Pick an account + action and +// invoke it; params render as role-driven smart controls (pickers, switches, +// file sources) with a raw-JSON escape hatch. Read-only actions are badged +// green, side-effecting ones amber; destructive ones confirm first. Stream API +// actions invoke over the streaming transport and render frames live (tracked +// in the app-level task registry). Every call lands in localStorage history +// with one-click replay. Responses render in a collapsible JsonTree. +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { motion } from 'motion/react'; +import { AlertTriangle, FlaskConical, History, Loader2, Play, RotateCcw, ShieldCheck, Trash2, Zap } from 'lucide-react'; +import { Select } from '@/components/ui/select'; +import { Textarea } from '@/components/ui/textarea'; +import { Picker } from '@/components/ui/picker'; +import { JsonTree } from '@/components/ui/json-tree'; +import { ParamField } from '@/components/debug/param-field'; +import { Segmented } from '@/components/debug/segmented'; +import { useApi } from '@/lib/api'; +import { useDebugTasks } from '@/contexts/DebugTaskContext'; +import { clearHistory, loadHistory, pushHistory, type InvokeRecord } from '@/lib/debug-history'; +import { cn } from '@/lib/utils'; +import type { DebugActionDoc, DebugStreamFrame, QQInfo } from '@/types'; + +const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] backdrop-blur-sm'; + +// Name patterns for genuinely destructive actions → require a confirm. False +// positives just add one extra click; false negatives skip a confirm — both low +// stakes (the amber banner already warns that any write is real). +const DESTRUCTIVE_RE = /(kick|ban|mute|recall|withdraw|delete|del_|dismiss|disband|leave|quit|remove|revoke)/i; + +function coerceParam(type: string, raw: string): unknown { + if (raw === '') return undefined; + if (/int|uint|number|messageId/i.test(type)) { + const n = Number(raw); + return Number.isFinite(n) ? n : raw; + } + if (type === 'bool' || type === 'boolean') return raw === 'true' || raw === '1'; + if (type === 'message') { + const t = raw.trim(); + if ((t.startsWith('[') && t.endsWith(']')) || (t.startsWith('{') && t.endsWith('}'))) { + try { return JSON.parse(t); } catch { /* fall through to literal */ } + } + return raw; + } + return raw; +} + +function Field({ label, children }: { label: ReactNode; children: ReactNode }) { + return ( + + ); +} + +export function ActionTester({ accounts, docs, presetAction }: { accounts: QQInfo[]; docs: DebugActionDoc[]; presetAction?: { name: string; nonce: number } }) { + const api = useApi(); + const tasks = useDebugTasks(); + + const [uin, setUin] = useState(''); + const [actionName, setActionName] = useState(''); + const [fields, setFields] = useState>({}); + const [paramMode, setParamMode] = useState<'form' | 'json'>('form'); + const [rawJson, setRawJson] = useState('{}'); + const [invoking, setInvoking] = useState(false); + const [result, setResult] = useState(null); + const [frames, setFrames] = useState([]); + const [confirmOpen, setConfirmOpen] = useState(false); + const [history, setHistory] = useState([]); + const [showHistory, setShowHistory] = useState(false); + const streamAbort = useRef(null); + + useEffect(() => { setHistory(loadHistory()); }, []); + useEffect(() => { if (accounts[0] && !uin) setUin(accounts[0].uin); }, [accounts, uin]); + // Prefill from the API browser's 试一下 (nonce lets the same action re-trigger). + useEffect(() => { + if (presetAction) { setActionName(presetAction.name); setParamMode('form'); setResult(null); setFrames([]); setShowHistory(false); } + }, [presetAction]); + + const doc = useMemo(() => docs.find((d) => d.name === actionName), [docs, actionName]); + const effectiveMode = paramMode === 'json' || !doc ? 'json' : 'form'; + const isStream = !!doc?.stream; + const isDestructive = DESTRUCTIVE_RE.test(actionName); + + const actionOptions = useMemo( + () => docs.map((d) => ({ value: d.name, label: d.name, sub: d.summary })), + [docs], + ); + + const buildParams = (): Record | { __error: string } => { + if (effectiveMode === 'json') { + let parsed: unknown; + try { parsed = JSON.parse(rawJson || '{}'); } catch { return { __error: 'params JSON 无效' }; } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return { __error: 'params 必须是对象' }; + return parsed as Record; + } + const out: Record = {}; + if (doc) for (const p of doc.params) { + const v = coerceParam(p.type, fields[p.name] ?? ''); + if (v !== undefined) out[p.name] = v; + } + return out; + }; + + const runInvoke = async () => { + if (!uin) { setResult({ error: '请选择账号' }); return; } + if (!actionName.trim()) { setResult({ error: '请填写 action' }); return; } + const params = buildParams(); + if ('__error' in params) { setResult({ error: params.__error as string }); return; } + + setInvoking(true); + setResult(null); + setFrames([]); + const startedAt = Date.now(); + + if (isStream) { + const ac = new AbortController(); + streamAbort.current = ac; + const taskId = tasks.start({ kind: 'stream', label: `${actionName} @ ${uin}`, progress: undefined, cancel: () => ac.abort() }); + let last: DebugStreamFrame | null = null; + try { + await api.debug.invokeStream(uin, actionName.trim(), params, (frame) => { + last = frame; + setFrames((prev) => [...prev, frame]); + const d = frame.data as { type?: string; progress?: number; transferred?: number; total?: number } | undefined; + if (d && typeof d.progress === 'number') tasks.update(taskId, { progress: d.progress }); + else if (d && typeof d.transferred === 'number' && typeof d.total === 'number' && d.total > 0) tasks.update(taskId, { progress: d.transferred / d.total }); + }, ac.signal); + // A clean success requires the terminal frame (status ok AND the + // NapCat terminal marker data.type==='response') — a stream that closed + // without emitting its terminator must not read as success. + const term = last as DebugStreamFrame | null; + const ok = !!term && term.status === 'ok' && (term.data as { type?: string } | undefined)?.type === 'response'; + setResult(last); + tasks.finish(taskId, ok ? 'done' : 'failed'); + setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok, ms: Date.now() - startedAt, stream: true })); + } catch (e) { + const aborted = ac.signal.aborted; + const msg = e instanceof Error ? e.message : '流式调用失败'; + if (!aborted) setResult({ error: msg }); + tasks.finish(taskId, aborted ? 'canceled' : 'failed', msg); + setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok: false, ms: Date.now() - startedAt, stream: true })); + } finally { + streamAbort.current = null; + setInvoking(false); + } + return; + } + + try { + const res = await api.debug.invoke(uin, actionName.trim(), params); + setResult(res); + setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok: res.status === 'ok', ms: Date.now() - startedAt })); + } catch (e) { + setResult({ error: e instanceof Error ? e.message : '调用失败' }); + setHistory(pushHistory({ at: startedAt, uin, action: actionName.trim(), params, ok: false, ms: Date.now() - startedAt })); + } finally { + setInvoking(false); + } + }; + + const onExecute = () => { + if (isDestructive) { setConfirmOpen(true); return; } + void runInvoke(); + }; + + const replay = (rec: InvokeRecord) => { + setUin(rec.uin); + setActionName(rec.action); + setParamMode('json'); + setRawJson(JSON.stringify(rec.params, null, 2)); + setResult(null); + setFrames([]); + setShowHistory(false); + }; + + const resultFailed = !!result && ('error' in result || result.status === 'failed'); + + return ( +
+ {/* tester */} + +
+
+ +

Action 测试台

+
+ +
+ +
+ + 调用会真实生效(真发消息 / 真踢人等),请谨慎。 +
+ +
+ + + + + { setActionName(v); setResult(null); setFrames([]); }} + options={actionOptions} + placeholder="search action…" + validateRaw={(s) => s.trim().length > 0} + /> + +
+ + {doc && ( +
+ {doc.readOnly + ? 只读·安全 + : 有副作用} + {isStream && 流式} + {doc.summary}{doc.returns ? <> · 返回 {doc.returns} : null} +
+ )} + +
+ 参数 + +
+ + {effectiveMode === 'json' ? ( +