diff --git a/package.json b/package.json index df768a5b..41f47b65 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snowluma-monorepo", - "version": "1.9.12", + "version": "1.9.13", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index f64cdd96..aa8c29ed 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/bridge", - "version": "1.9.12", + "version": "1.9.13", "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/common/package.json b/packages/common/package.json index 23563203..8085b162 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/common", - "version": "1.9.12", + "version": "1.9.13", "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).", @@ -45,10 +45,12 @@ } }, "scripts": { - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "test": "vitest run" }, "devDependencies": { "@types/node": "^24.12.2", - "typescript": "catalog:" + "typescript": "catalog:", + "vitest": "^4.1.4" } } diff --git a/packages/common/src/runtime.ts b/packages/common/src/runtime.ts index d1f5e610..e6eca30b 100644 --- a/packages/common/src/runtime.ts +++ b/packages/common/src/runtime.ts @@ -7,71 +7,102 @@ export interface RuntimeConfig { * the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD. * Defaults to false; the Docker image flips it on in supervisord.conf. */ hookAutoLoad?: boolean; + /** WebUI listener bind address. '0.0.0.0' = all interfaces (default), + * '127.0.0.1' = localhost-only. Listener-level: change needs a restart. */ + webuiHost?: string; + /** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this + * only flips serving on/off. Listener-level: change needs a restart. */ + webuiTls?: { enabled?: boolean }; + /** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY), + * consumed by the WebUI's client-ip resolver. '' = trust nobody. */ + trustProxy?: string; } const CONFIG_DIR = 'config'; const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json'); -const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = { - webuiPort: 5099, - hookAutoLoad: false, -}; +const DEFAULT_WEBUI_PORT = 5099; +const DEFAULT_WEBUI_HOST = '0.0.0.0'; + +/** + * Pure on-disk-object → typed config normalization (defaults + validation, + * no fs / no env). Exported for testing; `loadRuntimeConfig` wraps it. + */ +export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig { + const obj = isObject(parsed) ? parsed : {}; + return { + webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT), + hookAutoLoad: normalizeBool(obj.hookAutoLoad, false), + webuiHost: normalizeHost(obj.webuiHost), + webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false }, + trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '', + }; +} + +/** + * Pure SNOWLUMA_* env → override patch (no fs). Env wins over runtime.json + * (a trusted launcher like SnowLumaDesktop pins these per-launch without + * rewriting the file). Absent vars produce no key. + */ +export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial { + const out: Partial = {}; + + const port = parsePortString(env.SNOWLUMA_WEBUI_PORT); + if (port !== undefined) out.webuiPort = port; + + const host = env.SNOWLUMA_WEBUI_HOST; + if (typeof host === 'string' && host.trim()) out.webuiHost = host.trim(); + + // Present-but-"0"/"off" is a deliberate override (trust nobody), distinct + // from "absent" — so gate on key presence, not truthiness. + const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY; + if (typeof tp === 'string') out.trustProxy = tp; + + return out; +} export function loadRuntimeConfig(): RuntimeConfig { fs.mkdirSync(CONFIG_DIR, { recursive: true }); - const loaded = tryLoadRuntimeConfig(); - let normalized: RuntimeConfig; - if (!loaded) { - saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG); - normalized = { ...DEFAULT_RUNTIME_CONFIG }; - } else { - normalized = { - webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099), - hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false), - }; - if ( - normalized.webuiPort !== loaded.webuiPort - || normalized.hookAutoLoad !== loaded.hookAutoLoad - ) { - saveRuntimeConfig(normalized); - } + const parsed = tryLoadRuntimeConfig(); + const normalized = normalizeRuntimeConfig(parsed ?? {}); + + // Persist when the file is absent or when normalization changed/backfilled + // anything (e.g. an older runtime.json lacking webuiHost/webuiTls). + if (parsed === null || !sameRuntimeConfig(parsed, normalized)) { + saveRuntimeConfig(normalized); } - // SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without - // rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop) - // pick a free port per-launch while CLI/Docker users continue to drive - // it from runtime.json. - const envPort = envPortOverride(); - if (envPort !== undefined) { - normalized = { ...normalized, webuiPort: envPort }; - } - - return normalized; + // Env overrides apply in-memory only — never written back to disk. + return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) }; } -function envPortOverride(): number | undefined { - const raw = process.env.SNOWLUMA_WEBUI_PORT; - if (!raw || typeof raw !== 'string') return undefined; - const n = Number(raw.trim()); - if (!Number.isFinite(n)) return undefined; - const port = Math.trunc(n); - if (port <= 0 || port > 65535) return undefined; - return port; +/** + * Read the persisted config (normalized, no env overrides, no write). For the + * settings panel's GET — shows what's actually saved/editable on disk. + */ +export function readRuntimeConfig(): RuntimeConfig { + return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {}); } -function tryLoadRuntimeConfig(): RuntimeConfig | null { +/** + * Persist a partial update. Merges onto the ON-DISK config (not the env-merged + * runtime view) so an env override (e.g. SNOWLUMA_WEBUI_PORT) is never baked + * into runtime.json. Returns the new persisted config (without env overrides). + */ +export function updateRuntimeConfig(patch: Partial): RuntimeConfig { + fs.mkdirSync(CONFIG_DIR, { recursive: true }); + const onDisk = normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {}); + const next = normalizeRuntimeConfig({ ...onDisk, ...patch }); + saveRuntimeConfig(next); + return next; +} + +function tryLoadRuntimeConfig(): Record | null { if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null; - try { - const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8'); - const parsed = JSON.parse(raw) as unknown; - if (!isObject(parsed)) return null; - - return { - webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099), - hookAutoLoad: normalizeBool(parsed.hookAutoLoad, false), - }; + const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown; + return isObject(parsed) ? parsed : null; } catch { return null; } @@ -81,6 +112,33 @@ function saveRuntimeConfig(config: RuntimeConfig): void { fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8'); } +/** True when the raw on-disk object already matches the normalized config + * on every known field (so we can skip a needless rewrite). */ +function sameRuntimeConfig(parsed: Record, n: RuntimeConfig): boolean { + const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined; + return ( + parsed.webuiPort === n.webuiPort + && parsed.hookAutoLoad === n.hookAutoLoad + && parsed.webuiHost === n.webuiHost + && parsedTls === n.webuiTls?.enabled + && parsed.trustProxy === n.trustProxy + ); +} + +function parsePortString(raw: unknown): number | undefined { + if (typeof raw !== 'string' || !raw.trim()) return undefined; + const n = Number(raw.trim()); + if (!Number.isFinite(n)) return undefined; + const port = Math.trunc(n); + if (port <= 0 || port > 65535) return undefined; + return port; +} + +function normalizeHost(value: unknown): string { + if (typeof value === 'string' && value.trim()) return value.trim(); + return DEFAULT_WEBUI_HOST; +} + function normalizePort(value: unknown, fallback: number): number { if (typeof value === 'number' && Number.isFinite(value)) { const n = Math.trunc(value); diff --git a/packages/common/tests/runtime.test.ts b/packages/common/tests/runtime.test.ts new file mode 100644 index 00000000..8814c34f --- /dev/null +++ b/packages/common/tests/runtime.test.ts @@ -0,0 +1,117 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime'; + +describe('normalizeRuntimeConfig', () => { + it('applies all defaults for an empty object', () => { + expect(normalizeRuntimeConfig({})).toEqual({ + webuiPort: 5099, + hookAutoLoad: false, + webuiHost: '0.0.0.0', + webuiTls: { enabled: false }, + trustProxy: '', + }); + }); + + it('passes through valid values', () => { + expect(normalizeRuntimeConfig({ + webuiPort: 8080, + hookAutoLoad: true, + webuiHost: '127.0.0.1', + webuiTls: { enabled: true }, + trustProxy: '1', + })).toEqual({ + webuiPort: 8080, + hookAutoLoad: true, + webuiHost: '127.0.0.1', + webuiTls: { enabled: true }, + trustProxy: '1', + }); + }); + + it('falls back on invalid types', () => { + const out = normalizeRuntimeConfig({ + webuiPort: 0, // out of range → default + webuiHost: 123, // non-string → default + webuiTls: 'yes', // non-object → default + trustProxy: 5, // non-string → default + }); + expect(out.webuiPort).toBe(5099); + expect(out.webuiHost).toBe('0.0.0.0'); + expect(out.webuiTls).toEqual({ enabled: false }); + expect(out.trustProxy).toBe(''); + }); + + it('coerces webuiTls.enabled loosely and trims a blank host to default', () => { + expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true }); + expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0'); + }); + + it('rejects a non-object input back to full defaults', () => { + expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099); + expect(normalizeRuntimeConfig('nope').webuiHost).toBe('0.0.0.0'); + }); +}); + +describe('resolveRuntimeEnvOverrides', () => { + it('returns empty when no SNOWLUMA_* vars are set', () => { + expect(resolveRuntimeEnvOverrides({})).toEqual({}); + }); + + it('parses port / host / trustProxy from env', () => { + expect(resolveRuntimeEnvOverrides({ + SNOWLUMA_WEBUI_PORT: '6700', + SNOWLUMA_WEBUI_HOST: '127.0.0.1', + SNOWLUMA_WEBUI_TRUST_PROXY: '1', + })).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' }); + }); + + it('ignores an out-of-range / non-numeric port env', () => { + expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({}); + expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({}); + }); + + it('treats trustProxy="0"/"off" as a real override (not absent)', () => { + expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' }); + }); +}); + +describe('updateRuntimeConfig (fs)', () => { + let prevCwd: string; + let dir: string; + let prevPortEnv: string | undefined; + beforeEach(async () => { + const fs = await import('fs'); const os = await import('os'); const path = await import('path'); + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-')); + prevCwd = process.cwd(); + process.chdir(dir); + prevPortEnv = process.env.SNOWLUMA_WEBUI_PORT; + delete process.env.SNOWLUMA_WEBUI_PORT; + }); + afterEach(async () => { + const fs = await import('fs'); + process.chdir(prevCwd); + if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT; + else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv; + fs.rmSync(dir, { recursive: true, force: true }); + }); + + it('merges a patch over on-disk values and persists normalized', async () => { + const { updateRuntimeConfig } = await import('../src/runtime'); + const fs = await import('fs'); const path = await import('path'); + const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } }); + expect(out.webuiHost).toBe('127.0.0.1'); + expect(out.webuiTls).toEqual({ enabled: true }); + const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8')); + expect(onDisk.webuiHost).toBe('127.0.0.1'); + expect(onDisk.webuiTls).toEqual({ enabled: true }); + }); + + it('does NOT bake an env-overridden port into the persisted file', async () => { + const { updateRuntimeConfig } = await import('../src/runtime'); + const fs = await import('fs'); const path = await import('path'); + process.env.SNOWLUMA_WEBUI_PORT = '9999'; + updateRuntimeConfig({ webuiHost: '127.0.0.1' }); + const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8')); + expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999 + }); +}); diff --git a/packages/common/vitest.config.ts b/packages/common/vitest.config.ts new file mode 100644 index 00000000..d807e895 --- /dev/null +++ b/packages/common/vitest.config.ts @@ -0,0 +1,10 @@ +// Vitest config for @snowluma/common. Pure-TS package (no proton), so a +// plain node-environment runner over tests/ is enough. +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['tests/**/*.test.ts'], + environment: 'node', + }, +}); diff --git a/packages/core/package.json b/packages/core/package.json index 6c49654f..669ac58a 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/core", - "version": "1.9.12", + "version": "1.9.13", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts index 86920988..bbdddb49 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/bridge/apis/group-file.ts @@ -21,6 +21,7 @@ import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/ import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page'; import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file'; import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file'; +import { RenameGroupFile } from '@snowluma/protocol/oidb-services/group-file/rename-group-file'; import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder'; import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request'; import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request'; @@ -604,6 +605,10 @@ export class GroupFileApi { return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory }); } + rename(groupId: number, fileId: string, parentDirectory: string, newFileName: string): Promise { + return RenameGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, newFileName }); + } + // ─────────────── folders ─────────────── createFolder(groupId: number, name: string, parentId = '/'): Promise { diff --git a/packages/core/src/bridge/apis/misc.ts b/packages/core/src/bridge/apis/misc.ts index bb549d61..ce126781 100644 --- a/packages/core/src/bridge/apis/misc.ts +++ b/packages/core/src/bridge/apis/misc.ts @@ -10,6 +10,7 @@ import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign'; import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh'; import { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decrypt-key'; +import { ImageOcr, type OcrResult } from '@snowluma/protocol/oidb-services/misc/image-ocr'; export class MiscApi { constructor(private readonly ctx: BridgeContext) { } @@ -18,6 +19,10 @@ export class MiscApi { return TranslateEnToZh.invoke(this.ctx, { words }); } + ocrImage(imageUrl: string): Promise { + return ImageOcr.invoke(this.ctx, { imageUrl }); + } + async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise { let appid = '1109937557'; // default: bilibili let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg'; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 728681e3..4668352e 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -48,7 +48,11 @@ async function main() { ) { try { const { initWebUI } = await import('./webui/server'); - await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager); + await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, { + host: runtimeConfig.webuiHost, + tlsEnabled: runtimeConfig.webuiTls?.enabled, + trustProxy: runtimeConfig.trustProxy, + }); } catch (err) { log.error('Failed to start WebUI: ', err); } diff --git a/packages/core/src/notifications/config.ts b/packages/core/src/notifications/config.ts index eb410eef..2ec24437 100644 --- a/packages/core/src/notifications/config.ts +++ b/packages/core/src/notifications/config.ts @@ -48,9 +48,13 @@ export interface NotificationsConfig { channels: NotificationChannel[]; } -/** A neutral plaintext starting point; the WebUI ships per-vendor presets - * (钉钉/Discord/…) as frontend constants the operator can drop in. */ -export const DEFAULT_BODY_TEMPLATE = '{nickname}({uin}) {event} @ {time}'; +/** Default body template — Server酱-style JSON ({title}/{desp}). The WebUI + * ships additional per-vendor presets (钉钉/Discord/…) as frontend constants + * the operator can drop in. */ +export const DEFAULT_BODY_TEMPLATE = `{ + "title": "账号状态通知:{event}", + "desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}" +}`; export function defaultNotificationsConfig(): NotificationsConfig { return { @@ -67,12 +71,25 @@ export function defaultNotificationsConfig(): NotificationsConfig { * A key present in `vars` is replaced by its value; an unknown `{key}` is left * untouched (原样) so a typo'd placeholder is visible rather than silently * blanked. Pure + total (a non-string template yields ''). + * + * **JSON safety**: When the template is valid JSON (parseable by JSON.parse), + * values are escaped to prevent breaking the JSON structure — backslashes + * become `\\` and double-quotes become `\"`. */ export function renderTemplate(template: string, vars: Record): string { if (typeof template !== 'string') return ''; - return template.replace(/\{(\w+)\}/g, (match, key: string) => - Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : match, - ); + let isJson = false; + try { + JSON.parse(template); + isJson = true; + } catch { + // not JSON — plain text mode + } + return template.replace(/\{(\w+)\}/g, (match, key: string) => { + if (!Object.prototype.hasOwnProperty.call(vars, key)) return match; + const val = vars[key]; + return isJson ? val.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : val; + }); } // ─── Normalization helpers (replicated from ui-config conventions) ────────── diff --git a/packages/core/src/webui/backup.ts b/packages/core/src/webui/backup.ts new file mode 100644 index 00000000..32a645ae --- /dev/null +++ b/packages/core/src/webui/backup.ts @@ -0,0 +1,125 @@ +// WebUI config backup/restore (Wave A2). Format: a zero-dep JSON bundle +// { version, app, createdAt, files: { "": { encoding, data } } } +// over an explicit allowlist (never a whole-dir sweep) so a stray/unknown file +// can't leak and an import can't path-traverse. +// +// Credentials are gated by a toggle on both export and import. The credential +// set is: webui.json (password hash), key.pem (TLS private key), AND every +// OneBot config (onebot.json + per-account onebot_.json) — those carry the +// OneBot access token, so a no-credentials backup must NOT include them. +// cert.pem is public so it always travels. +// +// Pure functions here (read/list/decode); the fs glue (atomic two-phase write, +// snapshot) lives in server.ts. Restore is restart-to-apply, like A1. + +export const BACKUP_VERSION = 1; +export const BACKUP_APP = 'snowluma'; + +export interface BackupFileSpec { + /** Path relative to the config dir; also the bundle key. */ + name: string; + binary: boolean; + /** Sensitive (private key / password hash / access token) — credential-gated. */ + credential: boolean; +} + +/** Static allowlist. Per-account `onebot_.json` are matched by pattern. */ +export const BACKUP_FILES: readonly BackupFileSpec[] = [ + { name: 'runtime.json', binary: false, credential: false }, + { name: 'ui.json', binary: false, credential: false }, + { name: 'notifications.json', binary: false, credential: false }, + { name: 'cert.pem', binary: false, credential: false }, + { name: 'ui-assets/background', binary: true, credential: false }, + { name: 'webui.json', binary: false, credential: true }, + { name: 'key.pem', binary: false, credential: true }, + // OneBot config carries the access token → credential. + { name: 'onebot.json', binary: false, credential: true }, +]; + +const SPEC_BY_NAME = new Map(BACKUP_FILES.map((f) => [f.name, f])); +const PER_UIN_ONEBOT = /^onebot_\d+\.json$/; + +/** Resolve a file name (static or per-uin onebot pattern) to its spec, or null. */ +export function specFor(name: string): BackupFileSpec | null { + const s = SPEC_BY_NAME.get(name); + if (s) return s; + if (PER_UIN_ONEBOT.test(name)) return { name, binary: false, credential: true }; + return null; +} + +export interface BackupEntry { encoding: 'utf8' | 'base64'; data: string } +export interface Backup { + version: number; + app: string; + createdAt?: string; + files: Record; +} + +/** + * Assemble a bundle from the allowlist plus any per-account onebot files. + * `readFile` returns null for missing. + */ +export function buildBackup( + readFile: (name: string) => Buffer | null, + perUinOnebotNames: readonly string[], + opts: { includeCredentials: boolean }, + createdAt: string, +): Backup { + const files: Record = {}; + const all: BackupFileSpec[] = [ + ...BACKUP_FILES, + ...perUinOnebotNames.filter((n) => PER_UIN_ONEBOT.test(n)).map((n) => ({ name: n, binary: false, credential: true })), + ]; + for (const spec of all) { + if (spec.credential && !opts.includeCredentials) continue; + const buf = readFile(spec.name); + if (!buf) continue; + files[spec.name] = spec.binary + ? { encoding: 'base64', data: buf.toString('base64') } + : { encoding: 'utf8', data: buf.toString('utf8') }; + } + return { version: BACKUP_VERSION, app: BACKUP_APP, createdAt, files }; +} + +/** Validate a parsed bundle wholesale — any defect rejects the whole import. */ +export function validateBackup(parsed: unknown): { ok: true; backup: Backup } | { ok: false; error: string } { + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + return { ok: false, error: 'backup must be an object' }; + } + const b = parsed as Record; + if (b.app !== BACKUP_APP) return { ok: false, error: 'not a SnowLuma backup' }; + if (b.version !== BACKUP_VERSION) return { ok: false, error: `unsupported backup version ${String(b.version)}` }; + if (typeof b.files !== 'object' || b.files === null || Array.isArray(b.files)) { + return { ok: false, error: 'backup.files must be an object' }; + } + const files = b.files as Record; + for (const [name, entry] of Object.entries(files)) { + if (!specFor(name)) return { ok: false, error: `unknown file in backup: ${name}` }; + if (typeof entry !== 'object' || entry === null) return { ok: false, error: `malformed entry: ${name}` }; + const e = entry as Record; + if (e.encoding !== 'utf8' && e.encoding !== 'base64') return { ok: false, error: `bad encoding for ${name}` }; + if (typeof e.data !== 'string') return { ok: false, error: `bad data for ${name}` }; + } + return { ok: true, backup: { version: BACKUP_VERSION, app: BACKUP_APP, createdAt: typeof b.createdAt === 'string' ? b.createdAt : undefined, files: files as Record } }; +} + +/** + * Decide what a (validated) bundle would restore: decode each non-skipped file + * to bytes. Pure — the caller (server.ts) does the atomic two-phase fs write so + * a mid-restore failure can't leave a half-applied live config. Credential + * files are skipped unless `restoreCredentials`. + */ +export function planRestore( + backup: Backup, + opts: { restoreCredentials: boolean }, +): { restore: Array<{ name: string; data: Buffer }>; skipped: string[] } { + const restore: Array<{ name: string; data: Buffer }> = []; + const skipped: string[] = []; + for (const [name, entry] of Object.entries(backup.files)) { + const spec = specFor(name); + if (!spec) { skipped.push(name); continue; } // validated, but be defensive + if (spec.credential && !opts.restoreCredentials) { skipped.push(name); continue; } + restore.push({ name, data: Buffer.from(entry.data, entry.encoding) }); + } + return { restore, skipped }; +} diff --git a/packages/core/src/webui/debug-stream.ts b/packages/core/src/webui/debug-stream.ts new file mode 100644 index 00000000..cc6889f7 --- /dev/null +++ b/packages/core/src/webui/debug-stream.ts @@ -0,0 +1,28 @@ +// SSE frame pusher for the debug stream (Wave A3). Drops frames under +// backpressure (consumer slow → desiredSize <= 0) instead of buffering +// unbounded into memory, and coalesces the drop count into a {kind:'dropped'} +// marker emitted just before the next delivered frame. Extracted from the route +// handler so this (easy-to-get-wrong) logic is unit-tested. + +export interface FramePusherOptions { + /** The stream controller's current desiredSize (null = no backpressure info). */ + desiredSize: () => number | null; + /** Deliver an encoded SSE chunk (the caller maps this to the controller). */ + enqueue: (chunk: Uint8Array) => void; + encode?: (s: string) => Uint8Array; +} + +/** Returns a `push(payload)` that frames + delivers with backpressure dropping. */ +export function createFramePusher(opts: FramePusherOptions): (payload: unknown) => void { + const encode = opts.encode ?? ((s: string) => new TextEncoder().encode(s)); + let dropped = 0; + return (payload: unknown): void => { + const d = opts.desiredSize(); + if (d !== null && d <= 0) { dropped += 1; return; } + if (dropped > 0) { + opts.enqueue(encode(`data: ${JSON.stringify({ kind: 'dropped', count: dropped })}\n\n`)); + dropped = 0; + } + opts.enqueue(encode(`data: ${JSON.stringify(payload)}\n\n`)); + }; +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 4d48510f..99ed29e0 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -4,14 +4,21 @@ import type { HookManager, HookProcessInfo } from '@snowluma/bridge'; import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger'; import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config'; import type { OneBotManager } from '@snowluma/onebot/manager'; -import type { OneBotConfig } from '@snowluma/onebot/types'; +import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types'; +import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime'; import { randomBytes } from 'crypto'; -import { existsSync, readFileSync } from 'fs'; +import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'; +import { createServer as createHttpsServer } from 'https'; import { Hono, type Context } from 'hono'; import os from 'os'; import path from 'path'; import { fileURLToPath } from 'url'; import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth'; +import { resolveTlsContext, validateTlsPair } from './tls'; +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 { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { findAvailablePort } from './port'; import { @@ -60,6 +67,7 @@ const MUST_CHANGE_ALLOWLIST = new Set([ // into access logs / Referer / browser history. const TOKEN_QUERY_ALLOWLIST = new Set([ '/api/logs/stream', + '/api/debug/stream', ]); // uin = QQ number; 5–12 digits. Used to construct config file paths, @@ -78,14 +86,6 @@ function purgeExpiredTokens() { } } -/** - * Resolve the client IP for per-IP rate limiting. Default is the TCP - * socket peer (cannot be spoofed by the client). Operators behind a - * reverse proxy must opt in via the `SNOWLUMA_WEBUI_TRUST_PROXY` env - * var; see `./client-ip.ts` for the accepted values. - */ -const trustProxyMode = parseTrustProxy(process.env.SNOWLUMA_WEBUI_TRUST_PROXY); -const getClientIp = makeClientIpResolver(trustProxyMode); async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> { const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, { @@ -105,7 +105,19 @@ export async function initWebUI( oneBotManager: OneBotManager, hookManager?: HookManager, notificationManager?: NotificationManager, + listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string } = {}, ): Promise<{ port: number }> { + // Resolve the client IP for per-IP rate limiting from the configured + // trust-proxy directive (runtime.json `trustProxy`, env-overridable via + // SNOWLUMA_WEBUI_TRUST_PROXY which loadRuntimeConfig already merged in). + // Default ('') = trust the TCP socket peer only (cannot be spoofed). + const trustProxyMode = parseTrustProxy(listener.trustProxy); + const getClientIp = makeClientIpResolver(trustProxyMode); + + // Actual bound port (set just before serve; findAvailablePort may bump it). + // Read by GET /api/system/settings so the panel shows what's really live. + let boundPort = desiredPort; + const auth = WebuiAuth.load(); const initialPassword = auth.takeInitialPassword(); if (auth.isDevMode()) { @@ -395,6 +407,252 @@ export async function initWebUI( }); }); + // ── System settings (WebUI listener) — Wave A1 ── + // Listener-level changes (port/host/TLS) are persisted but apply only on the + // next restart (no supervisor → no self-restart). The panel surfaces which + // fields are currently overridden by env so edits that won't take effect are + // visible. + const SYSTEM_CERT_PATH = path.join('config', 'cert.pem'); + const SYSTEM_KEY_PATH = path.join('config', 'key.pem'); + const hasCert = (): boolean => existsSync(SYSTEM_CERT_PATH) && existsSync(SYSTEM_KEY_PATH); + + app.get('/api/system/settings', (c) => { + const disk = readRuntimeConfig(); + const envOverrides = Object.keys(resolveRuntimeEnvOverrides(process.env)); + return c.json({ + settings: { + webuiPort: disk.webuiPort, + webuiHost: disk.webuiHost, + tlsEnabled: disk.webuiTls?.enabled ?? false, + trustProxy: disk.trustProxy ?? '', + }, + hasCert: hasCert(), + envOverrides, // field names currently pinned by SNOWLUMA_* env vars + listeningPort: boundPort, + restartRequiredToApply: true, + }); + }); + + app.post('/api/system/settings', async (c) => { + let body: unknown; + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + const coerced = coerceSettingsPatch(body); + if (!coerced.ok) return c.json({ success: false, message: coerced.error }, 400); + // Enabling TLS without a usable cert would brick HTTPS on restart — block it. + if (coerced.patch.webuiTls?.enabled && !resolveTlsContext('config').ok) { + return c.json({ success: false, message: '启用 TLS 前请先上传有效的证书与私钥' }, 400); + } + const saved = updateRuntimeConfig(coerced.patch); + return c.json({ + success: true, + settings: { + webuiPort: saved.webuiPort, + webuiHost: saved.webuiHost, + tlsEnabled: saved.webuiTls?.enabled ?? false, + trustProxy: saved.trustProxy ?? '', + }, + restartRequiredToApply: true, + }); + }); + + app.post('/api/system/tls/cert', async (c) => { + let body: unknown; + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + const cert = (body as { cert?: unknown }).cert; + const key = (body as { key?: unknown }).key; + if (typeof cert !== 'string' || typeof key !== 'string') { + return c.json({ success: false, message: 'cert 和 key 必须为 PEM 字符串' }, 400); + } + const valid = validateTlsPair(cert, key); + if (!valid.ok) return c.json({ success: false, message: valid.reason }, 400); + try { + mkdirSync('config', { recursive: true }); + writeFileSync(SYSTEM_CERT_PATH, cert.endsWith('\n') ? cert : cert + '\n', 'utf8'); + // Private key must not be world-readable (mirrors auth.ts's webui.json + // 0600). writeFileSync's mode is ignored for an existing file, so chmod + // explicitly afterwards. + writeFileSync(SYSTEM_KEY_PATH, key.endsWith('\n') ? key : key + '\n', { encoding: 'utf8', mode: 0o600 }); + // Best-effort (mirrors auth.ts): the key is already written 0600 above, so + // a rare chmod failure must not fail the request. + try { chmodSync(SYSTEM_KEY_PATH, 0o600); } catch { /* best-effort */ } + } catch (err) { + log.warn('write cert/key failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '写入证书失败,请检查服务器日志' }, 500); + } + return c.json({ success: true, restartRequiredToApply: true }); + }); + + app.delete('/api/system/tls/cert', (c) => { + try { + rmSync(SYSTEM_CERT_PATH, { force: true }); + rmSync(SYSTEM_KEY_PATH, { force: true }); + } catch (err) { + log.warn('remove cert/key failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '删除证书失败' }, 500); + } + return c.json({ success: true }); + }); + + // ── Config backup / restore (Wave A2) ── + const cfgPath = (name: string) => path.join('config', name); + const readCfg = (name: string): Buffer | null => { + const p = cfgPath(name); + return existsSync(p) ? readFileSync(p) : null; + }; + + const listPerUinOnebot = (): string[] => { + try { + return existsSync('config') ? readdirSync('config').filter((n) => /^onebot_\d+\.json$/.test(n)) : []; + } catch { return []; } + }; + + app.get('/api/system/backup/export', (c) => { + const includeCredentials = c.req.query('credentials') === '1'; + const ts = new Date().toISOString(); + const bundle = buildBackup(readCfg, listPerUinOnebot(), { includeCredentials }, ts); + c.header('Content-Disposition', `attachment; filename="snowluma-backup-${ts.replace(/[:.]/g, '-')}.json"`); + // Bundle may carry the TLS private key / password hash — never cache it. + c.header('Cache-Control', 'no-store, max-age=0'); + c.header('Pragma', 'no-cache'); + return c.json(bundle); + }); + + app.post('/api/system/backup/import', async (c) => { + const declaredLen = Number(c.req.header('content-length')); + if (Number.isFinite(declaredLen) && declaredLen > 32 * 1024 * 1024) { + return c.json({ success: false, message: '备份文件过大' }, 413); + } + let body: unknown; + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + if (typeof body !== 'object' || body === null) { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + const { backup, restoreCredentials } = body as { backup?: unknown; restoreCredentials?: unknown }; + const v = validateBackup(backup); + if (!v.ok) return c.json({ success: false, message: v.error }, 400); + + const plan = planRestore(v.backup, { restoreCredentials: restoreCredentials === true }); + // Snapshot the current (about-to-be-overwritten) config so a restore is + // recoverable; one timestamped dir per import. + const snapDir = path.join('config', `.restore-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`); + // Two-phase write for near-atomicity: stage every file as a .tmp first, then + // rename them all. A failure during staging touches no live file; rename + // almost never fails, shrinking the half-applied window to near zero. + const staged: Array<{ tmp: string; dest: string; name: string }> = []; + try { + for (const { name } of plan.restore) { + const src = cfgPath(name); + if (!existsSync(src)) continue; + const snap = path.join(snapDir, name); + mkdirSync(path.dirname(snap), { recursive: true }); + copyFileSync(src, snap); + } + for (const { name, data } of plan.restore) { + const dest = cfgPath(name); + mkdirSync(path.dirname(dest), { recursive: true }); + const tmp = dest + '.restore.tmp'; + writeFileSync(tmp, data, name === 'key.pem' ? { mode: 0o600 } : undefined); + staged.push({ tmp, dest, name }); + } + for (const { tmp, dest, name } of staged) { + renameSync(tmp, dest); + if (name === 'key.pem') { try { chmodSync(dest, 0o600); } catch { /* best-effort */ } } + } + return c.json({ + success: true, + restored: plan.restore.map((r) => r.name), + skipped: plan.skipped, + snapshotDir: snapDir, + restartRequiredToApply: true, + }); + } catch (err) { + // Clean up any staged .tmp not yet renamed (staging-phase failure leaves + // the live config untouched; a rare rename-phase failure may be partial, + // recoverable from the snapshot dir). + for (const { tmp } of staged) { try { if (existsSync(tmp)) rmSync(tmp, { force: true }); } catch { /* ignore */ } } + log.warn('backup import failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '恢复失败;若为写入阶段失败则当前配置未改动,否则可从 config/.restore-backup-* 快照恢复' }, 500); + } + }); + + // ── Debug tools (Wave A3) ── + // Action schemas for the tester form (declarative actions only; legacy ones + // are invoked freeform). + app.get('/api/debug/actions', (c) => + c.json({ actions: collectActionDocs(), categories: collectCategories() })); + + // Manually invoke an action against one account. Real side effects — gated by + // the same /api/* auth. + app.post('/api/debug/invoke', 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 result = await inst.invokeAction(action, (params ?? {}) as OneBotJsonObject); + return c.json(result); + }); + + // 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. + app.get('/api/debug/stream', (c) => { + const stream = new ReadableStream({ + start(controller) { + const encoder = new TextEncoder(); + let closed = false; + const offs: Array<() => void> = []; + let heartbeat: NodeJS.Timeout | undefined; + const teardown = () => { + if (closed) return; + closed = true; + if (heartbeat) clearInterval(heartbeat); + for (const off of offs) { try { off(); } catch { /* ignore */ } } + try { controller.close(); } catch { /* ignore */ } + }; + const raw = (chunk: Uint8Array) => { + if (closed) return; + try { controller.enqueue(chunk); } catch { teardown(); } + }; + // Drop-under-backpressure framing (unit-tested in debug-stream.ts). + const pushFrame = createFramePusher({ + desiredSize: () => controller.desiredSize, + enqueue: raw, + encode: (s) => encoder.encode(s), + }); + const send = (payload: unknown) => { if (!closed) pushFrame(payload); }; + send({ kind: 'ready' }); + for (const inst of oneBotManager.getInstances()) { + const uin = inst.uin; + offs.push(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event }))); + offs.push(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec }))); + } + heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000); + c.req.raw.signal.addEventListener('abort', teardown); + }, + }); + return new Response(stream, { + headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }, + }); + }); + app.get('/api/qq-list', (c) => { const instances = oneBotManager.getInstances(); const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname })); @@ -708,10 +966,27 @@ export async function initWebUI( if (finalPort !== desiredPort) { log.warn('port %d is in use, using %d instead', desiredPort, finalPort); } + boundPort = finalPort; + + const host = listener.host || '0.0.0.0'; + + // TLS: only when explicitly enabled AND the on-disk cert/key load. A bad + // or missing cert must never brick the WebUI — fall back to HTTP + warn. + let tlsServe: { createServer: typeof createHttpsServer; serverOptions: { cert: Buffer; key: Buffer } } | undefined; + let scheme = 'http'; + if (listener.tlsEnabled) { + const tls = resolveTlsContext('config'); + if (tls.ok && tls.cert && tls.key) { + tlsServe = { createServer: createHttpsServer, serverOptions: { cert: tls.cert, key: tls.key } }; + scheme = 'https'; + } else { + log.warn('TLS enabled but cert/key unusable (%s) — serving over HTTP instead', tls.reason); + } + } await new Promise((resolve) => { - serve({ fetch: app.fetch, port: finalPort }, (info) => { - log.info(`listening http://localhost:${info.port}`); + serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => { + log.info(`listening ${scheme}://${host}:${info.port}`); resolve(); }); }); diff --git a/packages/core/src/webui/system-settings.ts b/packages/core/src/webui/system-settings.ts new file mode 100644 index 00000000..fcecf80e --- /dev/null +++ b/packages/core/src/webui/system-settings.ts @@ -0,0 +1,52 @@ +// Pure validator for the POST /api/system/settings body. Rejects clearly-bad +// input with a message (→ 400) rather than silently normalizing it, then hands +// a clean patch to updateRuntimeConfig. Wire field `tlsEnabled` maps to the +// nested `webuiTls.enabled`. + +import type { RuntimeConfig } from '@snowluma/common/runtime'; + +export type SettingsPatch = Partial>; + +export type CoerceResult = + | { ok: true; patch: SettingsPatch } + | { ok: false; error: string }; + +function isObject(v: unknown): v is Record { + return typeof v === 'object' && v !== null && !Array.isArray(v); +} + +export function coerceSettingsPatch(body: unknown): CoerceResult { + if (!isObject(body)) return { ok: false, error: 'body must be an object' }; + const patch: SettingsPatch = {}; + + if ('webuiPort' in body) { + const p = body.webuiPort; + if (typeof p !== 'number' || !Number.isInteger(p) || p <= 0 || p > 65535) { + return { ok: false, error: 'webuiPort must be an integer in 1..65535' }; + } + patch.webuiPort = p; + } + + if ('webuiHost' in body) { + if (typeof body.webuiHost !== 'string' || !body.webuiHost.trim()) { + return { ok: false, error: 'webuiHost must be a non-empty string' }; + } + patch.webuiHost = body.webuiHost.trim(); + } + + if ('tlsEnabled' in body) { + if (typeof body.tlsEnabled !== 'boolean') { + return { ok: false, error: 'tlsEnabled must be a boolean' }; + } + patch.webuiTls = { enabled: body.tlsEnabled }; + } + + if ('trustProxy' in body) { + if (typeof body.trustProxy !== 'string') { + return { ok: false, error: 'trustProxy must be a string' }; + } + patch.trustProxy = body.trustProxy; + } + + return { ok: true, patch }; +} diff --git a/packages/core/src/webui/tls.ts b/packages/core/src/webui/tls.ts new file mode 100644 index 00000000..144e0b1e --- /dev/null +++ b/packages/core/src/webui/tls.ts @@ -0,0 +1,57 @@ +// WebUI TLS helpers. Cert/key live as config/cert.pem + config/key.pem +// (NapCat-aligned, self-contained, travels in A2 backups). Two pure-ish +// helpers: validate a pasted pair (save path) and resolve the on-disk pair +// (boot path). Validation is `tls.createSecureContext` — it parses the PEM +// and checks the key matches the cert; expiry is NOT checked here. + +import fs from 'fs'; +import path from 'path'; +import tls from 'tls'; + +export interface TlsValidation { + ok: boolean; + reason?: string; +} + +export interface TlsResolution { + ok: boolean; + cert?: Buffer; + key?: Buffer; + reason?: string; +} + +function errMsg(e: unknown): string { + return e instanceof Error ? e.message : String(e); +} + +/** Parse-validate a cert/key pair (used by the save endpoint before writing). */ +export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation { + if (!cert || !cert.toString().trim()) return { ok: false, reason: 'certificate is empty' }; + if (!key || !key.toString().trim()) return { ok: false, reason: 'private key is empty' }; + try { + tls.createSecureContext({ cert, key }); + return { ok: true }; + } catch (e) { + return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` }; + } +} + +/** Load + validate config/cert.pem + config/key.pem from `configDir`. */ +export function resolveTlsContext(configDir: string): TlsResolution { + const certPath = path.join(configDir, 'cert.pem'); + const keyPath = path.join(configDir, 'key.pem'); + if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) { + return { ok: false, reason: 'cert.pem or key.pem missing in config dir' }; + } + let cert: Buffer; + let key: Buffer; + try { + cert = fs.readFileSync(certPath); + key = fs.readFileSync(keyPath); + } catch (e) { + return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` }; + } + const valid = validateTlsPair(cert, key); + if (!valid.ok) return { ok: false, reason: valid.reason }; + return { ok: true, cert, key }; +} diff --git a/packages/core/tests/notifications-config.test.ts b/packages/core/tests/notifications-config.test.ts index d81827b9..29bde880 100644 --- a/packages/core/tests/notifications-config.test.ts +++ b/packages/core/tests/notifications-config.test.ts @@ -47,6 +47,15 @@ describe('renderTemplate — mechanical {key} substitution', () => { // to a recursive/loop replace would break this while passing every other test. expect(renderTemplate('{a}', { a: '{b}', b: 'NESTED' })).toBe('{b}'); }); + + it('escapes backslashes and quotes when template is JSON-like', () => { + const tmpl = '{"text": "{val}"}'; + expect(renderTemplate(tmpl, { val: 'a"b\\c' })).toBe('{"text": "a\\"b\\\\c"}'); + }); + + it('does NOT escape when template is plain text', () => { + expect(renderTemplate('{val}', { val: 'a"b\\c' })).toBe('a"b\\c'); + }); }); describe('normalizeNotificationsConfig — total normalize', () => { diff --git a/packages/core/tests/webui-backup.test.ts b/packages/core/tests/webui-backup.test.ts new file mode 100644 index 00000000..e907ec13 --- /dev/null +++ b/packages/core/tests/webui-backup.test.ts @@ -0,0 +1,128 @@ +import { describe, it, expect } from 'vitest'; +import { BACKUP_FILES, specFor, buildBackup, validateBackup, planRestore } from '../src/webui/backup'; + +const TS = '2026-06-18T00:00:00.000Z'; + +function reader(map: Record) { + return (name: string): Buffer | null => map[name] ?? null; +} + +describe('buildBackup', () => { + it('includes present non-credential files and skips missing ones', () => { + const b = buildBackup(reader({ + 'runtime.json': Buffer.from('{"webuiPort":5099}'), + 'ui.json': Buffer.from('{}'), + }), [], { includeCredentials: false }, TS); + expect(b.version).toBe(1); + expect(b.app).toBe('snowluma'); + expect(b.createdAt).toBe(TS); + expect(Object.keys(b.files).sort()).toEqual(['runtime.json', 'ui.json']); + expect(b.files['runtime.json']).toEqual({ encoding: 'utf8', data: '{"webuiPort":5099}' }); + }); + + it('treats all OneBot config (global + per-uin), webui.json, key.pem as credentials', () => { + const map = { + 'runtime.json': Buffer.from('{}'), + 'webui.json': Buffer.from('{"hash":"x"}'), + 'key.pem': Buffer.from('KEY'), + 'cert.pem': Buffer.from('CERT'), + 'onebot.json': Buffer.from('{"accessToken":"t"}'), + 'onebot_12345.json': Buffer.from('{"accessToken":"t2"}'), + }; + const perUin = ['onebot_12345.json']; + const without = buildBackup(reader(map), perUin, { includeCredentials: false }, TS); + // only public files survive a no-credentials export + expect(Object.keys(without.files).sort()).toEqual(['cert.pem', 'runtime.json']); + const withCreds = buildBackup(reader(map), perUin, { includeCredentials: true }, TS); + expect(Object.keys(withCreds.files).sort()).toEqual( + ['cert.pem', 'key.pem', 'onebot.json', 'onebot_12345.json', 'runtime.json', 'webui.json'], + ); + }); + + it('base64-encodes binary files (background image)', () => { + const png = Buffer.from([0x89, 0x50, 0x4e, 0x47]); + const b = buildBackup(reader({ 'ui-assets/background': png }), [], { includeCredentials: false }, TS); + expect(b.files['ui-assets/background']).toEqual({ encoding: 'base64', data: png.toString('base64') }); + }); +}); + +describe('specFor', () => { + it('resolves static names and per-uin onebot pattern; rejects others', () => { + expect(specFor('runtime.json')?.credential).toBe(false); + expect(specFor('onebot.json')?.credential).toBe(true); + expect(specFor('onebot_98765.json')).toEqual({ name: 'onebot_98765.json', binary: false, credential: true }); + expect(specFor('onebot_.json')).toBeNull(); + expect(specFor('../evil')).toBeNull(); + expect(specFor('onebot_12.json.bak')).toBeNull(); + }); +}); + +describe('validateBackup', () => { + const good = { version: 1, app: 'snowluma', files: { 'runtime.json': { encoding: 'utf8', data: '{}' } } }; + + it('accepts a well-formed bundle (incl. per-uin onebot)', () => { + expect(validateBackup(good).ok).toBe(true); + expect(validateBackup({ ...good, files: { 'onebot_42.json': { encoding: 'utf8', data: '{}' } } }).ok).toBe(true); + }); + + it('rejects a non-object / wrong app / wrong version', () => { + expect(validateBackup(null).ok).toBe(false); + expect(validateBackup({ ...good, app: 'other' }).ok).toBe(false); + expect(validateBackup({ ...good, version: 999 }).ok).toBe(false); + }); + + it('rejects an unknown / path-traversal filename', () => { + expect(validateBackup({ ...good, files: { '../evil': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false); + expect(validateBackup({ ...good, files: { 'unknown.json': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false); + expect(validateBackup({ ...good, files: { 'onebot_../x.json': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false); + }); + + it('rejects a malformed entry', () => { + expect(validateBackup({ ...good, files: { 'runtime.json': { encoding: 'rot13', data: 'x' } } }).ok).toBe(false); + expect(validateBackup({ ...good, files: { 'runtime.json': { encoding: 'utf8' } } }).ok).toBe(false); + }); +}); + +describe('planRestore', () => { + it('decodes restored files to bytes (utf8 + base64)', () => { + const png = Buffer.from([1, 2, 3, 4]); + const backup = { + version: 1, app: 'snowluma', + files: { + 'runtime.json': { encoding: 'utf8' as const, data: '{"a":1}' }, + 'ui-assets/background': { encoding: 'base64' as const, data: png.toString('base64') }, + }, + }; + const { restore, skipped } = planRestore(backup, { restoreCredentials: false }); + expect(skipped).toEqual([]); + const byName = Object.fromEntries(restore.map((r) => [r.name, r.data])); + expect(byName['runtime.json'].toString()).toBe('{"a":1}'); + expect(byName['ui-assets/background'].equals(png)).toBe(true); + }); + + it('skips all credential files unless restoreCredentials', () => { + const backup = { + version: 1, app: 'snowluma', + files: { + 'runtime.json': { encoding: 'utf8' as const, data: '{}' }, + 'webui.json': { encoding: 'utf8' as const, data: '{"hash":"x"}' }, + 'key.pem': { encoding: 'utf8' as const, data: 'KEY' }, + 'onebot.json': { encoding: 'utf8' as const, data: '{"accessToken":"t"}' }, + 'onebot_7.json': { encoding: 'utf8' as const, data: '{"accessToken":"t"}' }, + }, + }; + const skip = planRestore(backup, { restoreCredentials: false }); + expect(skip.restore.map((r) => r.name)).toEqual(['runtime.json']); + expect(skip.skipped.sort()).toEqual(['key.pem', 'onebot.json', 'onebot_7.json', 'webui.json']); + const keep = planRestore(backup, { restoreCredentials: true }); + expect(keep.restore.map((r) => r.name).sort()).toEqual( + ['key.pem', 'onebot.json', 'onebot_7.json', 'runtime.json', 'webui.json'], + ); + }); +}); + +it('BACKUP_FILES marks webui.json / key.pem / onebot.json as credentials, cert.pem public', () => { + const creds = BACKUP_FILES.filter((f) => f.credential).map((f) => f.name).sort(); + expect(creds).toEqual(['key.pem', 'onebot.json', 'webui.json']); + expect(specFor('cert.pem')?.credential).toBe(false); +}); diff --git a/packages/core/tests/webui-debug-stream.test.ts b/packages/core/tests/webui-debug-stream.test.ts new file mode 100644 index 00000000..e753b091 --- /dev/null +++ b/packages/core/tests/webui-debug-stream.test.ts @@ -0,0 +1,52 @@ +import { describe, it, expect } from 'vitest'; +import { createFramePusher } from '../src/webui/debug-stream'; + +function harness(sizes: number[]) { + // desiredSize() returns the next scripted value each call. + let i = 0; + const frames: string[] = []; + const push = createFramePusher({ + desiredSize: () => (i < sizes.length ? sizes[i++] : sizes[sizes.length - 1] ?? 1), + enqueue: (chunk) => { frames.push(Buffer.from(chunk).toString()); }, + encode: (s) => Buffer.from(s), + }); + return { push, frames }; +} + +describe('createFramePusher', () => { + it('enqueues an SSE data frame when there is headroom', () => { + const { push, frames } = harness([1]); + push({ kind: 'event', x: 1 }); + expect(frames).toEqual([`data: ${JSON.stringify({ kind: 'event', x: 1 })}\n\n`]); + }); + + it('drops under backpressure (desiredSize <= 0) without enqueuing', () => { + const { push, frames } = harness([0, -3]); + push({ a: 1 }); + push({ a: 2 }); + expect(frames).toEqual([]); + }); + + it('emits a coalesced dropped marker before the next delivered frame', () => { + const { push, frames } = harness([0, 0, 5]); // drop, drop, then headroom + push({ a: 1 }); + push({ a: 2 }); + push({ a: 3 }); + expect(frames).toEqual([ + `data: ${JSON.stringify({ kind: 'dropped', count: 2 })}\n\n`, + `data: ${JSON.stringify({ a: 3 })}\n\n`, + ]); + }); + + it('treats null desiredSize as always-deliver (no backpressure signal)', () => { + let i = 0; + const frames: string[] = []; + const push = createFramePusher({ + desiredSize: () => (i++ === 0 ? null : 1), + enqueue: (chunk) => { frames.push(Buffer.from(chunk).toString()); }, + encode: (s) => Buffer.from(s), + }); + push({ a: 1 }); + expect(frames).toHaveLength(1); + }); +}); diff --git a/packages/core/tests/webui-system-settings.test.ts b/packages/core/tests/webui-system-settings.test.ts new file mode 100644 index 00000000..d79b6607 --- /dev/null +++ b/packages/core/tests/webui-system-settings.test.ts @@ -0,0 +1,39 @@ +import { describe, it, expect } from 'vitest'; +import { coerceSettingsPatch } from '../src/webui/system-settings'; + +describe('coerceSettingsPatch', () => { + it('accepts a full valid body and maps tlsEnabled → webuiTls.enabled', () => { + const r = coerceSettingsPatch({ webuiPort: 8080, webuiHost: '127.0.0.1', tlsEnabled: true, trustProxy: '1' }); + expect(r).toEqual({ ok: true, patch: { webuiPort: 8080, webuiHost: '127.0.0.1', webuiTls: { enabled: true }, trustProxy: '1' } }); + }); + + it('only includes provided keys (partial patch)', () => { + const r = coerceSettingsPatch({ webuiHost: '0.0.0.0' }); + expect(r).toEqual({ ok: true, patch: { webuiHost: '0.0.0.0' } }); + }); + + it('rejects a non-object body', () => { + expect(coerceSettingsPatch(null).ok).toBe(false); + expect(coerceSettingsPatch('x').ok).toBe(false); + }); + + it('rejects an out-of-range or non-integer port', () => { + expect(coerceSettingsPatch({ webuiPort: 0 }).ok).toBe(false); + expect(coerceSettingsPatch({ webuiPort: 70000 }).ok).toBe(false); + expect(coerceSettingsPatch({ webuiPort: 12.5 }).ok).toBe(false); + }); + + it('rejects an empty/blank host', () => { + expect(coerceSettingsPatch({ webuiHost: ' ' }).ok).toBe(false); + expect(coerceSettingsPatch({ webuiHost: 123 }).ok).toBe(false); + }); + + it('rejects a non-boolean tlsEnabled and non-string trustProxy', () => { + expect(coerceSettingsPatch({ tlsEnabled: 'yes' }).ok).toBe(false); + expect(coerceSettingsPatch({ trustProxy: 1 }).ok).toBe(false); + }); + + it('accepts an empty-string trustProxy (trust nobody)', () => { + expect(coerceSettingsPatch({ trustProxy: '' })).toEqual({ ok: true, patch: { trustProxy: '' } }); + }); +}); diff --git a/packages/core/tests/webui-tls.test.ts b/packages/core/tests/webui-tls.test.ts new file mode 100644 index 00000000..115ada7d --- /dev/null +++ b/packages/core/tests/webui-tls.test.ts @@ -0,0 +1,102 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { validateTlsPair, resolveTlsContext } from '../src/webui/tls'; + +// A throwaway self-signed pair (openssl, CN=snowluma-test). createSecureContext +// only parses — expiry is irrelevant — so this stays valid for the test forever. +const CERT = `-----BEGIN CERTIFICATE----- +MIIDETCCAfmgAwIBAgIUNiu66PmcO6Do6cUaB92UKD8j3qYwDQYJKoZIhvcNAQEL +BQAwGDEWMBQGA1UEAwwNc25vd2x1bWEtdGVzdDAeFw0yNjA2MTgwNjIwMTZaFw0z +NjA2MTUwNjIwMTZaMBgxFjAUBgNVBAMMDXNub3dsdW1hLXRlc3QwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCm0sVJhqlG75gOFJVsUJOfR+oqvb9eSq4t +k5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll2ANSjusmWN4hzpaOBBdX +bP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23LsMsij8T4nLk4eHiOkeRfi +uLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/KmcNtq7JrX7F7qYnYsJKLZZ +aZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5dcZuI+KwixVKZgapG5n5R +ghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WVhvrD6pphAgMBAAGjUzBR +MB0GA1UdDgQWBBRW/HP12nj9fYMYNxa3jyqmnUigvTAfBgNVHSMEGDAWgBRW/HP1 +2nj9fYMYNxa3jyqmnUigvTAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA +A4IBAQCijzVQ/jHNoqu6stvkkigUv2lTKrd1EHcTZLfzwQkmNv/hfY2EMobO/Qxs +FhmITreKFALJ/dUwTt0UTO00LV9whEgr2of4x8wwjZ9wRstY6uyRYBP85QC8+8mZ +zWlcf611HugrmpOWjWfEVmmxdI1m26YWTn52nZFPnJqDWg2+RlLJWl55lVotbXEZ +Fvas4Vcf2KOk0QwBQKvpt0BISeTIQhbT4GnducxSxyoXGeBQOjQNYb/vTpMn4F9U +IAxSsfs9WVoHKXOabK8GV89BCxWoRk4UaSahTq/2Vnbgt86tWibt3lA4y49+XhA2 +6z7n9HgJAUKqhsDrYvZmM7/VZ2d5 +-----END CERTIFICATE----- +`; +const KEY = `-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCm0sVJhqlG75gO +FJVsUJOfR+oqvb9eSq4tk5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll +2ANSjusmWN4hzpaOBBdXbP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23Ls +Msij8T4nLk4eHiOkeRfiuLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/Kmc +Ntq7JrX7F7qYnYsJKLZZaZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5d +cZuI+KwixVKZgapG5n5RghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WV +hvrD6pphAgMBAAECggEAJ13+u4qhIMHCnrQBzPU42PImEt8DLXOvJcc5PFM6ZJ6S +rRHkAk60HAWV+OqOu2jS3o6NGYsJWJpWaPewVQev+zUmelDfm3TgsztfvBIh8K50 +dGFsef81tB1WnWo++K1kzUBZ4ljOV9f5hz62tWVlFubo/Vd8bsA6wEB6Jskd2fls +ZOO0hJCb/M6IIwe3cWw4sb/YFTTLMUnVHM0aJfnQ/QH+uraRwecJMv118d0YBYVG +DsNmYqrv9TYNBh4P9mKv6/0x8zaKsJZVLAMwHztILHItOXBfxCbSDivGWVUGiDq2 +NxEuBOgxzOelxEYzUzf7B6sjHoEeIL5wIKQbwUbmfwKBgQDZRLhucrMZPw7ous1t +igkO32p1ku7FRxm0/JAskc66oX61KLIYbZFM9N7nTXAEs8ZGhzUkdSgxNcdHWIdK +RI+6pd2FhhcKU1feEohlOHvZTXXEMhm61phWnN391GZXfwMKSpscqsu9kIix2jtw +4YrzKLx82EDDHcLfBh9AtArKywKBgQDEj+7UJp5wuqz9hj+gogXeq4Buv9be1u4u +HCJZMZzLCwVjvoqYw0n1afXP3057v8hQPGsBaxzQpOg7i1lYGGfuZ9T6T8fFrtqw +m/LJLHhMQxeyCEQi1/EoNewvVGSwBJkLOuOs8T2WmMXmOgdHbEYdzkKtT71jst6y +TeJ15hVuAwKBgBMK4t9LTkc4L6ZWOQsQvhp/mmUTq7m+sZIbUMeXP/c7kE9wcauS +btm/3ImJT/gZiZdE4nN/kTY+8GhgafsoZzCEuRWq2vocs+bS2QGGIdS55Uh826R0 +ioWM2igVJaMljq6oO1AX6COFN3XfGraaDgOh3mNS0NpJEXtangKdxRRhAoGAP9SF +t/r6hJz6RDHuQ5mZ0l9bC5vciOy+19ZnCRPlWMIxc9ySYV05jSplmqVndSQoRnX4 +QbOo3dBPYda0orj6Nx8cuFRkCTvo5GUgCFgakJlQ/o1UowQA2g/4rL35HHfBwzXS +bXzBhUADM+owJu9wLYmneWRlmhSh4MEOAz8+QkUCgYAw0fA1Im2/ftrA2Z2IENTi +U4cLXqeUeGJfXjIBklUmXhc4qrd/9V9eEHjackI/JI7Qhp/QfPWMXLudlSrppnNJ ++s3dVevEKosiZbf4qtTtlmR/IifuTKjK5O94KlBT+evxNsL4Hv0b0oTsVNnEfOOl +OUsvSYNSnfvl87tyLIxYLA== +-----END PRIVATE KEY----- +`; + +describe('validateTlsPair', () => { + it('accepts a matching cert/key pair', () => { + expect(validateTlsPair(CERT, KEY)).toEqual({ ok: true }); + }); + + it('rejects garbage PEM with a reason', () => { + const r = validateTlsPair('not a cert', 'not a key'); + expect(r.ok).toBe(false); + expect(r.reason).toBeTruthy(); + }); + + it('rejects an empty cert', () => { + expect(validateTlsPair('', KEY).ok).toBe(false); + }); +}); + +describe('resolveTlsContext', () => { + let dir: string; + beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-tls-')); }); + afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); }); + + it('loads cert.pem + key.pem when both present and valid', () => { + fs.writeFileSync(path.join(dir, 'cert.pem'), CERT); + fs.writeFileSync(path.join(dir, 'key.pem'), KEY); + const r = resolveTlsContext(dir); + expect(r.ok).toBe(true); + expect(r.cert?.toString()).toContain('BEGIN CERTIFICATE'); + expect(r.key?.toString()).toContain('PRIVATE KEY'); + }); + + it('fails (with reason) when files are missing', () => { + const r = resolveTlsContext(dir); + expect(r.ok).toBe(false); + expect(r.reason).toMatch(/missing/i); + }); + + it('fails when the on-disk PEM is invalid', () => { + fs.writeFileSync(path.join(dir, 'cert.pem'), 'garbage'); + fs.writeFileSync(path.join(dir, 'key.pem'), 'garbage'); + const r = resolveTlsContext(dir); + expect(r.ok).toBe(false); + expect(r.reason).toBeTruthy(); + }); +}); diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 54818189..219b9322 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/mcp", - "version": "1.9.12", + "version": "1.9.13", "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/onebot/package.json b/packages/onebot/package.json index 1392b5d6..3985e38e 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/onebot", - "version": "1.9.12", + "version": "1.9.13", "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/actions/extended.ts b/packages/onebot/src/actions/extended.ts index cdb33bde..4b97648f 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -563,9 +563,12 @@ export const actions = [ }, }), + // _mark_all_as_read — no-op。NapCat 靠单次内核 IPC markAllMsgAsRead() 实现, + // SnowLuma 无等价单包 SSO cmd;遍历所有会话逐个发已读报告是风控高危群发, + // 故暂不真正执行(留待 RE 出"一键全读"cmd)。返回 ok 以兼容启动时盲调的客户端。 defineAction({ name: '_mark_all_as_read', - summary: '标记全部已读', + summary: '标记全部已读(no-op,待 RE 全读 cmd)', params: {}, run: async () => { return okResponse(); @@ -705,15 +708,23 @@ export const actions = [ }, }), - // get_group_shut_list 依赖尚未封装的 oidb。 - // 这里遵循 NapCat 约定返回空列表,避免调用方出错。 - defineAction({ + // get_group_shut_list — SnowLuma 无独立"禁言列表"cmd,按成员列表的 + // shutUpTime 字段(绝对到期时间戳,秒)派生:保留仍在禁言中的成员。 + // 走带 TTL 缓存的 fetchGroupMemberList(风控友好,0xfe7 高频会触发腾讯封号), + // 与 NapCat 文档返回形状 {user_id,nickname,shut_up_time} 对齐。 + // 取舍:NapCat 此接口实时,本实现复用成员缓存,故结果最长有 ~60s 延迟—— + // 刚下/解的禁言可能在该窗口内未反映,属可接受的低频运维查询取舍。 + groupAction({ name: 'get_group_shut_list', - summary: '获取群禁言列表(占位)', + summary: '获取群禁言列表', readOnly: true, - params: {}, - run: async () => { - return okResponse([]); + run: async (p, ctx) => { + const members = await ctx.bridge.apis.contacts.fetchGroupMemberList(p.group_id); + const nowSec = Math.floor(Date.now() / 1000); + const list = members + .filter((m) => (m.shutUpTime ?? 0) > nowSec) + .map((m) => ({ user_id: m.uin, nickname: m.nickname, shut_up_time: m.shutUpTime })); + return okResponse(list); }, }), @@ -849,10 +860,13 @@ export const actions = [ }, }), - // NapCat 似乎也用不了,暂时不处理。 + // get_online_clients — 在线设备列表。NapCat 也拿不到(注册监听后 sleep 500ms + // 直接返回空),且其返回是裸数组 [],偏离 OneBot v11 / go-cqhttp 规范。 + // SnowLuma 暂无对应单包 SSO cmd,返回 OneBot v11 标准空壳 { clients: [] } + // ——刻意采用规范形状而非 NapCat 的裸 [],故对照 NapCat 客户端此处不严格 parity。 defineAction({ name: 'get_online_clients', - summary: '获取在线客户端(占位)', + summary: '获取在线客户端(占位,OneBot v11 形状)', readOnly: true, params: {}, run: async () => { @@ -860,13 +874,21 @@ export const actions = [ }, }), + // _get_model_show — NapCat 纯内核无 packet wire,其实现是硬编码 mock + // (无视入参,model_show 恒返回字面量 'napcat')。SnowLuma 同样无对应单包 + // SSO cmd,故只复用 NapCat 的*外层形状*:data 为数组 [{ variants: {...} }]、 + // need_pay 恒 false;但刻意不照搬其固定字面量——回显请求的 model(缺省 + // 'snowluma'),对调用方更有信息量。属有意的行为分歧,仅形状对齐。 defineAction({ name: '_get_model_show', - summary: '获取机型展示(占位)', + summary: '获取机型展示(兼容 mock)', readOnly: true, - params: {}, - run: async () => { - return okResponse({ variants: [] }); + params: { + model: f.string().default(''), + }, + run: async (p) => { + const modelShow = p.model || 'snowluma'; + return okResponse([{ variants: { model_show: modelShow, need_pay: false } }]); }, }), @@ -1018,27 +1040,36 @@ export const actions = [ }, }), - defineAction({ - name: 'rename_group_file', - summary: '重命名群文件(未实现)', - params: {}, - run: async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }, - }), - + // get_file — 统一文件信息入口。SnowLuma 按 file_id 解析媒体缓存: + // 先图片、后语音(两者已带 url 重签与 file_size/file_name)。 + // 局限:群文件/普通文件的 file_id 无法在此解析——OneBot `get_file` 单参 + // 签名不含 group_id,而 SnowLuma 群文件下载需要 group 上下文(用 + // get_group_file_url / get_private_file_url)。故此处仅覆盖图片/语音, + // 不为群文件伪造结果。 + // 注意:缓存双 miss 时无法在此区分"传入的是群文件 file_id"与"图片/语音 + // 确实未缓存(如进程重启丢失)"——run() 不解析 id 形态。故错误信息保持 + // 中性:先陈述"未命中缓存"的事实,再把群文件改用别的接口作为指引, + // 而非武断断言"不支持"。(summary 仅进离线文档,调用方运行时只看到 wording。) defineAction({ name: 'get_file', - summary: '获取文件(未实现)', + summary: '获取文件信息(仅图片/语音缓存;群文件请用 get_group_file_url)', readOnly: true, params: { file_id: f.string().default(''), file: f.string().default(''), }, - run: async (p) => { - const fileId = p.file_id || p.file; + run: async (p, ctx) => { + const fileId = p.file || p.file_id; if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required'); - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + const image = await ctx.getImageInfo(fileId); + if (image) return okResponse(image); + const record = await ctx.getRecordInfo(fileId); + if (record) return okResponse(record); + return failedResponse( + RETCODE.ACTION_FAILED, + 'file_id not found in the image/voice cache. get_file only resolves cached ' + + 'image/voice ids; for group/normal files use get_group_file_url or get_private_file_url', + ); }, }), @@ -1195,12 +1226,70 @@ export const actions = [ : failedResponse(RETCODE.ACTION_FAILED, 'not implemented'), }), + // get_rkey_server — 把下载 rkey 列表(type 10=私聊 / 20=群聊,同 0x9067 来源) + // 收敛成 NapCat 的 server 形状。expired_time = now + 在场 rkey ttl 的最小值。 defineAction({ - name: ['ocr_image', '.ocr_image'], - summary: 'OCR 图片(未实现)', + name: 'get_rkey_server', + summary: '获取 rkey 服务器信息', readOnly: true, params: {}, - run: () => failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'), + run: async (_p, ctx) => { + if (!ctx.getDownloadRKeys) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + const rkeys = await ctx.getDownloadRKeys(); + const pick = (type: number) => + rkeys.find((r) => (r as { type?: number }).type === type) as + { rkey?: string; ttl?: number } | undefined; + const priv = pick(10); + const group = pick(20); + // No rkey at all → fail rather than hand back an "expired_time = now, + // no keys" shell that a caching caller would misread as a valid-but-empty + // (already-expired) result. + if (!priv?.rkey && !group?.rkey) { + return failedResponse(RETCODE.ACTION_FAILED, 'no download rkey available'); + } + const ttls = [priv?.ttl, group?.ttl].filter((t): t is number => typeof t === 'number' && t > 0); + const minTtl = ttls.length ? Math.min(...ttls) : 0; + const data: JsonObject = { + expired_time: Math.floor(Date.now() / 1000) + minTtl, + name: 'SnowLuma', + }; + if (priv?.rkey) data.private_rkey = priv.rkey; + if (group?.rkey) data.group_rkey = group.rkey; + return okResponse(data); + }, + }), + + // ocr_image — 服务端 OCR via OIDB 0xE07_0(port 自 Lagrange/NapCat proto)。 + // 该 cmd 接收图片 URL(服务端拉取),故 image 支持:http(s) URL 直用,或 + // 已缓存图片的 file_id(经 getImageInfo 解析出 URL)。base64/本地文件需先 + // 上传换 URL,本实现不覆盖(NapCat 走的是 Windows-only 内核 OCR,不可移植)。 + defineAction({ + name: ['ocr_image', '.ocr_image'], + summary: 'OCR 图片(服务端,需图片 URL 或已缓存的图片 file_id)', + readOnly: true, + params: { image: f.string({ allowEmpty: false }) }, + 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 + // the server's retCode. The file_id path below re-signs via getImageInfo. + let url = /^https?:\/\//i.test(p.image) ? p.image : ''; + if (!url) { + const info = await ctx.getImageInfo(p.image); + const resolved = info && typeof info.url === 'string' ? info.url : ''; + if (resolved) url = resolved; + } + if (!url) { + return failedResponse( + RETCODE.ACTION_FAILED, + 'ocr_image needs an http(s) image url or a cached image file_id; ' + + 'base64/local-file input is not supported', + ); + } + const result = await ctx.bridge.apis.misc.ocrImage(url); + // OcrResult is plain JSON data; the interface just lacks an index + // signature, so coerce for the JsonValue-typed response. + return okResponse(result as unknown as JsonObject); + }, }), groupAction({ diff --git a/packages/onebot/src/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts index 16fbd98c..e785fb40 100644 --- a/packages/onebot/src/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -100,6 +100,24 @@ export const actions = [ }, }), + // rename_group_file — 0x6D6_4。NapCat 入参:file_id + current_parent_directory + // (文件当前所在目录)+ new_name。SnowLuma 的 file_id 即原始 fileId,无需 UUID 解码。 + groupAction({ + name: 'rename_group_file', + summary: '重命名群文件', + params: { + file_id: f.string({ allowEmpty: false }), + current_parent_directory: f.string().default('/'), + new_name: f.string({ allowEmpty: false }), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupFile.rename(p.group_id, p.file_id, p.current_parent_directory || '/', p.new_name); + // {ok:true} 刻意对齐 NapCat RenameGroupFile 的返回体,偏离 SnowLuma 同类 + // 文件写操作(move/delete 返回空 data)——为 NapCat 客户端 drop-in 兼容。 + return okResponse({ ok: true }); + }, + }), + groupAction({ name: 'create_group_file_folder', summary: '创建群文件夹', diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index cba2a727..e757530a 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -81,9 +81,27 @@ export interface ApiActionContext { type ActionHandler = (params: JsonObject) => Promise; +/** A handled-action record handed to debug observers. */ +export interface ActionRecord { + action: string; + params: JsonObject; + response: import('./types').ApiResponse; + ms: number; +} +export type ActionObserver = (rec: ActionRecord) => void; + export class ApiHandler { private readonly handlers = new Map(); private readonly log: Logger; + /** Debug-stream taps — notified after every handled action. Attached + * on-demand (ref-counted) by the WebUI debug stream. */ + private readonly observers = new Set(); + + /** Observe handled actions (debug). Returns an unsubscribe. */ + setObserver(cb: ActionObserver): () => void { + this.observers.add(cb); + return () => { this.observers.delete(cb); }; + } constructor(context: ApiActionContext, uin?: number) { this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog; @@ -132,10 +150,10 @@ export class ApiHandler { this.log.trace(() => [`${action} ⇐ %s`, renderParamsVerbose(params)]); const startedAt = Date.now(); + let response: import('./types').ApiResponse; try { - const response = await handler(params); + response = await handler(params); this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]); - return response; } catch (error) { // Action failures are almost always param-shape problems coming // from the OneBot client; warn (not error) is the right level so @@ -145,7 +163,23 @@ export class ApiHandler { error instanceof Error ? error.message : String(error), error instanceof Error ? (error.stack ?? '') : ''); const message = error instanceof Error ? error.message : 'internal error'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); + response = failedResponse(RETCODE.INTERNAL_ERROR, message); + } + this.notifyObservers(action, params, response, Date.now() - startedAt); + return response; + } + + private notifyObservers( + action: string, + params: JsonObject, + response: import('./types').ApiResponse, + ms: number, + ): void { + if (!this.observers.size) return; + for (const cb of this.observers) { + try { cb({ action, params, response, ms }); } catch (err) { + this.log.warn('action observer error: %s', err instanceof Error ? err.message : String(err)); + } } } diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 95c15169..a7286de1 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -2,7 +2,7 @@ import { createLogger, type Logger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/protocol/format'; import path from 'path'; -import { ApiHandler } from './api-handler'; +import { ApiHandler, type ActionObserver } from './api-handler'; import type { ConverterContext } from './event-converter'; import { registerEventPipeline } from './event-pipeline'; import { buildApiContext, type OneBotInstanceContext } from './instance-context'; @@ -24,7 +24,7 @@ import { type NetworkAdapterContext, } from './network'; import { ReactionStore } from './reaction-store'; -import type { JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types'; +import type { ApiResponse, JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types'; const moduleLog = createLogger('Event'); @@ -59,6 +59,20 @@ export class OneBotInstance { return this.networkManager.describeStatuses(); } + // ── Debug taps (WebUI debug stream / tester) ── + /** Tap every emitted OneBot event for this account. Returns an unsubscribe. */ + subscribeDebugEvents(cb: (event: JsonObject) => void): () => void { + return this.networkManager.subscribeDebug(cb); + } + /** Observe every handled action for this account. Returns an unsubscribe. */ + observeActions(cb: ActionObserver): () => void { + return this.apiHandler.setObserver(cb); + } + /** Invoke an OneBot action against this account (debug tester). */ + invokeAction(action: string, params: JsonObject): Promise { + return this.apiHandler.handle(action, params); + } + constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) { this.uin = uin; this.bridge = bridge; diff --git a/packages/onebot/src/network/network-manager.ts b/packages/onebot/src/network/network-manager.ts index 7b3eb226..89f82da7 100644 --- a/packages/onebot/src/network/network-manager.ts +++ b/packages/onebot/src/network/network-manager.ts @@ -9,6 +9,14 @@ type AnyAdapter = IOneBotNetworkAdapter; export class OneBotNetworkManager { private readonly adapters = new Map(); + /** Debug-stream taps — notified for every emitted event regardless of adapter + * state. Attached on-demand (ref-counted) by the WebUI debug stream. */ + private readonly debugSubscribers = new Set<(event: JsonObject) => void>(); + + subscribeDebug(cb: (event: JsonObject) => void): () => void { + this.debugSubscribers.add(cb); + return () => { this.debugSubscribers.delete(cb); }; + } register(adapter: IOneBotNetworkAdapter): void { const existing = this.adapters.get(adapter.name); @@ -75,6 +83,14 @@ export class OneBotNetworkManager { } async emitEvent(event: JsonObject): Promise { + // Notify debug taps first — before the adapter check — so the debug stream + // sees every event even when no adapter is connected. Never let a tap throw + // into the dispatch path. + if (this.debugSubscribers.size) { + for (const cb of this.debugSubscribers) { + try { cb(event); } catch (err) { log.warn('debug subscriber error: %s', errMessage(err)); } + } + } if (!this.hasActiveAdapters()) return; const payload = buildDispatchPayload(event); const tasks: Promise[] = []; diff --git a/packages/onebot/tests/debug-seams.test.ts b/packages/onebot/tests/debug-seams.test.ts new file mode 100644 index 00000000..6102d230 --- /dev/null +++ b/packages/onebot/tests/debug-seams.test.ts @@ -0,0 +1,80 @@ +import { describe, it, expect, vi } from 'vitest'; +import { OneBotNetworkManager } from '../src/network/network-manager'; +import { ApiHandler, type ApiActionContext } from '../src/api-handler'; + +// ApiHandler's register* only define handlers (closures) at construction — they +// don't touch ctx — so a throwing proxy is a safe minimal context. +function fakeCtx(): ApiActionContext { + return new Proxy({} as ApiActionContext, { + get(_t, prop) { throw new Error(`ctx.${String(prop)} not stubbed`); }, + }); +} + +describe('OneBotNetworkManager.subscribeDebug', () => { + it('notifies debug subscribers on emitEvent even with no active adapters', async () => { + const nm = new OneBotNetworkManager(); + const seen: unknown[] = []; + nm.subscribeDebug((e) => seen.push(e)); + await nm.emitEvent({ post_type: 'meta_event', x: 1 }); + expect(seen).toEqual([{ post_type: 'meta_event', x: 1 }]); + }); + + it('stops notifying after unsubscribe', async () => { + const nm = new OneBotNetworkManager(); + const cb = vi.fn(); + const off = nm.subscribeDebug(cb); + await nm.emitEvent({ a: 1 }); + off(); + await nm.emitEvent({ a: 2 }); + expect(cb).toHaveBeenCalledTimes(1); + expect(cb).toHaveBeenCalledWith({ a: 1 }); + }); + + it('a throwing subscriber does not break emitEvent', async () => { + const nm = new OneBotNetworkManager(); + nm.subscribeDebug(() => { throw new Error('boom'); }); + await expect(nm.emitEvent({ a: 1 })).resolves.toBeUndefined(); + }); +}); + +describe('ApiHandler.setObserver', () => { + it('fires after a successful action with {action, params, response, ms}', async () => { + const h = new ApiHandler(fakeCtx()); + h.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: 'pong' })); + const recs: Array<{ action: string; response: { status: string } }> = []; + h.setObserver((r) => recs.push(r as any)); + const res = await h.handle('ping', { x: 1 }); + expect(res).toMatchObject({ status: 'ok', data: 'pong' }); + expect(recs).toHaveLength(1); + expect(recs[0]).toMatchObject({ action: 'ping', params: { x: 1 }, response: { status: 'ok' } }); + expect(typeof (recs[0] as any).ms).toBe('number'); + }); + + it('fires on a thrown action with the failure response', async () => { + const h = new ApiHandler(fakeCtx()); + h.registerAction('boom', async () => { throw new Error('kaboom'); }); + const recs: any[] = []; + h.setObserver((r) => recs.push(r)); + await h.handle('boom', {}); + expect(recs).toHaveLength(1); + expect(recs[0].response.status).toBe('failed'); + }); + + it('unsubscribe stops observation', async () => { + const h = new ApiHandler(fakeCtx()); + h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 })); + const cb = vi.fn(); + const off = h.setObserver(cb); + await h.handle('ping', {}); + off(); + await h.handle('ping', {}); + expect(cb).toHaveBeenCalledTimes(1); + }); + + it('a throwing observer does not break handle', async () => { + const h = new ApiHandler(fakeCtx()); + h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 })); + h.setObserver(() => { throw new Error('observer boom'); }); + await expect(h.handle('ping', {})).resolves.toMatchObject({ status: 'ok' }); + }); +}); diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index 1ab9886b..b56a248f 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -350,12 +350,6 @@ describe('extended-actions / get_group_ignore_add_request', () => { }); }); -describe('extended-actions / get_group_shut_list', () => { - it('returns empty list (oidb not yet wrapped)', async () => { - const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_group_shut_list', {}); - expect(res).toEqual({ status: 'ok', retcode: 0, data: [] }); - }); -}); // ─── Tier 1: delete_group_folder alias ─── @@ -620,3 +614,231 @@ describe('extended-actions / set_group_portrait', () => { expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'highway 500' }); }); }); + +// ─── Wave 1: get_group_shut_list ─── + +describe('extended-actions / get_group_shut_list', () => { + it('returns only currently-muted members in NapCat shape', async () => { + const nowSec = Math.floor(Date.now() / 1000); + const fetchGroupMemberList = vi.fn(async () => [ + { uin: 111, uid: 'u1', nickname: 'muted', card: '', role: 'member', level: 1, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: nowSec + 3600 }, + { uin: 222, uid: 'u2', nickname: 'free', card: '', role: 'member', level: 1, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: 0 }, + { uin: 333, uid: 'u3', nickname: 'expired', card: '', role: 'member', level: 1, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: nowSec - 3600 }, + ]); + const bridge = fakeBridge({ fetchGroupMemberList: fetchGroupMemberList as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_group_shut_list', { group_id: 12345 }); + expect(res.status).toBe('ok'); + expect(fetchGroupMemberList).toHaveBeenCalledWith(12345); + expect(res.data).toEqual([ + { user_id: 111, nickname: 'muted', shut_up_time: nowSec + 3600 }, + ]); + }); + + it('rejects missing group_id', async () => { + const bridge = fakeBridge({ fetchGroupMemberList: vi.fn() as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_group_shut_list', {}); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + }); +}); + +// ─── Wave 1: get_file (compose image→record cache) ─── + +describe('extended-actions / get_file', () => { + const imageInfo = { file: 'a.jpg', url: 'http://x/a.jpg', file_size: '12', file_name: 'a.jpg' }; + const recordInfo = { file: 'b.amr', url: 'http://x/b.amr', file_size: '34', file_name: 'b.amr' }; + + it('resolves an image file_id via the image cache', async () => { + const getImageInfo = vi.fn(async () => imageInfo); + const getRecordInfo = vi.fn(async () => null); + const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })).handle('get_file', { file_id: 'a.jpg' }); + expect(res).toMatchObject({ status: 'ok', data: imageInfo }); + expect(getRecordInfo).not.toHaveBeenCalled(); + }); + + it('falls back to the record cache when not an image', async () => { + const getImageInfo = vi.fn(async () => null); + const getRecordInfo = vi.fn(async () => recordInfo); + const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })).handle('get_file', { file: 'b.amr' }); + expect(res).toMatchObject({ status: 'ok', data: recordInfo }); + }); + + it('fails with a neutral cache-miss message that points to the group-file path', async () => { + // A double cache miss is runtime-indistinguishable between "a group-file + // file_id was passed (unsupported here)" and "the image/voice really isn't + // cached" — run() does not parse the id's shape. So the error must stay + // neutral: state the cache miss, then offer the group-file path as + // guidance, without asserting "unsupported". + const getImageInfo = vi.fn(async () => null); + const getRecordInfo = vi.fn(async () => null); + const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })).handle('get_file', { file_id: 'nope' }); + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + const wording = (res as { wording?: string }).wording ?? ''; + expect(wording).toMatch(/not found in the image\/voice cache/); + expect(wording).toMatch(/get_group_file_url/); + expect(wording).not.toMatch(/unsupported/); + }); + + it('rejects when neither file nor file_id is given', async () => { + const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_file', {}); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + }); +}); + +// ─── Wave 2: rename_group_file (0x6D6_4) ─── + +describe('extended-actions / rename_group_file', () => { + it('renames a group file via apis.groupFile.rename', async () => { + const rename = vi.fn(async () => undefined); + const bridge = fakeBridge({ apis: { groupFile: { rename } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('rename_group_file', { + group_id: 12345, file_id: '/abc', current_parent_directory: '/', new_name: 'new.txt', + }); + expect(res.status).toBe('ok'); + expect(rename).toHaveBeenCalledWith(12345, '/abc', '/', 'new.txt'); + }); + + it('rejects missing required params', async () => { + const rename = vi.fn(); + const bridge = fakeBridge({ apis: { groupFile: { rename } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('rename_group_file', { group_id: 12345, file_id: '/abc' }); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(rename).not.toHaveBeenCalled(); + }); + + it('surfaces oidb errors (handler maps a thrown error to INTERNAL_ERROR, as its sibling file ops do)', async () => { + const rename = vi.fn(async () => { throw new Error('rename rejected'); }); + const bridge = fakeBridge({ apis: { groupFile: { rename } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('rename_group_file', { + group_id: 1, file_id: '/a', current_parent_directory: '/', new_name: 'x', + }); + expect(res).toMatchObject({ status: 'failed', retcode: 1200, wording: 'rename rejected' }); + }); +}); + +// ─── Wave 2: get_rkey_server ─── + +describe('extended-actions / get_rkey_server', () => { + it('reshapes download rkeys into the NapCat server shape (private=10, group=20)', async () => { + const nowSec = Math.floor(Date.now() / 1000); + const getDownloadRKeys = vi.fn(async () => [ + { rkey: '&rkey=PRIV', type: 10, ttl: 3600, create_time: 100 }, + { rkey: '&rkey=GRP', type: 20, ttl: 7200, create_time: 200 }, + ]); + const res = await makeHandler(fakeCtx(fakeBridge(), { getDownloadRKeys })).handle('get_rkey_server', {}); + expect(res.status).toBe('ok'); + const d = res.data as { private_rkey?: string; group_rkey?: string; expired_time: number; name: string }; + expect(d.private_rkey).toBe('&rkey=PRIV'); + expect(d.group_rkey).toBe('&rkey=GRP'); + expect(d.name).toBe('SnowLuma'); + // expiry = now + min(ttl) = now + 3600 (allow a 1s clock tick) + expect(d.expired_time).toBeGreaterThanOrEqual(nowSec + 3600); + expect(d.expired_time).toBeLessThanOrEqual(nowSec + 3601); + }); + + it('leaves a missing scope undefined', async () => { + const getDownloadRKeys = vi.fn(async () => [ + { rkey: '&rkey=PRIV', type: 10, ttl: 3600, create_time: 100 }, + ]); + const res = await makeHandler(fakeCtx(fakeBridge(), { getDownloadRKeys })).handle('get_rkey_server', {}); + const d = res.data as { private_rkey?: string; group_rkey?: string }; + expect(d.private_rkey).toBe('&rkey=PRIV'); + expect(d.group_rkey).toBeUndefined(); + }); + + it('fails (not an expired empty shell) when no rkey is available', async () => { + const getDownloadRKeys = vi.fn(async () => []); + const res = await makeHandler(fakeCtx(fakeBridge(), { getDownloadRKeys })).handle('get_rkey_server', {}); + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + }); +}); + +// ─── Wave 3: ocr_image / .ocr_image (OIDB 0xE07_0) ─── + +describe('extended-actions / ocr_image', () => { + const ocrResult = { texts: [{ text: 'hello', confidence: 99, coordinates: [{ x: 1, y: 2 }] }], language: 'en' }; + + it('OCRs an http(s) image URL directly', async () => { + const ocrImage = vi.fn(async () => ocrResult); + const bridge = fakeBridge({ apis: { misc: { ocrImage } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('ocr_image', { image: 'https://x/a.jpg' }); + expect(res).toMatchObject({ status: 'ok', data: ocrResult }); + expect(ocrImage).toHaveBeenCalledWith('https://x/a.jpg'); + }); + + it('resolves a cached image file_id to a url via getImageInfo', async () => { + const ocrImage = vi.fn(async () => ocrResult); + const getImageInfo = vi.fn(async () => ({ url: 'https://cdn/resolved.jpg' })); + const bridge = fakeBridge({ apis: { misc: { ocrImage } } }); + const res = await makeHandler(fakeCtx(bridge, { getImageInfo })).handle('ocr_image', { image: 'abc.jpg' }); + expect(res.status).toBe('ok'); + expect(ocrImage).toHaveBeenCalledWith('https://cdn/resolved.jpg'); + }); + + it('.ocr_image shares the same handler', async () => { + const ocrImage = vi.fn(async () => ocrResult); + const bridge = fakeBridge({ apis: { misc: { ocrImage } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('.ocr_image', { image: 'http://x/a.jpg' }); + expect(res.status).toBe('ok'); + }); + + it('fails when the id cannot be resolved to a url', async () => { + const ocrImage = vi.fn(); + const getImageInfo = vi.fn(async () => null); + const bridge = fakeBridge({ apis: { misc: { ocrImage } } }); + const res = await makeHandler(fakeCtx(bridge, { getImageInfo })).handle('ocr_image', { image: 'unknown' }); + expect(res.status).toBe('failed'); + expect(ocrImage).not.toHaveBeenCalled(); + }); + + it('rejects missing image', async () => { + const bridge = fakeBridge({ apis: { misc: { ocrImage: vi.fn() } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('ocr_image', {}); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + }); +}); + +// ─── TierB Phase 1: compat stubs (model_show / online_clients / mark_all_as_read) ─── +// These are kernel-only in NapCat (mock/no-op), so SnowLuma ships honest +// compat shapes rather than RE-ing a wire that doesn't exist. We pin the +// response *shape* of each. NOTE two deliberate divergences from NapCat: +// • _get_model_show reuses NapCat's array/variants shape but ECHOES the +// requested model instead of NapCat's hardcoded 'napcat'. +// • get_online_clients returns the OneBot-v11/go-cqhttp { clients: [] } +// envelope, NOT NapCat's (non-standard) bare []. A strict-NapCat client +// would expect an array here; we intentionally follow the spec instead. + +describe('extended-actions / TierB compat stubs', () => { + it('_get_model_show returns the napcat-shaped variants array, echoing the model', async () => { + const res = await makeHandler(fakeCtx(fakeBridge())).handle('_get_model_show', { model: 'MyPhone' }); + expect(res.status).toBe('ok'); + // NapCat shape: data = [{ variants: { model_show, need_pay } }] + expect(Array.isArray(res.data)).toBe(true); + expect(res.data).toHaveLength(1); + expect((res.data as any)[0].variants).toMatchObject({ model_show: 'MyPhone', need_pay: false }); + }); + + it('_get_model_show defaults model_show to snowluma when model is absent or empty', async () => { + for (const params of [{}, { model: '' }]) { + const res = await makeHandler(fakeCtx(fakeBridge())).handle('_get_model_show', params); + expect(res.status).toBe('ok'); + expect((res.data as any)[0].variants.model_show).toBe('snowluma'); + expect((res.data as any)[0].variants.need_pay).toBe(false); + } + }); + + it('_set_model_show is an accepted no-op', async () => { + const res = await makeHandler(fakeCtx(fakeBridge())).handle('_set_model_show', { model: 'x', model_show: 'y' }); + expect(res).toMatchObject({ status: 'ok', retcode: 0, data: null }); + }); + + it('get_online_clients returns the OneBot-standard {clients:[]} envelope', async () => { + const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_online_clients', {}); + expect(res.status).toBe('ok'); + expect(res.data).toMatchObject({ clients: [] }); + }); + + it('_mark_all_as_read is an accepted no-op', async () => { + const res = await makeHandler(fakeCtx(fakeBridge())).handle('_mark_all_as_read', {}); + expect(res).toMatchObject({ status: 'ok', retcode: 0 }); + }); +}); diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index f06035af..45d35622 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/proto-defs", - "version": "1.9.12", + "version": "1.9.13", "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).", @@ -70,6 +70,10 @@ "./oidb-actions/media": { "types": "./src/oidb-actions/media.ts", "default": "./src/oidb-actions/media.ts" + }, + "./oidb-actions/ocr": { + "types": "./src/oidb-actions/ocr.ts", + "default": "./src/oidb-actions/ocr.ts" } }, "scripts": { diff --git a/packages/proto-defs/src/oidb-actions/group-file.ts b/packages/proto-defs/src/oidb-actions/group-file.ts index 40ed92d4..007bb455 100644 --- a/packages/proto-defs/src/oidb-actions/group-file.ts +++ b/packages/proto-defs/src/oidb-actions/group-file.ts @@ -84,10 +84,18 @@ export interface OidbGroupFileMoveReq { parentDirectory?: pb<5, string>; targetDirectory?: pb<6, string>; } +export interface OidbGroupFileRenameReq { + groupUin?: pb<1, uint_32>; + busId?: pb<3, uint_32>; + fileId?: pb<4, string>; + parentFolder?: pb<5, string>; + newFileName?: pb<6, string>; +} export interface OidbGroupFileReq { file?: pb<1, OidbGroupFileUploadReq>; download?: pb<3, OidbGroupFileDownloadReq>; delete?: pb<4, OidbGroupFileDeleteReq>; + rename?: pb<5, OidbGroupFileRenameReq>; move?: pb<6, OidbGroupFileMoveReq>; } export interface OidbGroupFileUploadResp { @@ -121,6 +129,7 @@ export interface OidbGroupFileResp { upload?: pb<1, OidbGroupFileUploadResp>; download?: pb<3, OidbGroupFileDownloadResp>; delete?: pb<4, OidbGroupFileRetResp>; + rename?: pb<5, OidbGroupFileRetResp>; move?: pb<6, OidbGroupFileRetResp>; } export interface OidbGroupSendFileInfo { diff --git a/packages/proto-defs/src/oidb-actions/ocr.ts b/packages/proto-defs/src/oidb-actions/ocr.ts new file mode 100644 index 00000000..e1a8016d --- /dev/null +++ b/packages/proto-defs/src/oidb-actions/ocr.ts @@ -0,0 +1,50 @@ +// OIDB 0xE07_0 — server-side image OCR. Field tags verified against +// NapCat's Oidb.0xE07 proto AND Lagrange.Core's OidbSvcTrpcTcp.0xE07_0 +// (the two agree; NapCat's transformer builds with cmd 0xEB7, which is a +// typo — the proto name + Lagrange + the `OidbSvcTrpcTcp.0xe07_0` wire +// name are authoritative). Request takes an image URL (server fetches it). + +import type { pb, pb_repeated, int_32, uint_32, bool } from '@snowluma/proton'; + +export interface OcrReqBody { + imageUrl?: pb<1, string>; + languageType?: pb<2, uint_32>; + scene?: pb<3, uint_32>; + originMd5?: pb<10, string>; + afterCompressMd5?: pb<11, string>; + afterCompressFileSize?: pb<12, string>; + afterCompressWeight?: pb<13, string>; + afterCompressHeight?: pb<14, string>; + isCut?: pb<15, bool>; +} +export interface ImageOcrReq { + version?: pb<1, uint_32>; + client?: pb<2, uint_32>; + entrance?: pb<3, uint_32>; + ocrReqBody?: pb<10, OcrReqBody>; +} + +export interface OcrCoordinate { + x?: pb<1, int_32>; + y?: pb<2, int_32>; +} +export interface OcrPolygon { + coordinates?: pb_repeated<1, OcrCoordinate>; +} +export interface OcrTextDetection { + detectedText?: pb<1, string>; + confidence?: pb<2, uint_32>; + polygon?: pb<3, OcrPolygon>; + advancedInfo?: pb<4, string>; +} +export interface OcrRspBody { + textDetections?: pb_repeated<1, OcrTextDetection>; + language?: pb<2, string>; + requestId?: pb<3, string>; +} +export interface ImageOcrResp { + retCode?: pb<1, int_32>; + errMsg?: pb<2, string>; + wording?: pb<3, string>; + ocrRspBody?: pb<10, OcrRspBody>; +} diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 402d8f9e..398eb333 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/protocol", - "version": "1.9.12", + "version": "1.9.13", "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/'`.", @@ -99,6 +99,10 @@ "types": "./src/oidb-services/misc/translate-en-to-zh.ts", "default": "./src/oidb-services/misc/translate-en-to-zh.ts" }, + "./oidb-services/misc/image-ocr": { + "types": "./src/oidb-services/misc/image-ocr.ts", + "default": "./src/oidb-services/misc/image-ocr.ts" + }, "./oidb-services/misc/click-inline-keyboard-button": { "types": "./src/oidb-services/misc/click-inline-keyboard-button.ts", "default": "./src/oidb-services/misc/click-inline-keyboard-button.ts" @@ -263,6 +267,10 @@ "types": "./src/oidb-services/group-file/move-group-file.ts", "default": "./src/oidb-services/group-file/move-group-file.ts" }, + "./oidb-services/group-file/rename-group-file": { + "types": "./src/oidb-services/group-file/rename-group-file.ts", + "default": "./src/oidb-services/group-file/rename-group-file.ts" + }, "./oidb-services/group-file/create-group-folder": { "types": "./src/oidb-services/group-file/create-group-folder.ts", "default": "./src/oidb-services/group-file/create-group-folder.ts" diff --git a/packages/protocol/src/oidb-services/group-file/rename-group-file.ts b/packages/protocol/src/oidb-services/group-file/rename-group-file.ts new file mode 100644 index 00000000..6b2ca5af --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/rename-group-file.ts @@ -0,0 +1,49 @@ +// 0x6D6_4 — rename a group file (not a folder; that is 0x6D7_2). The +// rename slot lives on the shared `OidbGroupFileReq` envelope at field 5. +// Wire fields verified against NapCat's Oidb.0x6D6 transformer +// (busId=102, parentFolder = the file's CURRENT parent directory). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileReq, OidbGroupFileResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero } from '../shared'; + +export namespace RenameGroupFile { + export const command = 0x6D6; + export const subCommand = 4; + export const uinForm = true; + + export interface Params { + groupId: number; fileId: string; + parentDirectory: string; newFileName: string; + } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupFileReq => ({ + rename: { + groupUin: p.groupId, + busId: 102, + fileId: p.fileId, + parentFolder: p.parentDirectory, + newFileName: p.newFileName, + }, + }); + + export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): void => { + const result = body.rename; + if (!result) throw new Error('group file rename response missing'); + ensureRetCodeZero('group file rename', result.retCode, result.retMsg, result.clientWording); + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, RenameGroupFile, params); +} diff --git a/packages/protocol/src/oidb-services/misc/image-ocr.ts b/packages/protocol/src/oidb-services/misc/image-ocr.ts new file mode 100644 index 00000000..43d69fce --- /dev/null +++ b/packages/protocol/src/oidb-services/misc/image-ocr.ts @@ -0,0 +1,65 @@ +// 0xE07_0 — server-side image OCR. Sends an image URL; the server fetches +// it and returns detected text + bounding-box polygons. Cmd/sub verified +// against Lagrange.Core ([Service("OidbSvcTrpcTcp.0xe07_0")]) and NapCat's +// Oidb.0xE07 proto (NapCat's transformer cmd 0xEB7 is a typo). uinForm is +// false (NapCat build(..., false, false); Lagrange sends no uid). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { ImageOcrReq, ImageOcrResp } from '@snowluma/proto-defs/oidb-actions/ocr'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero } from '../shared'; + +/** One detected text run with its bounding-box vertices. */ +export interface OcrText { + text: string; + confidence: number; + coordinates: Array<{ x: number; y: number }>; +} +export interface OcrResult { + texts: OcrText[]; + language: string; +} + +export namespace ImageOcr { + export const command = 0xE07; + export const subCommand = 0; + + export interface Params { imageUrl: string; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): ImageOcrReq => ({ + version: 1, + client: 0, + entrance: 1, + ocrReqBody: { + imageUrl: p.imageUrl, + originMd5: '', + afterCompressMd5: '', + afterCompressFileSize: '', + afterCompressWeight: '', + afterCompressHeight: '', + isCut: false, + }, + }); + + export const deserialize = (_ctx: Deps, body: ImageOcrResp): OcrResult => { + ensureRetCodeZero('image ocr', body.retCode, body.errMsg, body.wording); + const rsp = body.ocrRspBody; + const texts: OcrText[] = (rsp?.textDetections ?? []).map((d) => ({ + text: d.detectedText ?? '', + confidence: d.confidence ?? 0, + coordinates: (d.polygon?.coordinates ?? []).map((c) => ({ x: c.x ?? 0, y: c.y ?? 0 })), + })); + return { texts, language: rsp?.language ?? '' }; + }; + + 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, ImageOcr, params); +} diff --git a/packages/protocol/src/packet-pipeline.ts b/packages/protocol/src/packet-pipeline.ts index ac5e388d..5b4f66ab 100644 --- a/packages/protocol/src/packet-pipeline.ts +++ b/packages/protocol/src/packet-pipeline.ts @@ -163,6 +163,19 @@ export class IncomingPacketPipeline { private async dispatchGroupInvite(event: Extract): Promise { const uid = event.fromUid; if (uid) { + // Record the requester's identity up-front (synchronously), mirroring the + // friend_request path — uid-bearing group_invites take this async branch + // and would otherwise never store the inviter's uid↔uin when the uin is + // already known (needsProfile=false). uin equal to the group's own uin is + // the legacy decoder-pollution signature → pass 0 so the map write is + // skipped (rememberUidUin short-circuits on uin <= 0). + this.deps.identity.rememberRequestIdentity({ + groupId: event.groupId, + uid, + uin: event.fromUin > 0 && event.fromUin !== event.groupId ? event.fromUin : 0, + source: 'group_request', + }); + const subType = event.subType === 'invite' ? 'invite' : 'add'; // ALWAYS fetch the verify comment (it's never in the push). Resolve // the UID→UIN profile only when the requester isn't already known — @@ -180,6 +193,13 @@ export class IncomingPacketPipeline { if (needsProfile) { if (profileR.status === 'fulfilled' && profileR.value && profileR.value.uin > 0) { event.fromUin = profileR.value.uin; + // uin was unknown/polluted at entry; now resolved → self-heal the map. + this.deps.identity.rememberRequestIdentity({ + groupId: event.groupId, + uid, + uin: event.fromUin, + source: 'group_request', + }); } else if (profileR.status === 'rejected') { this.log.warn('failed to resolve stranger profile: uid=%s err=%s', uid, profileR.reason instanceof Error ? profileR.reason.message : String(profileR.reason)); diff --git a/packages/protocol/tests/oidb-services/group-file/rename-group-file.test.ts b/packages/protocol/tests/oidb-services/group-file/rename-group-file.test.ts new file mode 100644 index 00000000..8b178ba2 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/rename-group-file.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupFileReq, OidbGroupFileResp } from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { RenameGroupFile } from '../../../src/oidb-services/group-file/rename-group-file'; + +// A success response the real server would send: command/sub echoed, rename +// ret slot with retCode 0. Lets `invoke`'s deserialize pass so we can assert +// the request wire (cmd name + body) without it throwing on an empty body. +function okRenameResponse(): Buffer { + const env: OidbBase = { + command: 0x6D6, subCommand: 4, body: { rename: { retCode: 0 } }, + }; + return Buffer.from(protobuf_encode>(env)); +} + +function makeSender() { + const defaultResp: SendPacketResult = { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: okRenameResponse(), + }; + return { sendRawPacket: vi.fn(async () => defaultResp) }; +} + +describe('RenameGroupFile namespace', () => { + it('declares command 0x6D6 sub 4 (rename slot), uin form', () => { + expect(RenameGroupFile.command).toBe(0x6D6); + expect(RenameGroupFile.subCommand).toBe(4); + expect(RenameGroupFile.uinForm).toBe(true); + }); + + it('serializes into the rename slot with busId 102 and the current parent folder', () => { + const out = RenameGroupFile.serialize({} as any, { + groupId: 12345, fileId: '/abc', parentDirectory: '/sub', newFileName: 'new.txt', + }); + expect(out).toEqual({ + rename: { + groupUin: 12345, busId: 102, fileId: '/abc', parentFolder: '/sub', newFileName: 'new.txt', + }, + }); + }); + + it('round-trips the rename body through the OIDB envelope (locks the pb field tags)', async () => { + const sender = makeSender(); + await RenameGroupFile.invoke(sender, { + groupId: 12345, fileId: '/abc', parentDirectory: '/', newFileName: 'new.txt', + }); + expect(sender.sendRawPacket).toHaveBeenCalledOnce(); + const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x6d6_4'); + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0x6D6); + expect(env.subCommand).toBe(4); + expect(env.body.rename).toMatchObject({ + groupUin: 12345, busId: 102, fileId: '/abc', parentFolder: '/', newFileName: 'new.txt', + }); + }); + + it('deserialize throws when the rename slot is missing from the response', () => { + expect(() => RenameGroupFile.deserialize({} as any, {})).toThrow(/rename response missing/); + }); +}); diff --git a/packages/protocol/tests/oidb-services/misc/image-ocr.test.ts b/packages/protocol/tests/oidb-services/misc/image-ocr.test.ts new file mode 100644 index 00000000..acdf61e4 --- /dev/null +++ b/packages/protocol/tests/oidb-services/misc/image-ocr.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { ImageOcrReq, ImageOcrResp } from '@snowluma/proto-defs/oidb-actions/ocr'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { ImageOcr } from '../../../src/oidb-services/misc/image-ocr'; + +// A server OCR response: retCode 0, one text detection with a 2-vertex box. +function ocrResponse(): Buffer { + const env: OidbBase = { + command: 0xE07, subCommand: 0, + body: { + retCode: 0, + ocrRspBody: { + language: 'zh', + textDetections: [ + { detectedText: '你好', confidence: 95, polygon: { coordinates: [{ x: 1, y: 2 }, { x: 3, y: 4 }] } }, + ], + }, + }, + }; + return Buffer.from(protobuf_encode>(env)); +} + +function makeSender(resp = ocrResponse()) { + const r: SendPacketResult = { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: resp, + }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('ImageOcr namespace', () => { + it('declares command 0xE07 sub 0 (no uin form)', () => { + expect(ImageOcr.command).toBe(0xE07); + expect(ImageOcr.subCommand).toBe(0); + expect(ImageOcr.uinForm).toBeUndefined(); // defaults to false in invokeOidb + }); + + it('serializes the image url into ocrReqBody with the fixed version/client/entrance header', () => { + const out = ImageOcr.serialize({} as any, { imageUrl: 'https://x/a.jpg' }); + expect(out).toMatchObject({ version: 1, client: 0, entrance: 1 }); + expect(out.ocrReqBody).toMatchObject({ imageUrl: 'https://x/a.jpg', isCut: false }); + }); + + it('routes to OidbSvcTrpcTcp.0xe07_0 and encodes the exact wire bytes (fixed byte-oracle locks pb tags)', async () => { + const sender = makeSender(); + await ImageOcr.invoke(sender, { imageUrl: 'https://x/a.jpg' }); + const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0xe07_0'); + // Independent byte-oracle: a fixed hex constant, NOT re-derived from the + // proto, so a tag change actually goes red (a symmetric encode→decode + // round-trip would not). Hand-decoded: 08 871c = field1 command varint + // 0xE07; 22 17 = field4 body (23B); body: 08 01 version=1, 18 01 + // entrance=1 (client=0 omitted), 52 11 = field10 ocrReqBody (17B): + // 0a 0f = field1 imageUrl + "https://x/a.jpg". + expect(Buffer.from(bytes).toString('hex')) + .toBe('08871c22170801180152110a0f68747470733a2f2f782f612e6a7067'); + // And the structure decodes back as expected. + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0xE07); + expect(env.body.ocrReqBody?.imageUrl).toBe('https://x/a.jpg'); + }); + + it('deserializes an empty ocr body to {texts:[], language:""}', () => { + expect(ImageOcr.deserialize({} as any, { retCode: 0 })).toEqual({ texts: [], language: '' }); + }); + + it('deserializes text detections + coordinates + language', async () => { + const result = await ImageOcr.invoke(makeSender(), { imageUrl: 'https://x/a.jpg' }); + expect(result.language).toBe('zh'); + expect(result.texts).toEqual([ + { text: '你好', confidence: 95, coordinates: [{ x: 1, y: 2 }, { x: 3, y: 4 }] }, + ]); + }); + + it('throws on a non-zero retCode', () => { + expect(() => ImageOcr.deserialize({} as any, { retCode: 5, errMsg: 'bad', wording: 'nope' })) + .toThrow(); + }); +}); diff --git a/packages/proton/package.json b/packages/proton/package.json index 70b41671..ec8c786f 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/proton", - "version": "1.9.12", + "version": "1.9.13", "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 5c716c59..daff2fe7 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/runtime", - "version": "1.9.12", + "version": "1.9.13", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 77ac1f33..fea973d1 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.9.12", + "version": "1.9.13", "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 47d0032e..456f9698 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.9.12", + "version": "1.9.13", "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 55947c72..61880dce 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/websocket", - "version": "1.9.12", + "version": "1.9.13", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 1afb0a5f..df0af7a2 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,7 +1,7 @@ { "name": "webui", "private": true, - "version": "1.9.12", + "version": "1.9.13", "type": "module", "scripts": { "dev": "vite", diff --git a/packages/webui/src/components/config/node-edit-dialog.tsx b/packages/webui/src/components/config/node-edit-dialog.tsx index 39ff38de..2e70eca8 100644 --- a/packages/webui/src/components/config/node-edit-dialog.tsx +++ b/packages/webui/src/components/config/node-edit-dialog.tsx @@ -16,6 +16,7 @@ import { } from '@/components/ui/dialog'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; +import { Select } from '@/components/ui/select'; import { cn } from '@/lib/utils'; import type { HttpClientNetwork, @@ -447,17 +448,13 @@ function SelectField({ return (
- onChange(e.target.value as T)}> {options.map((opt) => ( ))} - +
); } diff --git a/packages/webui/src/components/layout/sidebar.tsx b/packages/webui/src/components/layout/sidebar.tsx index bffdd7e3..1feb4258 100644 --- a/packages/webui/src/components/layout/sidebar.tsx +++ b/packages/webui/src/components/layout/sidebar.tsx @@ -1,4 +1,4 @@ -import { Check, Eye, EyeOff, GripVertical, LayoutDashboard, Lock, PlugZap, Settings, Sparkles, SlidersHorizontal, Terminal } from 'lucide-react'; +import { Bug, Check, Eye, EyeOff, GripVertical, LayoutDashboard, Lock, PlugZap, Settings, Sparkles, SlidersHorizontal, Terminal } from 'lucide-react'; import { motion, Reorder } from 'motion/react'; import { Link, useRouterState } from '@tanstack/react-router'; import { ScrollArea } from '@/components/ui/scroll-area'; @@ -21,6 +21,7 @@ export const NAV_ITEMS: NavItem[] = [ { to: '/processes', label: '进程注入', icon: PlugZap, description: '加载 / 卸载 / 登录' }, { to: '/config', label: '节点配置', icon: Settings, description: 'OneBot 协议端点' }, { to: '/logs', label: '日志', icon: Terminal, description: '实时事件流' }, + { to: '/debug', label: '调试', icon: Bug, description: '测试台与实时活动' }, { to: '/settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' }, ]; diff --git a/packages/webui/src/components/pages/debug-page.tsx b/packages/webui/src/components/pages/debug-page.tsx new file mode 100644 index 00000000..ff01a636 --- /dev/null +++ b/packages/webui/src/components/pages/debug-page.tsx @@ -0,0 +1,361 @@ +// Debug — a standalone top-level page (Wave A3, redesigned). Apple-HIG flavour: +// clarity (calm type hierarchy, generous whitespace), deference (translucent +// chrome, content-first), depth (soft layered cards, a sliding segmented +// control). Two tools over /api/debug/*: +// • Action 测试台 — pick account + action (schema form / raw JSON), invoke. +// • 实时活动 — merged live SSE of events + action calls. +import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react'; +import { motion } from 'motion/react'; +import { Activity, Bug, ChevronRight, FlaskConical, Loader2, Pause, Play, RadioTower, Trash2 } from 'lucide-react'; +import { Input } from '@/components/ui/input'; +import { Select } from '@/components/ui/select'; +import { Textarea } from '@/components/ui/textarea'; +import { useApi } from '@/lib/api'; +import { cn } from '@/lib/utils'; +import type { DebugActionDoc, DebugInvokeResult, DebugStreamMessage, QQInfo } from '@/types'; + +const STREAM_CAP = 300; + +interface StreamRow { id: number; at: number; msg: Extract } + +function coerceParam(type: string, raw: string): unknown { + if (raw === '') return undefined; + if (type.includes('int') || type === 'number' || type === 'uint') { + const n = Number(raw); + return Number.isFinite(n) ? n : raw; + } + if (type === 'bool' || type === 'boolean') return raw === 'true' || raw === '1'; + return raw; +} + +// ── iOS-style segmented control with a sliding active pill ── +function Segmented({ value, onChange, options }: { + value: T; onChange: (v: T) => void; options: { value: T; label: ReactNode }[]; +}) { + const id = useId(); + return ( +
+ {options.map((o) => { + const active = o.value === value; + return ( + + ); + })} +
+ ); +} + +function Field({ label, children }: { label: ReactNode; children: ReactNode }) { + return ( + + ); +} + +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'; + +export function DebugPage() { + const api = useApi(); + + // ── action tester ── + const [accounts, setAccounts] = useState([]); + const [docs, setDocs] = useState([]); + 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 doc = useMemo(() => docs.find((d) => d.name === actionName), [docs, actionName]); + const effectiveMode = paramMode === 'json' || !doc ? 'json' : 'form'; + + useEffect(() => { + void (async () => { + try { + const [qq, acts] = await Promise.all([api.qqList(), api.debug.actions()]); + setAccounts(qq); + setDocs(acts.actions); + if (qq[0]) setUin(qq[0].uin); + } catch { /* surfaced lazily on invoke */ } + })(); + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + const invoke = async () => { + if (!uin) { setResult({ error: '请选择账号' }); return; } + if (!actionName.trim()) { setResult({ error: '请填写 action' }); return; } + let params: Record = {}; + if (effectiveMode === 'json') { + try { params = JSON.parse(rawJson || '{}'); } catch { setResult({ error: 'params JSON 无效' }); return; } + if (typeof params !== 'object' || params === null || Array.isArray(params)) { setResult({ error: 'params 必须是对象' }); return; } + } else if (doc) { + for (const p of doc.params) { + const v = coerceParam(p.type, fields[p.name] ?? ''); + if (v !== undefined) params[p.name] = v; + } + } + setInvoking(true); + setResult(null); + try { setResult(await api.debug.invoke(uin, actionName.trim(), params)); } + catch (e) { setResult({ error: e instanceof Error ? e.message : '调用失败' }); } + finally { setInvoking(false); } + }; + + const resultFailed = !!result && ('error' in result || result.status === 'failed'); + + // ── live stream ── + const [rows, setRows] = useState([]); + const [paused, setPaused] = useState(false); + const [status, setStatus] = useState<'open' | 'reconnecting' | 'closed'>('closed'); + const [kindFilter, setKindFilter] = useState<'all' | 'event' | 'action'>('all'); + const pausedRef = useRef(paused); + pausedRef.current = paused; + const idRef = useRef(0); + + useEffect(() => { + const off = api.debug.stream( + (m) => { + if (m.kind === 'ready' || pausedRef.current) return; + setRows((prev) => { + const next = [{ id: idRef.current++, at: Date.now(), msg: m }, ...prev]; + return next.length > STREAM_CAP ? next.slice(0, STREAM_CAP) : next; + }); + }, + (s) => setStatus(s), + ); + return off; + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + const visible = rows.filter((r) => kindFilter === 'all' || r.msg.kind === kindFilter); + + return ( +
+ {/* header */} + +
+
+ +
+
+

调试

+

接口测试台与实时活动观测

+
+
+ +
+ +
+ {/* tester */} + +
+ +

Action 测试台

+
+
+ 调用会真实生效(真发消息 / 真踢人等),请谨慎。 +
+ +
+ + + + + { setActionName(e.target.value); setResult(null); }} /> + + {docs.map((d) => )} + + +
+ + {doc && ( +

+ {doc.summary}{doc.returns ? <> · 返回 {doc.returns} : null} +

+ )} + +
+ 参数 + setParamMode(m)} + options={[{ value: 'form', label: '表单' }, { value: 'json', label: 'JSON' }]} + /> +
+ + {effectiveMode === 'json' ? ( +