diff --git a/.editorconfig b/.editorconfig index 3827920d..0193ca80 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,6 +11,9 @@ trim_trailing_whitespace = true [*.{json,yml,yaml,md}] indent_size = 2 +[*.{ts,tsx,mts,cts}] +indent_size = 4 + [*.py] indent_size = 4 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..94076538 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,17 @@ +# Dependencies, build outputs and local tooling +node_modules/ +.pnpm-store/ +dist/ +coverage/ +.turbo/ +.vite/ +.claude/ +dev/ +pnpm-lock.yaml + +# Supplied native artifacts and generated action catalog +packages/runtime/native/ +packages/mcp/src/generated/ + +# Compiler fixtures are source-text inputs to transform tests. +packages/proton/test/fixtures/ diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..6971be29 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,18 @@ +{ + "printWidth": 100, + "tabWidth": 2, + "useTabs": false, + "semi": true, + "singleQuote": true, + "trailingComma": "all", + "arrowParens": "always", + "endOfLine": "lf", + "overrides": [ + { + "files": ["*.ts", "*.tsx", "*.mts", "*.cts"], + "options": { + "tabWidth": 4 + } + } + ] +} diff --git a/AGENTS.md b/AGENTS.md index c2498ea8..da70ed13 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,6 +59,8 @@ pnpm --filter @snowluma/onebot test # example: tests for the affected package pnpm --filter webui test # the frontend package has no @snowluma/ prefix ``` +TypeScript formatting uses the root [Prettier configuration](.prettierrc.json), [local ESLint formatting rules](eslint.format.config.ts), and [ignore list](.prettierignore). Use `pnpm format` for all TS/TSX/MTS/CTS files and `pnpm format:check` for a read-only check. For selected files, run `pnpm exec eslint --config eslint.format.config.ts --fix ` followed by `pnpm exec prettier --write `. These commands enforce four-space indentation, braces around control-statement bodies, and blank lines around statement blocks while preserving other logical spacing. They are separate from CI and its code-quality lint rules. Generated catalogs and compiler fixtures retain their source formatting. + Use focused tests while iterating. Before handing off a code change, run the full checks required by CONTRIBUTING.md and report anything that could not run. [PR CI](.github/workflows/ci.yml) is the reference; `pnpm run ci` reproduces its commands locally, including dependency installation and the generated-catalog check. - **Documentation-only changes:** verify links, paths, commands and `git diff --check`; runtime tests do not validate prose. @@ -79,7 +81,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful - **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content. - **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible. - **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter. -- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and two-space indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior. +- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and four-space TypeScript indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior. - **Keep diagnostics safe.** Use existing sanitization when recording external input. Credentials, private keys, private account data and unredacted captures do not belong in commits, fixtures or public reports. ## Generated files and related changes diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d8fa46c6..c2f5a31b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -104,7 +104,7 @@ git checkout -b fix/onebot-mention-encoding ### 2. 写代码 - **保持改动聚焦**:一个 PR 只做一件事。顺手发现的其他问题请单独开 issue 或新 PR。 -- **跟随既有风格**:不要为了你个人偏好引入大规模格式化或重命名。 +- **跟随既有风格**:TypeScript 排版以仓库 Prettier 配置为准;普通功能或修复 PR 只格式化涉及的文件,避免混入无关的大规模格式化或重命名。 - **写测试**:修 bug 时优先写一个能复现该 bug 的测试,确认它会 fail,再让它 pass。新增功能至少补上 happy path 的测试。 - **不要添加无意义的注释**:标识符已经说清楚的事情不需要再写一遍。注释应当解释"为什么",而不是"做了什么"。 @@ -169,10 +169,30 @@ git push origin fix/onebot-mention-encoding ### 代码风格 - TypeScript 严格模式,按 `tsconfig.base.json` 配置。 +- TypeScript 使用四空格缩进,控制语句始终带大括号。排版由根目录 [`.prettierrc.json`](./.prettierrc.json) 和独立的本地 [ESLint 格式规则](./eslint.format.config.ts) 管理;普通 `pnpm lint` 负责代码质量检查。 - 优先用现有抽象,不要为"假想的未来需求"提前抽象。 - 不要给内部函数加防御性的参数校验,除非是系统边界(用户输入、外部 API)。 - 不要保留死代码、被注释掉的代码或者 `// TODO` 没有具体上下文的占位。 +从仓库根目录运行本地格式化命令: + +```bash +pnpm format # 为全部 TS/TSX/MTS/CTS 补大括号、空行并排版 +pnpm format:check # 检查上述规则,不修改文件 + +# 只格式化指定文件:先处理控制语句与空行,再排版 +pnpm exec eslint --config eslint.format.config.ts --fix packages/core/src/index.ts +pnpm exec prettier --write packages/core/src/index.ts +``` + +格式化范围排除 [`.prettierignore`](./.prettierignore) 中的构建产物、生成文件和编译器测试夹具;普通源码与测试都参与格式化。这两个命令供本地使用,不接入 CI。 + +空行采用保守规则:在语句块前后留空行,保留已有逻辑分段,不强行拆开连续声明或普通调用,也不在每条 `return`、`break` 前插空行;共用同一分支的连续 `case` 标签保持相邻。JSON、YAML 等文件继续使用原有缩进。 + +编辑器请选择项目本地安装的 Prettier 并读取仓库配置。VS Code 可安装 +`esbenp.prettier-vscode`,将 TypeScript / TypeScript React 的默认格式化器设为 +Prettier,并按需开启保存时格式化。 + ### 测试 - 单测放在被测代码同包的 `tests/` 或同目录的 `*.test.ts`,按既有风格走。 diff --git a/eslint.config.ts b/eslint.config.ts index 3de5bec1..57ef350b 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -1,14 +1,17 @@ import js from '@eslint/js'; +import eslintConfigPrettier from 'eslint-config-prettier/flat'; import reactHooks from 'eslint-plugin-react-hooks'; import reactRefresh from 'eslint-plugin-react-refresh'; import { defineConfig, globalIgnores } from 'eslint/config'; import globals from 'globals'; import tseslint from 'typescript-eslint'; -const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1'); +const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace( + /^\/(.:\/)/, + '$1', +); -export default defineConfig([ - globalIgnores([ +export const sourceIgnores = globalIgnores([ '**/dist/**', '**/node_modules/**', '**/coverage/**', @@ -20,89 +23,90 @@ export default defineConfig([ '**/test/fixtures/**', 'packages/runtime/native/**', 'packages/mcp/src/generated/**', - ]), - { - files: ['**/*.{js,mjs,cjs,ts,tsx}'], - extends: [js.configs.recommended], - languageOptions: { - ecmaVersion: 2023, - sourceType: 'module', - globals: { - ...globals.es2023, - ...globals.node, - }, - }, - rules: { - 'indent': ['error', 2, { SwitchCase: 1 }], - 'no-unused-vars': 'off', - 'no-useless-assignment': 'off', - 'prefer-const': 'off', - 'preserve-caught-error': 'off', - }, - }, - { - files: ['**/*.{ts,tsx}'], - extends: [tseslint.configs.recommended], - languageOptions: { - parserOptions: { - tsconfigRootDir, - }, - }, - rules: { - 'indent': ['error', 2, { SwitchCase: 1 }], - 'prefer-const': 'off', - '@typescript-eslint/no-explicit-any': 'error', - '@typescript-eslint/no-empty-object-type': 'off', - '@typescript-eslint/no-this-alias': 'off', - '@typescript-eslint/no-unused-vars': [ - 'warn', - { - argsIgnorePattern: '^_', - varsIgnorePattern: '^_', - caughtErrorsIgnorePattern: '^_', - }, - ], - }, - }, - { - files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'], - rules: { - '@typescript-eslint/no-explicit-any': 'off', - }, - }, - { - files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'], - rules: { - '@typescript-eslint/no-explicit-any': 'off', - }, - }, - { - // OIDB service layer is namespace-per-cmd by design — the - // structural-typing contract (namespace IS the OidbCallSpec) and - // the file:cmd 1:1 mapping are the whole point. Disable the - // module-syntax preference here only. - files: [ - 'packages/protocol/src/oidb-services/**/*.ts', - 'packages/protocol/tests/oidb-services/**/*.ts', - ], - rules: { - '@typescript-eslint/no-namespace': 'off', - }, - }, - { - files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'], - extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite], - languageOptions: { - globals: globals.browser, - parserOptions: { - tsconfigRootDir, - }, - }, - rules: { - 'indent': ['error', 2, { SwitchCase: 1 }], - 'prefer-const': 'off', - 'react-refresh/only-export-components': 'off', - 'react-hooks/set-state-in-effect': 'off', - }, - }, +]); + +export default defineConfig([ + sourceIgnores, + { + files: ['**/*.{js,mjs,cjs,ts,tsx}'], + extends: [js.configs.recommended], + languageOptions: { + ecmaVersion: 2023, + sourceType: 'module', + globals: { + ...globals.es2023, + ...globals.node, + }, + }, + rules: { + 'no-unused-vars': 'off', + 'no-useless-assignment': 'off', + 'prefer-const': 'off', + 'preserve-caught-error': 'off', + }, + }, + { + files: ['**/*.{ts,tsx}'], + extends: [tseslint.configs.recommended], + languageOptions: { + parserOptions: { + tsconfigRootDir, + }, + }, + rules: { + 'prefer-const': 'off', + '@typescript-eslint/no-explicit-any': 'error', + '@typescript-eslint/no-empty-object-type': 'off', + '@typescript-eslint/no-this-alias': 'off', + '@typescript-eslint/no-unused-vars': [ + 'warn', + { + argsIgnorePattern: '^_', + varsIgnorePattern: '^_', + caughtErrorsIgnorePattern: '^_', + }, + ], + }, + }, + { + files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'], + rules: { + '@typescript-eslint/no-explicit-any': 'off', + }, + }, + { + files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'], + rules: { + '@typescript-eslint/no-explicit-any': 'off', + }, + }, + { + // OIDB service layer is namespace-per-cmd by design — the + // structural-typing contract (namespace IS the OidbCallSpec) and + // the file:cmd 1:1 mapping are the whole point. Disable the + // module-syntax preference here only. + files: [ + 'packages/protocol/src/oidb-services/**/*.ts', + 'packages/protocol/tests/oidb-services/**/*.ts', + ], + rules: { + '@typescript-eslint/no-namespace': 'off', + }, + }, + { + files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'], + extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite], + languageOptions: { + globals: globals.browser, + parserOptions: { + tsconfigRootDir, + }, + }, + rules: { + 'prefer-const': 'off', + 'react-refresh/only-export-components': 'off', + 'react-hooks/set-state-in-effect': 'off', + }, + }, + eslintConfigPrettier, ]); diff --git a/eslint.format.config.ts b/eslint.format.config.ts new file mode 100644 index 00000000..159e071a --- /dev/null +++ b/eslint.format.config.ts @@ -0,0 +1,39 @@ +import stylistic from '@stylistic/eslint-plugin'; +import { defineConfig } from 'eslint/config'; +import reactHooks from 'eslint-plugin-react-hooks'; +import tseslint from 'typescript-eslint'; +import { sourceIgnores } from './eslint.config.ts'; + +// Local formatting only; CI continues to use eslint.config.ts for code quality. +export default defineConfig([ + sourceIgnores, + { + // Preserve quality-rule suppressions when running only formatting rules. + linterOptions: { reportUnusedDisableDirectives: 'off' }, + }, + { + files: ['**/*.{ts,tsx,mts,cts}'], + languageOptions: { + parser: tseslint.parser, + }, + plugins: { + '@stylistic': stylistic, + '@typescript-eslint': tseslint.plugin, + 'react-hooks': reactHooks, + }, + rules: { + curly: ['error', 'all'], + '@stylistic/padding-line-between-statements': [ + 'error', + { blankLine: 'always', prev: '*', next: 'block-like' }, + { blankLine: 'always', prev: 'block-like', next: '*' }, + // Stacked case labels share a branch and must stay adjacent. + { + blankLine: 'never', + prev: { selector: 'SwitchCase[consequent.length=0]' }, + next: ['case', 'default'], + }, + ], + }, + }, +]); diff --git a/package.json b/package.json index d565d06a..5efeac48 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,8 @@ "typecheck": "pnpm -r --if-present typecheck", "lint": "eslint .", "lint:fix": "eslint . --fix", + "format": "eslint --config eslint.format.config.ts --fix \"**/*.{ts,tsx,mts,cts}\" && prettier --write \"**/*.{ts,tsx,mts,cts}\"", + "format:check": "eslint --config eslint.format.config.ts \"**/*.{ts,tsx,mts,cts}\" && prettier --check \"**/*.{ts,tsx,mts,cts}\"", "ci": "node tools/ci-check.mjs", "start": "node dist/index.mjs", "bump": "node tools/bump-version.mjs", @@ -32,14 +34,17 @@ }, "devDependencies": { "@eslint/js": "^10.0.1", + "@stylistic/eslint-plugin": "5.10.0", "@vitest/coverage-istanbul": "4.1.4", "@vitest/coverage-v8": "^4.1.4", "cross-env": "^10.1.0", "eslint": "^10.2.0", + "eslint-config-prettier": "10.1.8", "eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-refresh": "^0.5.2", "globals": "^17.5.0", "jiti": "^2.6.1", + "prettier": "3.9.10", "typescript": "catalog:", "typescript-eslint": "^8.58.2" }, diff --git a/packages/bridge/src/hook-manager.ts b/packages/bridge/src/hook-manager.ts index 89dc6057..82b713d3 100644 --- a/packages/bridge/src/hook-manager.ts +++ b/packages/bridge/src/hook-manager.ts @@ -1,19 +1,15 @@ -import { - createLogger, - runWithTraceRequest, - type Logger, -} from '@snowluma/common/logger'; +import { createLogger, runWithTraceRequest, type Logger } from '@snowluma/common/logger'; import { renderParamsVerbose } from '@snowluma/common/log-summary'; import type { PacketSender } from '@snowluma/common/packet-sender'; import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types'; import fs from 'fs'; import { HookSession, type HookSessionDeps } from './hook-session'; import { - injectHookProcess, - listHookProcesses, - resolveHookNativePath, - unloadHookProcess, - type HookProcessBaseInfo, + injectHookProcess, + listHookProcesses, + resolveHookNativePath, + unloadHookProcess, + type HookProcessBaseInfo, } from './injector'; import { PipeWatcher } from './pipe-watcher'; import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator'; @@ -24,8 +20,8 @@ import type { HookProcessInfo } from './types'; const AUTO_LOAD_MAX_ATTEMPTS = 3; type AutoLoadAttempt = { - attempts: number; - inFlight: boolean; + attempts: number; + inFlight: boolean; }; /** @@ -36,42 +32,42 @@ type AutoLoadAttempt = { * dependency on @snowluma/core — the hook package is self-contained. */ export interface BridgeManagerSink { - onHookLogin(pid: number, uin: string, packetClient: PacketSender): void; - onPacket(pkt: PacketInfo): void; - onPidDisconnected(pid: number): void; - onPidReceiveHealthChanged(pid: number, healthy: boolean): void; + onHookLogin(pid: number, uin: string, packetClient: PacketSender): void; + onPacket(pkt: PacketInfo): void; + onPidDisconnected(pid: number): void; + onPidReceiveHealthChanged(pid: number, healthy: boolean): void; } export type HookManagerDeps = { - bridgeManager: BridgeManagerSink; - /** Sink for parsed packets from any live HookSession. Defaults to - * `bridgeManager.onPacket` — every packet flows straight into the - * per-UIN bridge dispatcher with no intermediate event emitter. */ - onPacket?: PacketSink; - /** Native injector entrypoints. Defaults to the real native addon. */ - injector?: HookSessionDeps['injector']; - /** Hook pipe-client factory. Defaults to `new QqHookClient(pid)`. */ - makeClient?: HookSessionDeps['makeClient']; - /** Pre-built watcher. Defaults to a PipeWatcher wrapping the native listings. */ - pipeWatcher?: PipeWatcher; - /** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */ - watcherIntervalMs?: number; - /** Native process lister used by `listProcesses()`. Defaults to the native addon. */ - listProcesses?: () => HookProcessBaseInfo[]; - /** When true, every newly-discovered QQ process is auto-injected (fires - * `loadProcess(pid)` from the watcher's 'process-discovered' handler). - * Failed loads are logged and leave the session in the 'error' state. - * A narrowly-classified early-process mapping race is retried on later - * watcher ticks with a fixed attempt limit. */ - autoLoadOnDiscovery?: boolean; - /** Optional hook fired whenever the set of HookProcessInfo observable to - * `listProcesses()` changes — new process discovered, process gone, or - * any session's status mutated. Used by the WebUI SSE wiring to push a - * fresh processes snapshot to connected clients without REST polling. - * Exceptions thrown by the callback are caught and logged; they do not - * break the watcher / session event loops. */ - onSessionsChanged?: () => void; - log?: Logger; + bridgeManager: BridgeManagerSink; + /** Sink for parsed packets from any live HookSession. Defaults to + * `bridgeManager.onPacket` — every packet flows straight into the + * per-UIN bridge dispatcher with no intermediate event emitter. */ + onPacket?: PacketSink; + /** Native injector entrypoints. Defaults to the real native addon. */ + injector?: HookSessionDeps['injector']; + /** Hook pipe-client factory. Defaults to `new QqHookClient(pid)`. */ + makeClient?: HookSessionDeps['makeClient']; + /** Pre-built watcher. Defaults to a PipeWatcher wrapping the native listings. */ + pipeWatcher?: PipeWatcher; + /** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */ + watcherIntervalMs?: number; + /** Native process lister used by `listProcesses()`. Defaults to the native addon. */ + listProcesses?: () => HookProcessBaseInfo[]; + /** When true, every newly-discovered QQ process is auto-injected (fires + * `loadProcess(pid)` from the watcher's 'process-discovered' handler). + * Failed loads are logged and leave the session in the 'error' state. + * A narrowly-classified early-process mapping race is retried on later + * watcher ticks with a fixed attempt limit. */ + autoLoadOnDiscovery?: boolean; + /** Optional hook fired whenever the set of HookProcessInfo observable to + * `listProcesses()` changes — new process discovered, process gone, or + * any session's status mutated. Used by the WebUI SSE wiring to push a + * fresh processes snapshot to connected clients without REST polling. + * Exceptions thrown by the callback are caught and logged; they do not + * break the watcher / session event loops. */ + onSessionsChanged?: () => void; + log?: Logger; }; /** @@ -92,410 +88,483 @@ export type HookManagerDeps = { * real QQ.exe or a native addon. */ export class HookManager { - private readonly bridgeManager: BridgeManagerSink; - private readonly onPacket: PacketSink; - private readonly injector: HookSessionDeps['injector']; - private readonly makeClient: HookSessionDeps['makeClient']; - private readonly pipeWatcher: PipeWatcher; - private readonly ownsPipeWatcher: boolean; - /** Watcher/API process enumeration — isolated + timeout-bounded by default - * so a blocked native /proc walk can't freeze the loop (issue #158). - * Resolves to `null` (UNKNOWN) on timeout/failure. */ - private readonly enumerate: () => Promise; - /** The owned enumerator (worker lifecycle), or null when a custom lister was - * injected (tests) — nothing to tear down in that case. */ - private readonly enumerator: ProcessEnumerator | null; - private readonly autoLoadOnDiscovery: boolean; - private readonly onSessionsChangedRaw?: () => void; - private readonly log: Logger; - private readonly sessions = new Map(); - private readonly autoLoadAttempts = new Map(); - private readonly startPromise: Promise; + private readonly bridgeManager: BridgeManagerSink; + private readonly onPacket: PacketSink; + private readonly injector: HookSessionDeps['injector']; + private readonly makeClient: HookSessionDeps['makeClient']; + private readonly pipeWatcher: PipeWatcher; + private readonly ownsPipeWatcher: boolean; + /** Watcher/API process enumeration — isolated + timeout-bounded by default + * so a blocked native /proc walk can't freeze the loop (issue #158). + * Resolves to `null` (UNKNOWN) on timeout/failure. */ + private readonly enumerate: () => Promise; + /** The owned enumerator (worker lifecycle), or null when a custom lister was + * injected (tests) — nothing to tear down in that case. */ + private readonly enumerator: ProcessEnumerator | null; + private readonly autoLoadOnDiscovery: boolean; + private readonly onSessionsChangedRaw?: () => void; + private readonly log: Logger; + private readonly sessions = new Map(); + private readonly autoLoadAttempts = new Map(); + private readonly startPromise: Promise; - private disposed = false; + private disposed = false; - constructor(deps: HookManagerDeps) { - this.bridgeManager = deps.bridgeManager; - this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt)); - this.onSessionsChangedRaw = deps.onSessionsChanged; - this.log = deps.log ?? createLogger('Hook'); + constructor(deps: HookManagerDeps) { + this.bridgeManager = deps.bridgeManager; + this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt)); + this.onSessionsChangedRaw = deps.onSessionsChanged; + this.log = deps.log ?? createLogger('Hook'); - this.injector = deps.injector ?? { - inject: injectHookProcess, - unload: (pid, handle) => { - if (!handle) return; - unloadHookProcess(pid, handle); - }, - }; - this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid)); - this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false; + this.injector = deps.injector ?? { + inject: injectHookProcess, + unload: (pid, handle) => { + if (!handle) { + return; + } - // A custom lister (tests) is used directly — no worker, no isolation, just - // an async wrap that maps a throw to the UNKNOWN sentinel. The default path - // wraps the native enumerator in a worker with a timeout. - if (deps.listProcesses) { - const lister = deps.listProcesses; - this.enumerator = null; - this.enumerate = async () => { - try { - return await lister(); - } catch (error) { - this.log.warn('listProcesses failed: %s', errMsg(error)); - return null; + unloadHookProcess(pid, handle); + }, + }; + this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid)); + this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false; + + // A custom lister (tests) is used directly — no worker, no isolation, just + // an async wrap that maps a throw to the UNKNOWN sentinel. The default path + // wraps the native enumerator in a worker with a timeout. + if (deps.listProcesses) { + const lister = deps.listProcesses; + this.enumerator = null; + + this.enumerate = async () => { + try { + return await lister(); + } catch (error) { + this.log.warn('listProcesses failed: %s', errMsg(error)); + return null; + } + }; + } else { + this.enumerator = createNativeProcessEnumerator({ + addonPath: resolveHookNativePath('node'), + fallbackSync: listHookProcesses, + processName: defaultProcessName(), + log: this.log, + }); + this.enumerate = () => this.enumerator!.enumerate(); } - }; - } else { - this.enumerator = createNativeProcessEnumerator({ - addonPath: resolveHookNativePath('node'), - fallbackSync: listHookProcesses, - processName: defaultProcessName(), - log: this.log, - }); - this.enumerate = () => this.enumerator!.enumerate(); - } - if (deps.pipeWatcher) { - this.pipeWatcher = deps.pipeWatcher; - this.ownsPipeWatcher = false; - } else { - this.pipeWatcher = new PipeWatcher({ - listProcesses: this.enumerate, - listLivePipes: processes => QqHookClient.listLivePipes(processes.map(({ pid }) => pid)), - intervalMs: deps.watcherIntervalMs, - log: this.log, - }); - this.ownsPipeWatcher = true; - } - - this.bindWatcher(); - this.startPromise = this.pipeWatcher.start(); - } - - // ─────────────── public API (unchanged from prior HookManager) ─────────────── - - async listProcesses(): Promise { - await this.startPromise; - const processes = await this.enumerate(); - if (processes === null) { - // Enumeration timed out / failed — report the last-known sessions rather - // than an empty list (which the WebUI would render as "no QQ"). - return [...this.sessions.values()] - .map((s) => s.toInfo()) - .sort((a, b) => a.pid - b.pid); - } - const result: HookProcessInfo[] = []; - for (const proc of processes) { - const session = this.ensureSession(proc.pid); - session.attachProcessInfo(proc); - result.push(session.toInfo()); - } - return result.sort((a, b) => a.pid - b.pid); - } - - async loadProcess(pid: number): Promise { - this.assertValidPid(pid); - await this.startPromise; - this.autoLoadAttempts.delete(pid); - const session = this.ensureSession(pid); - const info = await session.load(); - // Pull the next tick forward so a freshly-injected pipe gets noticed - // within the next event-loop turn instead of after the full interval. - this.pipeWatcher.wake(); - return info; - } - - async unloadProcess(pid: number): Promise { - this.assertValidPid(pid); - await this.startPromise; - this.autoLoadAttempts.delete(pid); - const session = this.ensureSession(pid); - return session.unload(); - } - - async refreshProcess(pid: number): Promise { - this.assertValidPid(pid); - await this.startPromise; - const session = this.ensureSession(pid); - return session.refresh(); - } - - async probeProcessLoginInfo(pid: number): Promise { - this.assertValidPid(pid); - return probeQqLoginInfo(pid); - } - - dispose(): void { - if (this.disposed) return; - this.disposed = true; - for (const session of this.sessions.values()) { - session.dispose(); - } - this.sessions.clear(); - this.autoLoadAttempts.clear(); - this.enumerator?.dispose(); - if (this.ownsPipeWatcher) { - this.pipeWatcher.dispose(); - } - } - - // ─────────────── wiring ─────────────── - - private bindWatcher(): void { - this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => { - if (this.disposed) return; - runWithTraceRequest(() => { - const session = this.ensureSession(info.pid); - session.attachProcessInfo(info); - this.log.trace(() => [ - 'hook_manager_fact event=process_discovered pid=%d info=%s autoLoad=%s', - info.pid, - renderParamsVerbose(info), - this.autoLoadOnDiscovery, - ]); - // Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets - // injected without a human clicking "Load" in WebUI. Fire-and-forget: - // failures are already captured inside loadInternal and surfaced via - // the session's status field. - if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) { - this.runAutoLoad(session); + if (deps.pipeWatcher) { + this.pipeWatcher = deps.pipeWatcher; + this.ownsPipeWatcher = false; + } else { + this.pipeWatcher = new PipeWatcher({ + listProcesses: this.enumerate, + listLivePipes: (processes) => + QqHookClient.listLivePipes(processes.map(({ pid }) => pid)), + intervalMs: deps.watcherIntervalMs, + log: this.log, + }); + this.ownsPipeWatcher = true; } - this.notifySessionsChanged(); - }); - }); - this.pipeWatcher.on('process-gone', (pid: number) => { - if (this.disposed) return; - runWithTraceRequest(() => { + + this.bindWatcher(); + this.startPromise = this.pipeWatcher.start(); + } + + // ─────────────── public API (unchanged from prior HookManager) ─────────────── + + async listProcesses(): Promise { + await this.startPromise; + const processes = await this.enumerate(); + + if (processes === null) { + // Enumeration timed out / failed — report the last-known sessions rather + // than an empty list (which the WebUI would render as "no QQ"). + return [...this.sessions.values()].map((s) => s.toInfo()).sort((a, b) => a.pid - b.pid); + } + + const result: HookProcessInfo[] = []; + + for (const proc of processes) { + const session = this.ensureSession(proc.pid); + session.attachProcessInfo(proc); + result.push(session.toInfo()); + } + + return result.sort((a, b) => a.pid - b.pid); + } + + async loadProcess(pid: number): Promise { + this.assertValidPid(pid); + await this.startPromise; this.autoLoadAttempts.delete(pid); - const session = this.sessions.get(pid); - this.log.trace( - 'hook_manager_fact event=process_gone pid=%d tracked=%s', - pid, - session !== undefined, - ); - if (session) session.notifyProcessGone(); - this.notifySessionsChanged(); - }); - }); - this.pipeWatcher.on('pipe-up', (pid: number) => { - if (this.disposed) return; - const session = this.sessions.get(pid); - if (session) session.onPipeUp(); - }); - this.pipeWatcher.on('pipe-down', (pid: number) => { - if (this.disposed) return; - const session = this.sessions.get(pid); - if (session) session.onPipeDown(); - }); - // After every tick, retry sessions that are stuck in 'connecting' OR - // 'disconnected' while the pipe is up. Mirrors the original - // tickWatcher's per-tick reconcileConnect pass; onPipeUp is idempotent - // so calling it for an already-connected session is harmless. - // - // The 'disconnected' branch matters on Windows: when the QQ-NT side of - // the named pipe stays alive but the SnowLuma-side socket dies (read - // EPIPE / idle-timeout / similar transient I/O fault), the watcher - // sees the pipe as still-live (the OS-level pipe is still listed by - // `listLivePipes`) so it never fires another `pipe-up`. Without - // retrying 'disconnected' sessions here the session is stranded - // forever — a real-world symptom users reported as "Windows running - // for a while then stops" with logs `pipe error: read EPIPE` → - // `session closed: UIN=…`. - this.pipeWatcher.on('tick', () => { - if (this.disposed) return; - for (const session of this.sessions.values()) { - const autoLoad = this.autoLoadAttempts.get(session.pid); - if (autoLoad && !autoLoad.inFlight && session.status === 'error' - && isTransientLibcMappingError(session.error)) { - this.runAutoLoad(session, autoLoad); - continue; - } - if ((session.status === 'connecting' - || session.status === 'disconnected' - || session.status === 'error') - && this.pipeWatcher.isPipeLive(session.pid)) { - session.onPipeUp(); - } - } - }); - } - - private runAutoLoad(session: HookSession, existing?: AutoLoadAttempt): void { - if (this.disposed || session.isDisposed) return; - const state = existing ?? { attempts: 0, inFlight: false }; - if (state.inFlight || state.attempts >= AUTO_LOAD_MAX_ATTEMPTS) return; - - state.attempts += 1; - state.inFlight = true; - this.autoLoadAttempts.set(session.pid, state); - const attempt = state.attempts; - - void runWithTraceRequest(async () => { - const startedAt = Date.now(); - this.log.trace( - 'hook_autoload_start pid=%d attempt=%d maxAttempts=%d', - session.pid, - attempt, - AUTO_LOAD_MAX_ATTEMPTS, - ); - try { + const session = this.ensureSession(pid); const info = await session.load(); - if (this.autoLoadAttempts.get(session.pid) !== state) { - this.log.trace( - 'hook_autoload_terminal pid=%d attempt=%d outcome=dropped reason=superseded elapsedMs=%d', - session.pid, - attempt, - Date.now() - startedAt, - ); - return; - } - state.inFlight = false; - - if (info.status !== 'error') { - this.autoLoadAttempts.delete(session.pid); - const reason = attempt > 1 ? 'recovered' : 'loaded'; - this.log.trace(() => [ - 'hook_autoload_terminal pid=%d attempt=%d outcome=completed reason=%s state=%s elapsedMs=%d', - session.pid, - attempt, - reason, - renderParamsVerbose(info), - Date.now() - startedAt, - ]); - if (attempt > 1) { - this.log.info( - 'auto-load recovered: PID=%d attempt=%d/%d', - session.pid, - attempt, - AUTO_LOAD_MAX_ATTEMPTS, - ); - } - return; - } - - if (!isTransientLibcMappingError(info.error)) { - this.autoLoadAttempts.delete(session.pid); - this.log.trace( - 'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=permanent_failure error=%j elapsedMs=%d', - session.pid, - attempt, - info.error, - Date.now() - startedAt, - ); - return; - } - - if (attempt >= AUTO_LOAD_MAX_ATTEMPTS) { - this.autoLoadAttempts.delete(session.pid); - this.log.trace( - 'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_exhausted error=%j elapsedMs=%d', - session.pid, - attempt, - info.error, - Date.now() - startedAt, - ); - this.log.warn( - 'auto-load retry exhausted: PID=%d attempts=%d err=%s', - session.pid, - attempt, - info.error, - ); - return; - } - - this.log.trace( - 'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_pending error=%j elapsedMs=%d', - session.pid, - attempt, - info.error, - Date.now() - startedAt, - ); - this.log.warn( - 'auto-load retry pending: PID=%d attempt=%d/%d err=%s', - session.pid, - attempt, - AUTO_LOAD_MAX_ATTEMPTS, - info.error, - ); - } catch (err) { - if (this.autoLoadAttempts.get(session.pid) === state) { - this.autoLoadAttempts.delete(session.pid); - } - this.log.trace( - 'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=unexpected_failure error=%j elapsedMs=%d', - session.pid, - attempt, - errMsg(err), - Date.now() - startedAt, - ); - this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errMsg(err)); - } - }); - } - - private ensureSession(pid: number): HookSession { - let session = this.sessions.get(pid); - if (session) return session; - - session = new HookSession(pid, { - injector: this.injector, - makeClient: this.makeClient, - pipeWatcher: this.pipeWatcher, - onPacket: this.onPacket, - log: this.log, - }); - session.attachProcessInfo({ name: defaultProcessName() }); - - session.on('login', (uin: string, sender) => { - this.bridgeManager.onHookLogin(pid, uin, sender); - }); - session.on('disconnected', (wasLoggedIn: boolean) => { - if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid); - }); - session.on('receive-health-changed', (healthy: boolean) => { - this.bridgeManager.onPidReceiveHealthChanged(pid, healthy); - }); - // status-changed fires on EVERY internal status mutation, including the - // ones reached via login / disconnected / refresh — subscribing here - // alone covers every transition the WebUI processes view cares about. - session.on('status-changed', () => { - this.notifySessionsChanged(); - }); - session.on('disposed', () => { - this.sessions.delete(pid); - }); - - this.sessions.set(pid, session); - return session; - } - - /** Fire the optional sessions-changed hook with exceptions isolated. - * A throwing subscriber must not abort the watcher's emit loop or break - * a HookSession event handler in flight. */ - private notifySessionsChanged(): void { - if (this.disposed) return; - if (!this.onSessionsChangedRaw) return; - try { - this.onSessionsChangedRaw(); - } catch (err) { - this.log.warn('onSessionsChanged threw: %s', errMsg(err)); + // Pull the next tick forward so a freshly-injected pipe gets noticed + // within the next event-loop turn instead of after the full interval. + this.pipeWatcher.wake(); + return info; } - } - private assertValidPid(pid: number): void { - if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid'); - } + async unloadProcess(pid: number): Promise { + this.assertValidPid(pid); + await this.startPromise; + this.autoLoadAttempts.delete(pid); + const session = this.ensureSession(pid); + return session.unload(); + } + + async refreshProcess(pid: number): Promise { + this.assertValidPid(pid); + await this.startPromise; + const session = this.ensureSession(pid); + return session.refresh(); + } + + async probeProcessLoginInfo(pid: number): Promise { + this.assertValidPid(pid); + return probeQqLoginInfo(pid); + } + + dispose(): void { + if (this.disposed) { + return; + } + + this.disposed = true; + + for (const session of this.sessions.values()) { + session.dispose(); + } + + this.sessions.clear(); + this.autoLoadAttempts.clear(); + this.enumerator?.dispose(); + + if (this.ownsPipeWatcher) { + this.pipeWatcher.dispose(); + } + } + + // ─────────────── wiring ─────────────── + + private bindWatcher(): void { + this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => { + if (this.disposed) { + return; + } + + runWithTraceRequest(() => { + const session = this.ensureSession(info.pid); + session.attachProcessInfo(info); + this.log.trace(() => [ + 'hook_manager_fact event=process_discovered pid=%d info=%s autoLoad=%s', + info.pid, + renderParamsVerbose(info), + this.autoLoadOnDiscovery, + ]); + + // Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets + // injected without a human clicking "Load" in WebUI. Fire-and-forget: + // failures are already captured inside loadInternal and surfaced via + // the session's status field. + if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) { + this.runAutoLoad(session); + } + + this.notifySessionsChanged(); + }); + }); + this.pipeWatcher.on('process-gone', (pid: number) => { + if (this.disposed) { + return; + } + + runWithTraceRequest(() => { + this.autoLoadAttempts.delete(pid); + const session = this.sessions.get(pid); + this.log.trace( + 'hook_manager_fact event=process_gone pid=%d tracked=%s', + pid, + session !== undefined, + ); + + if (session) { + session.notifyProcessGone(); + } + + this.notifySessionsChanged(); + }); + }); + this.pipeWatcher.on('pipe-up', (pid: number) => { + if (this.disposed) { + return; + } + + const session = this.sessions.get(pid); + + if (session) { + session.onPipeUp(); + } + }); + this.pipeWatcher.on('pipe-down', (pid: number) => { + if (this.disposed) { + return; + } + + const session = this.sessions.get(pid); + + if (session) { + session.onPipeDown(); + } + }); + // After every tick, retry sessions that are stuck in 'connecting' OR + // 'disconnected' while the pipe is up. Mirrors the original + // tickWatcher's per-tick reconcileConnect pass; onPipeUp is idempotent + // so calling it for an already-connected session is harmless. + // + // The 'disconnected' branch matters on Windows: when the QQ-NT side of + // the named pipe stays alive but the SnowLuma-side socket dies (read + // EPIPE / idle-timeout / similar transient I/O fault), the watcher + // sees the pipe as still-live (the OS-level pipe is still listed by + // `listLivePipes`) so it never fires another `pipe-up`. Without + // retrying 'disconnected' sessions here the session is stranded + // forever — a real-world symptom users reported as "Windows running + // for a while then stops" with logs `pipe error: read EPIPE` → + // `session closed: UIN=…`. + this.pipeWatcher.on('tick', () => { + if (this.disposed) { + return; + } + + for (const session of this.sessions.values()) { + const autoLoad = this.autoLoadAttempts.get(session.pid); + + if ( + autoLoad && + !autoLoad.inFlight && + session.status === 'error' && + isTransientLibcMappingError(session.error) + ) { + this.runAutoLoad(session, autoLoad); + continue; + } + + if ( + (session.status === 'connecting' || + session.status === 'disconnected' || + session.status === 'error') && + this.pipeWatcher.isPipeLive(session.pid) + ) { + session.onPipeUp(); + } + } + }); + } + + private runAutoLoad(session: HookSession, existing?: AutoLoadAttempt): void { + if (this.disposed || session.isDisposed) { + return; + } + + const state = existing ?? { attempts: 0, inFlight: false }; + + if (state.inFlight || state.attempts >= AUTO_LOAD_MAX_ATTEMPTS) { + return; + } + + state.attempts += 1; + state.inFlight = true; + this.autoLoadAttempts.set(session.pid, state); + const attempt = state.attempts; + + void runWithTraceRequest(async () => { + const startedAt = Date.now(); + this.log.trace( + 'hook_autoload_start pid=%d attempt=%d maxAttempts=%d', + session.pid, + attempt, + AUTO_LOAD_MAX_ATTEMPTS, + ); + + try { + const info = await session.load(); + + if (this.autoLoadAttempts.get(session.pid) !== state) { + this.log.trace( + 'hook_autoload_terminal pid=%d attempt=%d outcome=dropped reason=superseded elapsedMs=%d', + session.pid, + attempt, + Date.now() - startedAt, + ); + return; + } + + state.inFlight = false; + + if (info.status !== 'error') { + this.autoLoadAttempts.delete(session.pid); + const reason = attempt > 1 ? 'recovered' : 'loaded'; + this.log.trace(() => [ + 'hook_autoload_terminal pid=%d attempt=%d outcome=completed reason=%s state=%s elapsedMs=%d', + session.pid, + attempt, + reason, + renderParamsVerbose(info), + Date.now() - startedAt, + ]); + + if (attempt > 1) { + this.log.info( + 'auto-load recovered: PID=%d attempt=%d/%d', + session.pid, + attempt, + AUTO_LOAD_MAX_ATTEMPTS, + ); + } + + return; + } + + if (!isTransientLibcMappingError(info.error)) { + this.autoLoadAttempts.delete(session.pid); + this.log.trace( + 'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=permanent_failure error=%j elapsedMs=%d', + session.pid, + attempt, + info.error, + Date.now() - startedAt, + ); + return; + } + + if (attempt >= AUTO_LOAD_MAX_ATTEMPTS) { + this.autoLoadAttempts.delete(session.pid); + this.log.trace( + 'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_exhausted error=%j elapsedMs=%d', + session.pid, + attempt, + info.error, + Date.now() - startedAt, + ); + this.log.warn( + 'auto-load retry exhausted: PID=%d attempts=%d err=%s', + session.pid, + attempt, + info.error, + ); + return; + } + + this.log.trace( + 'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_pending error=%j elapsedMs=%d', + session.pid, + attempt, + info.error, + Date.now() - startedAt, + ); + this.log.warn( + 'auto-load retry pending: PID=%d attempt=%d/%d err=%s', + session.pid, + attempt, + AUTO_LOAD_MAX_ATTEMPTS, + info.error, + ); + } catch (err) { + if (this.autoLoadAttempts.get(session.pid) === state) { + this.autoLoadAttempts.delete(session.pid); + } + + this.log.trace( + 'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=unexpected_failure error=%j elapsedMs=%d', + session.pid, + attempt, + errMsg(err), + Date.now() - startedAt, + ); + this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errMsg(err)); + } + }); + } + + private ensureSession(pid: number): HookSession { + let session = this.sessions.get(pid); + + if (session) { + return session; + } + + session = new HookSession(pid, { + injector: this.injector, + makeClient: this.makeClient, + pipeWatcher: this.pipeWatcher, + onPacket: this.onPacket, + log: this.log, + }); + session.attachProcessInfo({ name: defaultProcessName() }); + + session.on('login', (uin: string, sender) => { + this.bridgeManager.onHookLogin(pid, uin, sender); + }); + session.on('disconnected', (wasLoggedIn: boolean) => { + if (wasLoggedIn) { + this.bridgeManager.onPidDisconnected(pid); + } + }); + session.on('receive-health-changed', (healthy: boolean) => { + this.bridgeManager.onPidReceiveHealthChanged(pid, healthy); + }); + // status-changed fires on EVERY internal status mutation, including the + // ones reached via login / disconnected / refresh — subscribing here + // alone covers every transition the WebUI processes view cares about. + session.on('status-changed', () => { + this.notifySessionsChanged(); + }); + session.on('disposed', () => { + this.sessions.delete(pid); + }); + + this.sessions.set(pid, session); + return session; + } + + /** Fire the optional sessions-changed hook with exceptions isolated. + * A throwing subscriber must not abort the watcher's emit loop or break + * a HookSession event handler in flight. */ + private notifySessionsChanged(): void { + if (this.disposed) { + return; + } + + if (!this.onSessionsChangedRaw) { + return; + } + + try { + this.onSessionsChangedRaw(); + } catch (err) { + this.log.warn('onSessionsChanged threw: %s', errMsg(err)); + } + } + + private assertValidPid(pid: number): void { + if (!Number.isInteger(pid) || pid <= 0) { + throw new Error('invalid pid'); + } + } } function defaultProcessName(): string { - return process.platform === 'win32' ? 'QQ.exe' : 'qq'; + return process.platform === 'win32' ? 'QQ.exe' : 'qq'; } function errMsg(value: unknown): string { - return value instanceof Error ? value.message : String(value); + return value instanceof Error ? value.message : String(value); } function isTransientLibcMappingError(error: string): boolean { - return /^target process does not map \S*\/libc\.so\.6 while resolving mmap$/.test(error); + return /^target process does not map \S*\/libc\.so\.6 while resolving mmap$/.test(error); } /** @@ -512,27 +581,36 @@ function isTransientLibcMappingError(error: string): boolean { * for picking the right PID from WebUI. */ export function shouldAutoLoadPid(pid: number, log: Logger): boolean { - if (process.platform !== 'linux') return true; - // Escape hatch: operators who explicitly want auto-load on every - // enumerated PID can set this to opt out of the filter. - if (process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL === '1') return true; + if (process.platform !== 'linux') { + return true; + } + + // Escape hatch: operators who explicitly want auto-load on every + // enumerated PID can set this to opt out of the filter. + if (process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL === '1') { + return true; + } + + let cmdline: string; + + try { + cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8'); + } catch { + // Can't read cmdline (process gone, permission, etc.) — let the + // existing load() path handle it; if the process is dead the load + // will fail with a clear error. + return true; + } + + if (cmdline.includes('--type=')) { + const type = /--type=([^\0\s]+)/.exec(cmdline)?.[1] ?? 'unknown'; + log.info('auto-load skip: PID=%d is an Electron child process (--type=%s)', pid, type); + return false; + } - let cmdline: string; - try { - cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8'); - } catch { - // Can't read cmdline (process gone, permission, etc.) — let the - // existing load() path handle it; if the process is dead the load - // will fail with a clear error. return true; - } - if (cmdline.includes('--type=')) { - const type = (/--type=([^\0\s]+)/.exec(cmdline)?.[1]) ?? 'unknown'; - log.info('auto-load skip: PID=%d is an Electron child process (--type=%s)', pid, type); - return false; - } - return true; } + export type { HookProcessBaseInfo } from './injector'; export type { QqPortLoginInfo } from './qq-port-probe'; export type { HookProcessInfo, HookProcessStatus } from './types'; diff --git a/packages/bridge/src/hook-packet-client.ts b/packages/bridge/src/hook-packet-client.ts index 7078b5a0..e74c3b5f 100644 --- a/packages/bridge/src/hook-packet-client.ts +++ b/packages/bridge/src/hook-packet-client.ts @@ -1,58 +1,74 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; import { packetTimeoutMs } from './packet-timeout'; import { - HookPipeRequestError, - PIPE_STATUS_CONNECTION_UNAVAILABLE, - QqHookClient, - type QqHookSendReply, + HookPipeRequestError, + PIPE_STATUS_CONNECTION_UNAVAILABLE, + QqHookClient, + type QqHookSendReply, } from './qq-hook-client'; export type OutboundHealthListener = (healthy: boolean) => void; export class HookPacketClient implements PacketSender { - private outboundHealthy = true; + private outboundHealthy = true; - constructor( - private readonly client: QqHookClient, - private readonly onOutboundHealthChanged?: OutboundHealthListener, - ) { } + constructor( + private readonly client: QqHookClient, + private readonly onOutboundHealthChanged?: OutboundHealthListener, + ) {} - async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = packetTimeoutMs()): Promise { - if (!this.client.isLoggedIn) { - return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null }; + async sendPacket( + serviceCmd: string, + body: Buffer, + timeoutMs = packetTimeoutMs(), + ): Promise { + if (!this.client.isLoggedIn) { + return { + success: false, + gotResponse: false, + errorCode: -1, + errorMessage: 'qq_hook client is not logged in', + responseData: null, + }; + } + + try { + const reply = (await this.client.send(serviceCmd, body, { + wantReply: true, + replyTimeoutMs: timeoutMs, + })) as QqHookSendReply; + this.setOutboundHealthy(true); + return { + success: reply.error === 0, + gotResponse: true, + errorCode: reply.error, + errorMessage: reply.message || '', + responseData: reply.body, + }; + } catch (error) { + if ( + error instanceof HookPipeRequestError && + error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE + ) { + this.setOutboundHealthy(false); + } + + return { + success: false, + gotResponse: false, + errorCode: -1, + errorMessage: error instanceof Error ? error.message : String(error), + responseData: null, + }; + } } - try { - const reply = await this.client.send(serviceCmd, body, { - wantReply: true, - replyTimeoutMs: timeoutMs, - }) as QqHookSendReply; - this.setOutboundHealthy(true); - return { - success: reply.error === 0, - gotResponse: true, - errorCode: reply.error, - errorMessage: reply.message || '', - responseData: reply.body, - }; - } catch (error) { - if (error instanceof HookPipeRequestError - && error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE) { - this.setOutboundHealthy(false); - } - return { - success: false, - gotResponse: false, - errorCode: -1, - errorMessage: error instanceof Error ? error.message : String(error), - responseData: null, - }; - } - } + private setOutboundHealthy(healthy: boolean): void { + if (this.outboundHealthy === healthy) { + return; + } - private setOutboundHealthy(healthy: boolean): void { - if (this.outboundHealthy === healthy) return; - this.outboundHealthy = healthy; - this.onOutboundHealthChanged?.(healthy); - } + this.outboundHealthy = healthy; + this.onOutboundHealthChanged?.(healthy); + } } diff --git a/packages/bridge/src/hook-runtime-dir.ts b/packages/bridge/src/hook-runtime-dir.ts index c3c4562e..801ae7d8 100644 --- a/packages/bridge/src/hook-runtime-dir.ts +++ b/packages/bridge/src/hook-runtime-dir.ts @@ -3,128 +3,166 @@ import os from 'os'; import path from 'path'; export interface HookRuntimeDirDeps { - platform?: NodeJS.Platform; - env?: NodeJS.ProcessEnv; - ownUid?: number; - readText?: (file: string) => string; + platform?: NodeJS.Platform; + env?: NodeJS.ProcessEnv; + ownUid?: number; + readText?: (file: string) => string; } function configuredDirectory(value: string | undefined, variable: string): string | null { - if (!value) return null; - if (!path.isAbsolute(value)) { - throw new Error(`${variable} must be an absolute path`); - } - return value; + if (!value) { + return null; + } + + if (!path.isAbsolute(value)) { + throw new Error(`${variable} must be an absolute path`); + } + + return value; } function parseProcessEnvironment(raw: string): NodeJS.ProcessEnv { - const result: NodeJS.ProcessEnv = {}; - for (const entry of raw.split('\0')) { - if (!entry) continue; - const separator = entry.indexOf('='); - if (separator <= 0) continue; - result[entry.slice(0, separator)] = entry.slice(separator + 1); - } - return result; + const result: NodeJS.ProcessEnv = {}; + + for (const entry of raw.split('\0')) { + if (!entry) { + continue; + } + + const separator = entry.indexOf('='); + + if (separator <= 0) { + continue; + } + + result[entry.slice(0, separator)] = entry.slice(separator + 1); + } + + return result; } function parseRealUid(status: string): number | null { - const match = /^Uid:\s+(\d+)/m.exec(status); - if (!match) return null; - const uid = Number(match[1]); - return Number.isSafeInteger(uid) && uid >= 0 ? uid : null; + const match = /^Uid:\s+(\d+)/m.exec(status); + + if (!match) { + return null; + } + + const uid = Number(match[1]); + return Number.isSafeInteger(uid) && uid >= 0 ? uid : null; } function isProcessGoneError(error: unknown): boolean { - const code = (error as NodeJS.ErrnoException | undefined)?.code; - return code === 'ENOENT' || code === 'ESRCH'; + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return code === 'ENOENT' || code === 'ESRCH'; } function errorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error); + return error instanceof Error ? error.message : String(error); } -function ownRuntimeDir( - platform: NodeJS.Platform, - env: NodeJS.ProcessEnv, - ownUid: number, -): string { - const explicit = configuredDirectory( - env.SNOWLUMA_HOOK_RUNTIME_DIR, - 'SNOWLUMA_HOOK_RUNTIME_DIR', - ); - if (explicit) return explicit; +function ownRuntimeDir(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, ownUid: number): string { + const explicit = configuredDirectory( + env.SNOWLUMA_HOOK_RUNTIME_DIR, + 'SNOWLUMA_HOOK_RUNTIME_DIR', + ); - const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR'); - if (xdg) return xdg; + if (explicit) { + return explicit; + } - if (platform === 'darwin') { - const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR'); - if (tmpdir) return path.join(tmpdir, 'snowluma-hook'); - } - return `/tmp/snowluma-${ownUid}`; + const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR'); + + if (xdg) { + return xdg; + } + + if (platform === 'darwin') { + const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR'); + + if (tmpdir) { + return path.join(tmpdir, 'snowluma-hook'); + } + } + + return `/tmp/snowluma-${ownUid}`; } /** * Resolve the socket directory for the target QQ process. The supervisor may * run under a different user, so its own runtime directory is not authoritative. */ -export function resolveHookRuntimeDir( - targetPid?: number, - deps: HookRuntimeDirDeps = {}, -): string { - const platform = deps.platform ?? process.platform; - const env = deps.env ?? process.env; - const ownUid = deps.ownUid - ?? (typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid); - const readText = deps.readText ?? ((file: string) => readFileSync(file, 'utf8')); +export function resolveHookRuntimeDir(targetPid?: number, deps: HookRuntimeDirDeps = {}): string { + const platform = deps.platform ?? process.platform; + const env = deps.env ?? process.env; + const ownUid = + deps.ownUid ?? + (typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid); + const readText = deps.readText ?? ((file: string) => readFileSync(file, 'utf8')); - if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) { - return ownRuntimeDir(platform, env, ownUid); - } - - let environError: unknown; - try { - const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`)); - const explicit = configuredDirectory( - targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR, - `QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`, - ); - if (explicit) return explicit; - const xdg = configuredDirectory( - targetEnv.XDG_RUNTIME_DIR, - `QQ process ${targetPid} XDG_RUNTIME_DIR`, - ); - if (xdg) return xdg; - environError = new Error('runtime directory is not present'); - } catch (error) { - // An invalid explicit path is configuration corruption and must remain - // visible. Permission/race failures are expected when /proc disappears; - // the status-file fallback below can still recover the target uid. - if (error instanceof Error && error.message.includes('must be an absolute path')) { - throw error; + if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) { + return ownRuntimeDir(platform, env, ownUid); } - environError = error; - } - let statusError: unknown; - try { - const uid = parseRealUid(readText(`/proc/${targetPid}/status`)); - if (uid !== null) return `/tmp/snowluma-${uid}`; - statusError = new Error('real uid is not available'); - } catch (error) { - statusError = error; - } + let environError: unknown; - if (isProcessGoneError(statusError) - && (isProcessGoneError(environError) - || (environError instanceof Error - && environError.message === 'runtime directory is not present'))) { - return ownRuntimeDir(platform, env, ownUid); - } + try { + const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`)); + const explicit = configuredDirectory( + targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR, + `QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`, + ); - throw new Error( - `cannot resolve hook runtime directory for PID ${targetPid}: ` - + `environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`, - ); + if (explicit) { + return explicit; + } + + const xdg = configuredDirectory( + targetEnv.XDG_RUNTIME_DIR, + `QQ process ${targetPid} XDG_RUNTIME_DIR`, + ); + + if (xdg) { + return xdg; + } + + environError = new Error('runtime directory is not present'); + } catch (error) { + // An invalid explicit path is configuration corruption and must remain + // visible. Permission/race failures are expected when /proc disappears; + // the status-file fallback below can still recover the target uid. + if (error instanceof Error && error.message.includes('must be an absolute path')) { + throw error; + } + + environError = error; + } + + let statusError: unknown; + + try { + const uid = parseRealUid(readText(`/proc/${targetPid}/status`)); + + if (uid !== null) { + return `/tmp/snowluma-${uid}`; + } + + statusError = new Error('real uid is not available'); + } catch (error) { + statusError = error; + } + + if ( + isProcessGoneError(statusError) && + (isProcessGoneError(environError) || + (environError instanceof Error && + environError.message === 'runtime directory is not present')) + ) { + return ownRuntimeDir(platform, env, ownUid); + } + + throw new Error( + `cannot resolve hook runtime directory for PID ${targetPid}: ` + + `environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`, + ); } diff --git a/packages/bridge/src/hook-session.ts b/packages/bridge/src/hook-session.ts index f6fef1d1..ca4b1e2f 100644 --- a/packages/bridge/src/hook-session.ts +++ b/packages/bridge/src/hook-session.ts @@ -1,8 +1,8 @@ import { - createLogger, - runWithoutRequestContext, - runWithTraceRequest, - type Logger, + createLogger, + runWithoutRequestContext, + runWithTraceRequest, + type Logger, } from '@snowluma/common/logger'; import { renderParamsVerbose } from '@snowluma/common/log-summary'; import type { PacketSink } from '@snowluma/common/protocol-types'; @@ -31,28 +31,28 @@ const RECEIVE_STALE_AFTER_MS = 90_000; const RECEIVE_STALE_CONFIRM_MS = 15_000; export type HookSessionDeps = { - injector: { - inject: (pid: number) => HookInjectResult | Promise; - unload: (pid: number, handle: HookInjectResult['handle']) => void; - }; - makeClient: (pid: number) => QqHookClient; - /** Active, pipe-independent login probe (reads QQ's ptlogin/deeplink ports). - * Drives the login-reconcile safety net; injectable for tests. Defaults to - * `probeQqLoginInfo`. */ - probeLogin?: (pid: number) => Promise; - /** Sync fast-path check used by load() to skip re-injection when a - * prior SnowLuma run left a working pipe behind. `tickNow` forces a - * fresh poll — used after unload to dodge the up-to-1500ms cache - * staleness that would otherwise false-flag a successful unload. */ - pipeWatcher: { - isPipeLive: (pid: number) => boolean; - tickNow?: () => Promise; - }; - /** Sink for parsed packets. Called with the BridgeManager-shaped - * PacketInfo for every packet received while logged in. If omitted, - * packets are dropped (useful in unit tests that don't care). */ - onPacket?: PacketSink; - log?: Logger; + injector: { + inject: (pid: number) => HookInjectResult | Promise; + unload: (pid: number, handle: HookInjectResult['handle']) => void; + }; + makeClient: (pid: number) => QqHookClient; + /** Active, pipe-independent login probe (reads QQ's ptlogin/deeplink ports). + * Drives the login-reconcile safety net; injectable for tests. Defaults to + * `probeQqLoginInfo`. */ + probeLogin?: (pid: number) => Promise; + /** Sync fast-path check used by load() to skip re-injection when a + * prior SnowLuma run left a working pipe behind. `tickNow` forces a + * fresh poll — used after unload to dodge the up-to-1500ms cache + * staleness that would otherwise false-flag a successful unload. */ + pipeWatcher: { + isPipeLive: (pid: number) => boolean; + tickNow?: () => Promise; + }; + /** Sink for parsed packets. Called with the BridgeManager-shaped + * PacketInfo for every packet received while logged in. If omitted, + * packets are dropped (useful in unit tests that don't care). */ + onPacket?: PacketSink; + log?: Logger; }; /** @@ -76,842 +76,1063 @@ export type HookSessionDeps = { * 'disposed' () — session stopped tracking this PID */ export class HookSession extends EventEmitter { - readonly pid: number; + readonly pid: number; - private readonly injector: HookSessionDeps['injector']; - private readonly makeClient: HookSessionDeps['makeClient']; - private readonly probeLogin: (pid: number) => Promise; - private readonly pipeWatcher: HookSessionDeps['pipeWatcher']; - private readonly onPacket: PacketSink | null; - private readonly log: Logger; + private readonly injector: HookSessionDeps['injector']; + private readonly makeClient: HookSessionDeps['makeClient']; + private readonly probeLogin: (pid: number) => Promise; + private readonly pipeWatcher: HookSessionDeps['pipeWatcher']; + private readonly onPacket: PacketSink | null; + private readonly log: Logger; - private _status: HookProcessStatus = 'available'; - private _error = ''; - private _uin = '0'; - private _method = ''; - private _name = ''; - private _path = ''; + private _status: HookProcessStatus = 'available'; + private _error = ''; + private _uin = '0'; + private _method = ''; + private _name = ''; + private _path = ''; - private injected = false; - private connected = false; - private loggedIn = false; - private injectResult: HookInjectResult | null = null; - private client: QqHookClient | null = null; - private sender: HookPacketClient | null = null; - private bound = false; - private opChain: Promise = Promise.resolve(); - private disposed = false; - private loginProbeTimer: ReturnType | null = null; - private probing = false; - private lastProbeFailure = ''; - private acceptedLoginHintUin = ''; - private loginHintAttemptUin = ''; - private loginHintAttempts = 0; - private nextLoginHintAt = 0; - private nextLoginIdentityObservationAt = 0; - private _receiveHealthy = true; - private _outboundHealthy = true; - private receiveWatchUin = ''; - private receiveWatchArmed = false; - private receiveWatchTimer: ReturnType | null = null; - private lastReceiveAt = 0; + private injected = false; + private connected = false; + private loggedIn = false; + private injectResult: HookInjectResult | null = null; + private client: QqHookClient | null = null; + private sender: HookPacketClient | null = null; + private bound = false; + private opChain: Promise = Promise.resolve(); + private disposed = false; + private loginProbeTimer: ReturnType | null = null; + private probing = false; + private lastProbeFailure = ''; + private acceptedLoginHintUin = ''; + private loginHintAttemptUin = ''; + private loginHintAttempts = 0; + private nextLoginHintAt = 0; + private nextLoginIdentityObservationAt = 0; + private _receiveHealthy = true; + private _outboundHealthy = true; + private receiveWatchUin = ''; + private receiveWatchArmed = false; + private receiveWatchTimer: ReturnType | null = null; + private lastReceiveAt = 0; - constructor(pid: number, deps: HookSessionDeps) { - super(); - this.pid = pid; - this.injector = deps.injector; - this.makeClient = deps.makeClient; - this.probeLogin = deps.probeLogin ?? probeQqLoginInfo; - this.pipeWatcher = deps.pipeWatcher; - this.onPacket = deps.onPacket ?? null; - this.log = deps.log ?? createLogger('HookSession'); - } + constructor(pid: number, deps: HookSessionDeps) { + super(); + this.pid = pid; + this.injector = deps.injector; + this.makeClient = deps.makeClient; + this.probeLogin = deps.probeLogin ?? probeQqLoginInfo; + this.pipeWatcher = deps.pipeWatcher; + this.onPacket = deps.onPacket ?? null; + this.log = deps.log ?? createLogger('HookSession'); + } - // ─────────────── readonly public surface ─────────────── + // ─────────────── readonly public surface ─────────────── - get status(): HookProcessStatus { return this._status; } - get error(): string { return this._error; } - get uin(): string { return this._uin; } - get method(): string { return this._method; } - get isDisposed(): boolean { return this.disposed; } - get receiveHealthy(): boolean { - return this._receiveHealthy && this._outboundHealthy; - } + get status(): HookProcessStatus { + return this._status; + } + get error(): string { + return this._error; + } + get uin(): string { + return this._uin; + } + get method(): string { + return this._method; + } + get isDisposed(): boolean { + return this.disposed; + } + get receiveHealthy(): boolean { + return this._receiveHealthy && this._outboundHealthy; + } - attachProcessInfo(info: { name?: string; path?: string }): void { - if (info.name) this._name = info.name; - if (info.path) this._path = info.path; - } + attachProcessInfo(info: { name?: string; path?: string }): void { + if (info.name) { + this._name = info.name; + } - toInfo(): HookProcessInfo { - return { - pid: this.pid, - name: this._name, - path: this._path, - injected: this.injected, - connected: this.connected, - loggedIn: this.loggedIn, - uin: this._uin, - status: this._status, - error: this._error, - method: this._method, - }; - } + if (info.path) { + this._path = info.path; + } + } - // ─────────────── user-facing commands ─────────────── + toInfo(): HookProcessInfo { + return { + pid: this.pid, + name: this._name, + path: this._path, + injected: this.injected, + connected: this.connected, + loggedIn: this.loggedIn, + uin: this._uin, + status: this._status, + error: this._error, + method: this._method, + }; + } - load(): Promise { - return this.traceCommand('load', () => this.loadInternal()); - } + // ─────────────── user-facing commands ─────────────── - unload(): Promise { - return this.traceCommand('unload', () => this.unloadInternal()); - } + load(): Promise { + return this.traceCommand('load', () => this.loadInternal()); + } - refresh(): Promise { - return this.traceCommand('refresh', () => this.refreshInternal()); - } + unload(): Promise { + return this.traceCommand('unload', () => this.unloadInternal()); + } - // ─────────────── watcher-driven events (called by manager) ─────────────── + refresh(): Promise { + return this.traceCommand('refresh', () => this.refreshInternal()); + } - /** Pipe came up (or stayed up across a SnowLuma restart). Drives connect - * attempts and adopts pre-existing hooks. Idempotent; safe to call on - * every watcher tick where the pipe is live. */ - onPipeUp(): void { - if (this.disposed) return; - void this.serialize(async () => { - if (this.disposed) return; - await this.reconcilePipeUp(); - }).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err))); - } + // ─────────────── watcher-driven events (called by manager) ─────────────── - onPipeDown(): void { - if (this.disposed) return; - void this.serialize(async () => { - if (this.disposed) return; - this.reconcilePipeDown(); - }).catch(err => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err))); - } + /** Pipe came up (or stayed up across a SnowLuma restart). Drives connect + * attempts and adopts pre-existing hooks. Idempotent; safe to call on + * every watcher tick where the pipe is live. */ + onPipeUp(): void { + if (this.disposed) { + return; + } + + void this.serialize(async () => { + if (this.disposed) { + return; + } + + await this.reconcilePipeUp(); + }).catch((err) => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err))); + } + + onPipeDown(): void { + if (this.disposed) { + return; + } + + void this.serialize(async () => { + if (this.disposed) { + return; + } + + this.reconcilePipeDown(); + }).catch((err) => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err))); + } + + /** Called by the manager when the watcher reports the QQ.exe process is + * gone. Cleans up and signals the manager to remove this session. */ + notifyProcessGone(): void { + if (this.disposed) { + return; + } + + void this.serialize(async () => { + if (this.disposed) { + return; + } + + runWithTraceRequest(() => { + const startedAt = Date.now(); + const wasLoggedIn = this.loggedIn; + this.log.trace(() => [ + 'hook_session_process_start pid=%d event=process_gone state=%s', + this.pid, + renderParamsVerbose(this.toInfo()), + ]); + this.tearDownClient(); + this.injected = false; + this.injectResult = null; + this._method = ''; + this.setStatus('available', ''); + + try { + if (wasLoggedIn) { + this.emit('disconnected', true); + } + + this.disposed = true; + this.emit('disposed'); + this.log.trace(() => [ + 'hook_session_process_terminal pid=%d outcome=completed reason=process_gone wasLoggedIn=%s state=%s elapsedMs=%d', + this.pid, + wasLoggedIn, + renderParamsVerbose(this.toInfo()), + Date.now() - startedAt, + ]); + this.removeAllListeners(); + } catch (error) { + this.log.trace(() => [ + 'hook_session_process_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d', + this.pid, + errMsg(error), + renderParamsVerbose(this.toInfo()), + Date.now() - startedAt, + ]); + throw error; + } + }); + }).catch((err) => + this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)), + ); + } + + dispose(): void { + if (this.disposed) { + return; + } - /** Called by the manager when the watcher reports the QQ.exe process is - * gone. Cleans up and signals the manager to remove this session. */ - notifyProcessGone(): void { - if (this.disposed) return; - void this.serialize(async () => { - if (this.disposed) return; - runWithTraceRequest(() => { - const startedAt = Date.now(); const wasLoggedIn = this.loggedIn; - this.log.trace(() => [ - 'hook_session_process_start pid=%d event=process_gone state=%s', - this.pid, - renderParamsVerbose(this.toInfo()), - ]); + this.disposed = true; this.tearDownClient(); - this.injected = false; - this.injectResult = null; - this._method = ''; - this.setStatus('available', ''); + + // Process shutdown must take the same PID-detach path as a live drop. + // tearDownClient strips the pipe client first, so this emit is the only + // disconnected edge HookManager will see. + if (wasLoggedIn) { + this.emit('disconnected', true); + } + + this.removeAllListeners(); + } + + // ─────────────── per-session serialization ─────────────── + + private traceCommand( + operation: 'load' | 'unload' | 'refresh', + command: () => Promise, + ): Promise { + return runWithTraceRequest(async () => { + const startedAt = Date.now(); + this.log.trace(() => [ + 'hook_session_start pid=%d operation=%s state=%s', + this.pid, + operation, + renderParamsVerbose(this.toInfo()), + ]); + + try { + const info = await this.serialize(command); + const outcome = + info.status === 'error' || + (operation === 'unload' && info.status !== 'available') + ? 'failed' + : 'completed'; + let reason: string; + + if (operation === 'unload' && info.status === 'connecting') { + reason = 'unload_verification_failed'; + } else if (outcome === 'failed') { + reason = `${operation}_failed`; + } else { + reason = `${operation}_settled`; + } + + this.log.trace(() => [ + 'hook_session_terminal pid=%d operation=%s outcome=%s reason=%s%s state=%s elapsedMs=%d', + this.pid, + operation, + outcome, + reason, + info.error ? ` error=${JSON.stringify(info.error)}` : '', + renderParamsVerbose(info), + Date.now() - startedAt, + ]); + return info; + } catch (error) { + this.log.trace(() => [ + 'hook_session_terminal pid=%d operation=%s outcome=failed reason=%s error=%j state=%s elapsedMs=%d', + this.pid, + operation, + `${operation}_threw`, + errMsg(error), + renderParamsVerbose(this.toInfo()), + Date.now() - startedAt, + ]); + throw error; + } + }); + } + + private serialize(op: () => Promise): Promise { + const previous = this.opChain; + let release!: () => void; + const completion = new Promise((resolve) => { + release = resolve; + }); + this.opChain = previous.then(() => completion); + return (async () => { + try { + await previous.catch(() => undefined); + return await op(); + } finally { + release(); + } + })(); + } + + // ─────────────── internal transitions ─────────────── + + private async loadInternal(): Promise { + this._error = ''; + this.setStatus('loading', ''); + try { - if (wasLoggedIn) this.emit('disconnected', true); - this.disposed = true; - this.emit('disposed'); - this.log.trace(() => [ - 'hook_session_process_terminal pid=%d outcome=completed reason=process_gone wasLoggedIn=%s state=%s elapsedMs=%d', - this.pid, - wasLoggedIn, - renderParamsVerbose(this.toInfo()), - Date.now() - startedAt, - ]); - this.removeAllListeners(); + if (!this.injected) { + // Fast path: a previous SnowLuma run may have left the hook DLL + // resident in QQ.exe. If the watcher already sees a live pipe, + // skip re-injection and let onPipeUp drive the reconnect. + if (this.pipeWatcher.isPipeLive(this.pid)) { + this.injected = true; + this._method = this._method || 'reconnect'; + this.log.trace( + 'hook_session_branch pid=%d operation=load branch=existing_pipe method=%j', + this.pid, + this._method, + ); + this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid); + } else { + this.log.trace( + 'hook_session_branch pid=%d operation=load branch=inject_begin', + this.pid, + ); + this.injectResult = await this.injector.inject(this.pid); + this.injected = true; + this._method = this.injectResult.method; + this.log.trace( + 'hook_session_branch pid=%d operation=load branch=inject_completed method=%j', + this.pid, + this._method, + ); + } + } + + this.applyStatus(); } catch (error) { - this.log.trace(() => [ - 'hook_session_process_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d', - this.pid, - errMsg(error), - renderParamsVerbose(this.toInfo()), - Date.now() - startedAt, - ]); - throw error; + this._error = errMsg(error); + this.setStatus('error', this._error); + this.log.error('load failed: PID=%d err=%s', this.pid, this._error); + // The module can already be listening even when this call returns + // failure: another load left it resident, or it came up after the + // call returned. A live pipe still has the account state, so connect + // instead of staying on the failed load. + await this.pipeWatcher.tickNow?.(); + + if (!this.disposed && this.pipeWatcher.isPipeLive(this.pid)) { + this.log.info('PID=%d load failed but pipe is up; connecting', this.pid); + await this.reconcilePipeUp(); + } } - }); - }).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err))); - } - dispose(): void { - if (this.disposed) return; - const wasLoggedIn = this.loggedIn; - this.disposed = true; - this.tearDownClient(); - // Process shutdown must take the same PID-detach path as a live drop. - // tearDownClient strips the pipe client first, so this emit is the only - // disconnected edge HookManager will see. - if (wasLoggedIn) this.emit('disconnected', true); - this.removeAllListeners(); - } + return this.toInfo(); + } - // ─────────────── per-session serialization ─────────────── + private async unloadInternal(): Promise { + this._error = ''; - private traceCommand( - operation: 'load' | 'unload' | 'refresh', - command: () => Promise, - ): Promise { - return runWithTraceRequest(async () => { - const startedAt = Date.now(); - this.log.trace(() => [ - 'hook_session_start pid=%d operation=%s state=%s', - this.pid, - operation, - renderParamsVerbose(this.toInfo()), - ]); - try { - const info = await this.serialize(command); - const outcome = info.status === 'error' - || (operation === 'unload' && info.status !== 'available') - ? 'failed' - : 'completed'; - let reason: string; - if (operation === 'unload' && info.status === 'connecting') { - reason = 'unload_verification_failed'; - } else if (outcome === 'failed') { - reason = `${operation}_failed`; - } else { - reason = `${operation}_settled`; + try { + const wasLoggedIn = this.loggedIn; + this.tearDownClient(); + + if (wasLoggedIn) { + this.emit('disconnected', true); + } + + const handle = this.injectResult?.handle; + + if (this.injected && handle) { + this.injector.unload(this.pid, handle); + this.log.info('SnowLuma unloaded from PID=%d', this.pid); + } + + this.injected = false; + this.injectResult = null; + this._method = ''; + this._uin = '0'; + + // Verify the unload took: if the pipe is still up the DLL is still + // resident. The cached snapshot is up to 1500ms stale and we just + // changed the world, so force a fresh poll first — otherwise even + // a successful unload reads as "pipe still live" until the next + // background tick runs and we'd report a spurious failure. + await this.pipeWatcher.tickNow?.(); + + if (this.pipeWatcher.isPipeLive(this.pid)) { + this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连'; + this.setStatus('connecting', this._error); + this.log.warn('unload verification failed: PID=%d pipe still up', this.pid); + } else { + this.setStatus('available', ''); + } + } catch (error) { + this._error = errMsg(error); + this.setStatus('error', this._error); + this.log.error('unload failed: PID=%d err=%s', this.pid, this._error); } - this.log.trace(() => [ - 'hook_session_terminal pid=%d operation=%s outcome=%s reason=%s%s state=%s elapsedMs=%d', - this.pid, - operation, - outcome, - reason, - info.error ? ` error=${JSON.stringify(info.error)}` : '', - renderParamsVerbose(info), - Date.now() - startedAt, - ]); - return info; - } catch (error) { - this.log.trace(() => [ - 'hook_session_terminal pid=%d operation=%s outcome=failed reason=%s error=%j state=%s elapsedMs=%d', - this.pid, - operation, - `${operation}_threw`, - errMsg(error), - renderParamsVerbose(this.toInfo()), - Date.now() - startedAt, - ]); - throw error; - } - }); - } - private serialize(op: () => Promise): Promise { - const previous = this.opChain; - let release!: () => void; - const completion = new Promise(resolve => { release = resolve; }); - this.opChain = previous.then(() => completion); - return (async () => { - try { - await previous.catch(() => undefined); - return await op(); - } finally { - release(); - } - })(); - } + return this.toInfo(); + } - // ─────────────── internal transitions ─────────────── + private async refreshInternal(): Promise { + this._error = ''; - private async loadInternal(): Promise { - this._error = ''; - this.setStatus('loading', ''); - try { - if (!this.injected) { - // Fast path: a previous SnowLuma run may have left the hook DLL - // resident in QQ.exe. If the watcher already sees a live pipe, - // skip re-injection and let onPipeUp drive the reconnect. - if (this.pipeWatcher.isPipeLive(this.pid)) { - this.injected = true; - this._method = this._method || 'reconnect'; - this.log.trace( - 'hook_session_branch pid=%d operation=load branch=existing_pipe method=%j', - this.pid, - this._method, - ); - this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid); - } else { - this.log.trace( - 'hook_session_branch pid=%d operation=load branch=inject_begin', - this.pid, - ); - this.injectResult = await this.injector.inject(this.pid); - this.injected = true; - this._method = this.injectResult.method; - this.log.trace( - 'hook_session_branch pid=%d operation=load branch=inject_completed method=%j', - this.pid, - this._method, - ); + try { + // Same pipe-up / pipe-down reconcilers the watcher drives, chosen by + // a fresh poll. This collapses what used to be a hand-copied pair of + // onPipeUp/onPipeDown bodies — and fixes the drift where the down + // branch reported 'disconnected' even for a never-logged-in session. + if (this.pipeWatcher.isPipeLive(this.pid)) { + await this.reconcilePipeUp(); + } else { + this.reconcilePipeDown(); + } + } catch (error) { + this._error = errMsg(error); + this.setStatus(this.injected ? 'disconnected' : 'error', this._error); + this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error); } - } - this.applyStatus(); - } catch (error) { - this._error = errMsg(error); - this.setStatus('error', this._error); - this.log.error('load failed: PID=%d err=%s', this.pid, this._error); - // The module can already be listening even when this call returns - // failure: another load left it resident, or it came up after the - // call returned. A live pipe still has the account state, so connect - // instead of staying on the failed load. - await this.pipeWatcher.tickNow?.(); - if (!this.disposed && this.pipeWatcher.isPipeLive(this.pid)) { - this.log.info('PID=%d load failed but pipe is up; connecting', this.pid); - await this.reconcilePipeUp(); - } + + return this.toInfo(); } - return this.toInfo(); - } - private async unloadInternal(): Promise { - this._error = ''; - try { - const wasLoggedIn = this.loggedIn; - this.tearDownClient(); - if (wasLoggedIn) this.emit('disconnected', true); + // ─────────────── settled-status reconcilers ─────────────── - const handle = this.injectResult?.handle; - if (this.injected && handle) { - this.injector.unload(this.pid, handle); - this.log.info('SnowLuma unloaded from PID=%d', this.pid); - } - - this.injected = false; - this.injectResult = null; - this._method = ''; - this._uin = '0'; - - // Verify the unload took: if the pipe is still up the DLL is still - // resident. The cached snapshot is up to 1500ms stale and we just - // changed the world, so force a fresh poll first — otherwise even - // a successful unload reads as "pipe still live" until the next - // background tick runs and we'd report a spurious failure. - await this.pipeWatcher.tickNow?.(); - if (this.pipeWatcher.isPipeLive(this.pid)) { - this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连'; - this.setStatus('connecting', this._error); - this.log.warn('unload verification failed: PID=%d pipe still up', this.pid); - } else { - this.setStatus('available', ''); - } - } catch (error) { - this._error = errMsg(error); - this.setStatus('error', this._error); - this.log.error('unload failed: PID=%d err=%s', this.pid, this._error); - } - return this.toInfo(); - } - - private async refreshInternal(): Promise { - this._error = ''; - try { - // Same pipe-up / pipe-down reconcilers the watcher drives, chosen by - // a fresh poll. This collapses what used to be a hand-copied pair of - // onPipeUp/onPipeDown bodies — and fixes the drift where the down - // branch reported 'disconnected' even for a never-logged-in session. - if (this.pipeWatcher.isPipeLive(this.pid)) { - await this.reconcilePipeUp(); - } else { - this.reconcilePipeDown(); - } - } catch (error) { - this._error = errMsg(error); - this.setStatus(this.injected ? 'disconnected' : 'error', this._error); - this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error); - } - return this.toInfo(); - } - - // ─────────────── settled-status reconcilers ─────────────── - - /** Push the settled status derived from the live flags. `wasLoggedIn` - * defaults to the current `loggedIn`; callers that just tore the client - * down pass the value captured *before* teardown (teardown clears it). */ - private applyStatus(wasLoggedIn: boolean = this.loggedIn, error = ''): void { - this.setStatus(statusFor({ - injected: this.injected, - connected: this.connected, - loggedIn: this.loggedIn, - wasLoggedIn, - }), error); - } - - /** Pipe is up: adopt a DLL that survived a SnowLuma restart, drop a - * stale client, then (re)connect if needed or just settle the status. - * Shared by onPipeUp and refresh's pipe-up branch. */ - private async reconcilePipeUp(): Promise { - if (!this.injected) { - this.injected = true; - if (!this._method) this._method = 'reconnect'; - } - if (this.client?.isClosed) this.tearDownClient(); - if (!this.connected) { - await this.attemptConnect(); - } else { - this.applyStatus(); - } - } - - /** Pipe is down (or the client closed): tear down, settle the status, - * and emit the disconnect notification iff we owed BridgeManager one - * (i.e. we had reached login). Shared by onPipeDown, refresh's pipe-down - * branch, and the client 'close' handler. */ - private reconcilePipeDown(): void { - if (!this.connected) { - // Nothing live to tear down. A session that never connected can't owe - // a disconnect, and we must NOT clobber a diagnostic the failed - // connect/load already set — settle the status keeping `_error`, or - // (when not even injected) leave the status untouched entirely. - if (this.injected) this.applyStatus(this.loggedIn, this._error); - return; - } - runWithTraceRequest(() => { - const startedAt = Date.now(); - const wasLoggedIn = this.loggedIn; - this.log.trace(() => [ - 'hook_session_disconnect_start pid=%d reason=pipe_down state=%s', - this.pid, - renderParamsVerbose(this.toInfo()), - ]); - this.tearDownClient(); - this.applyStatus(wasLoggedIn); - try { - if (wasLoggedIn) this.emit('disconnected', true); - this.log.trace(() => [ - 'hook_session_disconnect_terminal pid=%d outcome=completed reason=pipe_down wasLoggedIn=%s state=%s elapsedMs=%d', - this.pid, - wasLoggedIn, - renderParamsVerbose(this.toInfo()), - Date.now() - startedAt, - ]); - } catch (error) { - this.log.trace(() => [ - 'hook_session_disconnect_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d', - this.pid, - errMsg(error), - renderParamsVerbose(this.toInfo()), - Date.now() - startedAt, - ]); - throw error; - } - }); - } - - // ─────────────── client plumbing ─────────────── - - private async attemptConnect(): Promise { - if (this.connected) return; - return runWithTraceRequest(async () => { - const startedAt = Date.now(); - this.log.trace(() => [ - 'hook_session_connect_start pid=%d state=%s', - this.pid, - renderParamsVerbose(this.toInfo()), - ]); - if (this.client?.isClosed) this.tearDownClient(); - if (!this.client) { - this.client = this.makeClient(this.pid); - this.sender = new HookPacketClient( - this.client, - healthy => this.setOutboundHealthy(healthy), + /** Push the settled status derived from the live flags. `wasLoggedIn` + * defaults to the current `loggedIn`; callers that just tore the client + * down pass the value captured *before* teardown (teardown clears it). */ + private applyStatus(wasLoggedIn: boolean = this.loggedIn, error = ''): void { + this.setStatus( + statusFor({ + injected: this.injected, + connected: this.connected, + loggedIn: this.loggedIn, + wasLoggedIn, + }), + error, ); - this.bound = false; - } - if (!this.bound) { - this.bindClient(this.client); - this.bound = true; - } + } - const client = this.client; - try { - await client.connectAll({ recv: true }); - this.connected = true; - const loginState = client.getLoginState(); - // handleLoginState owns the connected+loggedIn → 'online' (+ login - // emit) transition; defer to it so the status is set once. Otherwise - // we're connected-but-not-logged-in → 'loaded'. - if (loginState.loggedIn) { - this.handleLoginState(loginState); + /** Pipe is up: adopt a DLL that survived a SnowLuma restart, drop a + * stale client, then (re)connect if needed or just settle the status. + * Shared by onPipeUp and refresh's pipe-up branch. */ + private async reconcilePipeUp(): Promise { + if (!this.injected) { + this.injected = true; + + if (!this._method) { + this._method = 'reconnect'; + } + } + + if (this.client?.isClosed) { + this.tearDownClient(); + } + + if (!this.connected) { + await this.attemptConnect(); } else { - this.applyStatus(); - // The native hook only PUSHES a loginState frame on the login edge; - // if QQ logged in before/around connect (Docker auto-login) that edge - // is missed and we'd wait forever. Actively re-probe until logged in. - runWithoutRequestContext(() => this.startLoginReconcile()); + this.applyStatus(); } - this.log.info('pipe connected: PID=%d', this.pid); - this.log.trace(() => [ - 'hook_session_connect_terminal pid=%d outcome=completed reason=connect_settled state=%s elapsedMs=%d', - this.pid, - renderParamsVerbose(this.toInfo()), - Date.now() - startedAt, - ]); - } catch (error) { - this._error = errMsg(error); - // Drop the client so the next attempt builds a fresh socket pair. - // A failed connect was never logged in → 'connecting' (or 'available'). - this.tearDownClient(); - this.applyStatus(false, this._error); - this.log.trace(() => [ - 'hook_session_connect_terminal pid=%d outcome=failed reason=connect_failed error=%j state=%s elapsedMs=%d', - this.pid, - this._error, - renderParamsVerbose(this.toInfo()), - Date.now() - startedAt, - ]); - } - }); - } - - private bindClient(client: QqHookClient): void { - client.on('packet', packet => this.handlePacket(packet)); - client.on('loginState', state => this.handleLoginState(state)); - client.on('error', error => { - const msg = errMsg(error); - this._error = msg; - this.log.warn('pipe error: PID=%d err=%s', this.pid, msg); - }); - client.on('close', () => { - if (this.disposed) return; - // Only the currently-registered client should drive a reconcile; - // listeners may fire for an already-replaced client. - if (this.client !== client) return; - void this.serialize(async () => { - if (this.disposed) return; - if (this.client !== client) return; - this.reconcilePipeDown(); - }).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err))); - }); - } - - private tearDownClient(): void { - this.stopLoginReconcile(); - this.resetReceiveWatch(); - const client = this.client; - if (client) { - client.removeAllListeners(); - try { client.close(); } catch { /* ignore */ } - } - this.client = null; - this.sender = null; - this.bound = false; - this.connected = false; - this.loggedIn = false; - this._outboundHealthy = true; - this.resetLoginHint(); - } - - private handleLoginState(state: QqHookLoginState): void { - const wasLoggedIn = this.loggedIn; - const previousUin = this._uin; - this._uin = state.uin || state.uinNumber.toString(); - this.loggedIn = state.loggedIn && isRealUin(this._uin); - // Login readiness has now been confirmed, so identity probing is done. - if (this.loggedIn) { - this.stopLoginReconcile(); - // A PID can switch accounts without an intermediate logout edge. Never - // carry the previous account's heartbeat deadline into the new epoch. - if (this.receiveWatchUin !== this._uin) { - this.resetReceiveWatch(this._uin); - this._outboundHealthy = true; - } - } else { - this.resetReceiveWatch(); - this._outboundHealthy = true; } - // Only the connected/logged-in states are ours to set here; when fully - // down we leave the status the teardown path already settled. - // Load-bearing invariant: `loggedIn ⇒ connected` (login can only be - // observed on a live client, and teardown clears `loggedIn` before - // `connected`), so statusFor lands 'online' here rather than the - // disconnected/connecting branch. - if (this.connected || this.loggedIn) { - this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error); - } + /** Pipe is down (or the client closed): tear down, settle the status, + * and emit the disconnect notification iff we owed BridgeManager one + * (i.e. we had reached login). Shared by onPipeDown, refresh's pipe-down + * branch, and the client 'close' handler. */ + private reconcilePipeDown(): void { + if (!this.connected) { + // Nothing live to tear down. A session that never connected can't owe + // a disconnect, and we must NOT clobber a diagnostic the failed + // connect/load already set — settle the status keeping `_error`, or + // (when not even injected) leave the status untouched entirely. + if (this.injected) { + this.applyStatus(this.loggedIn, this._error); + } - if (!this.loggedIn || !this.sender) return; - if (wasLoggedIn && previousUin === this._uin) return; - - runWithTraceRequest(() => { - const startedAt = Date.now(); - this.log.trace( - 'hook_session_login_start pid=%d previousUin=%j uin=%j', - this.pid, - previousUin, - this._uin, - ); - try { - this.emit('login', this._uin, this.sender!); - this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin); - this.log.trace(() => [ - 'hook_session_login_terminal pid=%d outcome=completed reason=login_detected previousUin=%j uin=%j state=%s elapsedMs=%d', - this.pid, - previousUin, - this._uin, - renderParamsVerbose(this.toInfo()), - Date.now() - startedAt, - ]); - } catch (error) { - this.log.trace(() => [ - 'hook_session_login_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d', - this.pid, - errMsg(error), - renderParamsVerbose(this.toInfo()), - Date.now() - startedAt, - ]); - throw error; - } - }); - } - - // ─────────────── login reconcile (Docker auto-login safety net) ─────────── - // The local endpoint can identify an auto-restored account before the - // runtime is ready. Forward identity for reconciliation, but never synthesize - // online state from the probe. - - private startLoginReconcile(): void { - if (this.loginProbeTimer || this.disposed) return; - this.log.info('awaiting login: PID=%d', this.pid); - void this.probeLoginOnce(); // immediate — catch already-logged-in fast - this.loginProbeTimer = setInterval(() => void this.probeLoginOnce(), LOGIN_RECONCILE_INTERVAL_MS); - this.loginProbeTimer.unref?.(); - } - - private stopLoginReconcile(): void { - if (this.loginProbeTimer) { - clearInterval(this.loginProbeTimer); - this.loginProbeTimer = null; - } - } - - private async probeLoginOnce(): Promise { - // A port-scan probe can outlast the interval; skip overlapping ticks so a - // slow probe never stacks concurrent subprocess-spawning scans. - if (this.probing) return; - if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; } - if (Date.now() < this.nextLoginIdentityObservationAt) return; - this.probing = true; - try { - let info: QqPortLoginInfo | null; - try { - info = await this.probeLogin(this.pid); - } catch (error) { - const message = errMsg(error); - const note = `${this.pid}:${message}`; - if (this.lastProbeFailure !== note) { - this.lastProbeFailure = note; - this.log.warn('login probe failed: PID=%d err=%s', this.pid, message); + return; } - return; // best-effort; the interval retries - } - // The await yielded — re-check we still want this before mutating state. - if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; } - if (info?.identityKnown && isRealUin(info.uin)) { + + runWithTraceRequest(() => { + const startedAt = Date.now(); + const wasLoggedIn = this.loggedIn; + this.log.trace(() => [ + 'hook_session_disconnect_start pid=%d reason=pipe_down state=%s', + this.pid, + renderParamsVerbose(this.toInfo()), + ]); + this.tearDownClient(); + this.applyStatus(wasLoggedIn); + + try { + if (wasLoggedIn) { + this.emit('disconnected', true); + } + + this.log.trace(() => [ + 'hook_session_disconnect_terminal pid=%d outcome=completed reason=pipe_down wasLoggedIn=%s state=%s elapsedMs=%d', + this.pid, + wasLoggedIn, + renderParamsVerbose(this.toInfo()), + Date.now() - startedAt, + ]); + } catch (error) { + this.log.trace(() => [ + 'hook_session_disconnect_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d', + this.pid, + errMsg(error), + renderParamsVerbose(this.toInfo()), + Date.now() - startedAt, + ]); + throw error; + } + }); + } + + // ─────────────── client plumbing ─────────────── + + private async attemptConnect(): Promise { + if (this.connected) { + return; + } + + return runWithTraceRequest(async () => { + const startedAt = Date.now(); + this.log.trace(() => [ + 'hook_session_connect_start pid=%d state=%s', + this.pid, + renderParamsVerbose(this.toInfo()), + ]); + + if (this.client?.isClosed) { + this.tearDownClient(); + } + + if (!this.client) { + this.client = this.makeClient(this.pid); + this.sender = new HookPacketClient(this.client, (healthy) => + this.setOutboundHealthy(healthy), + ); + this.bound = false; + } + + if (!this.bound) { + this.bindClient(this.client); + this.bound = true; + } + + const client = this.client; + + try { + await client.connectAll({ recv: true }); + this.connected = true; + const loginState = client.getLoginState(); + + // handleLoginState owns the connected+loggedIn → 'online' (+ login + // emit) transition; defer to it so the status is set once. Otherwise + // we're connected-but-not-logged-in → 'loaded'. + if (loginState.loggedIn) { + this.handleLoginState(loginState); + } else { + this.applyStatus(); + // The native hook only PUSHES a loginState frame on the login edge; + // if QQ logged in before/around connect (Docker auto-login) that edge + // is missed and we'd wait forever. Actively re-probe until logged in. + runWithoutRequestContext(() => this.startLoginReconcile()); + } + + this.log.info('pipe connected: PID=%d', this.pid); + this.log.trace(() => [ + 'hook_session_connect_terminal pid=%d outcome=completed reason=connect_settled state=%s elapsedMs=%d', + this.pid, + renderParamsVerbose(this.toInfo()), + Date.now() - startedAt, + ]); + } catch (error) { + this._error = errMsg(error); + // Drop the client so the next attempt builds a fresh socket pair. + // A failed connect was never logged in → 'connecting' (or 'available'). + this.tearDownClient(); + this.applyStatus(false, this._error); + this.log.trace(() => [ + 'hook_session_connect_terminal pid=%d outcome=failed reason=connect_failed error=%j state=%s elapsedMs=%d', + this.pid, + this._error, + renderParamsVerbose(this.toInfo()), + Date.now() - startedAt, + ]); + } + }); + } + + private bindClient(client: QqHookClient): void { + client.on('packet', (packet) => this.handlePacket(packet)); + client.on('loginState', (state) => this.handleLoginState(state)); + client.on('error', (error) => { + const msg = errMsg(error); + this._error = msg; + this.log.warn('pipe error: PID=%d err=%s', this.pid, msg); + }); + client.on('close', () => { + if (this.disposed) { + return; + } + + // Only the currently-registered client should drive a reconcile; + // listeners may fire for an already-replaced client. + if (this.client !== client) { + return; + } + + void this.serialize(async () => { + if (this.disposed) { + return; + } + + if (this.client !== client) { + return; + } + + this.reconcilePipeDown(); + }).catch((err) => + this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)), + ); + }); + } + + private tearDownClient(): void { + this.stopLoginReconcile(); + this.resetReceiveWatch(); const client = this.client; - if (!client) return; - if (this.acceptedLoginHintUin === info.uin) { - this.nextLoginIdentityObservationAt = Date.now() - + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; - return; - } - if (this.loginHintAttemptUin !== info.uin) { - this.loginHintAttemptUin = info.uin; - this.loginHintAttempts = 0; - this.nextLoginHintAt = 0; - this.nextLoginIdentityObservationAt = 0; - } - if (this.loginHintAttempts >= LOGIN_HINT_MAX_ATTEMPTS - || Date.now() < this.nextLoginHintAt) return; - const attempt = ++this.loginHintAttempts; - this.log.info('login identity discovered: PID=%d UIN=%s; awaiting readiness', this.pid, info.uin); - try { - await client.reconcileLoginIdentity(info.uin); - if (this.client !== client || this.disposed || !this.connected || this.loggedIn) return; - this.acceptedLoginHintUin = info.uin; - this.nextLoginIdentityObservationAt = Date.now() - + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; - } catch (error) { - if (this.client !== client || this.disposed) return; - if (attempt >= LOGIN_HINT_MAX_ATTEMPTS) { - this.log.warn( - 'login identity reconciliation failed: PID=%d UIN=%s attempts=%d err=%s', - this.pid, - info.uin, - attempt, - errMsg(error), - ); - this.nextLoginIdentityObservationAt = Date.now() - + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; - } else { - this.nextLoginHintAt = Date.now() - + LOGIN_HINT_RETRY_DELAYS_MS[attempt - 1]!; + if (client) { + client.removeAllListeners(); + + try { + client.close(); + } catch { + /* ignore */ + } + } + + this.client = null; + this.sender = null; + this.bound = false; + this.connected = false; + this.loggedIn = false; + this._outboundHealthy = true; + this.resetLoginHint(); + } + + private handleLoginState(state: QqHookLoginState): void { + const wasLoggedIn = this.loggedIn; + const previousUin = this._uin; + this._uin = state.uin || state.uinNumber.toString(); + this.loggedIn = state.loggedIn && isRealUin(this._uin); + + // Login readiness has now been confirmed, so identity probing is done. + if (this.loggedIn) { + this.stopLoginReconcile(); + + // A PID can switch accounts without an intermediate logout edge. Never + // carry the previous account's heartbeat deadline into the new epoch. + if (this.receiveWatchUin !== this._uin) { + this.resetReceiveWatch(this._uin); + this._outboundHealthy = true; + } + } else { + this.resetReceiveWatch(); + this._outboundHealthy = true; + } + + // Only the connected/logged-in states are ours to set here; when fully + // down we leave the status the teardown path already settled. + // Load-bearing invariant: `loggedIn ⇒ connected` (login can only be + // observed on a live client, and teardown clears `loggedIn` before + // `connected`), so statusFor lands 'online' here rather than the + // disconnected/connecting branch. + if (this.connected || this.loggedIn) { + this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error); + } + + if (!this.loggedIn || !this.sender) { + return; + } + + if (wasLoggedIn && previousUin === this._uin) { + return; + } + + runWithTraceRequest(() => { + const startedAt = Date.now(); this.log.trace( - 'login identity hint failed: PID=%d UIN=%s attempt=%d err=%s', - this.pid, - info.uin, - attempt, - errMsg(error), + 'hook_session_login_start pid=%d previousUin=%j uin=%j', + this.pid, + previousUin, + this._uin, ); - } + + try { + this.emit('login', this._uin, this.sender!); + this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin); + this.log.trace(() => [ + 'hook_session_login_terminal pid=%d outcome=completed reason=login_detected previousUin=%j uin=%j state=%s elapsedMs=%d', + this.pid, + previousUin, + this._uin, + renderParamsVerbose(this.toInfo()), + Date.now() - startedAt, + ]); + } catch (error) { + this.log.trace(() => [ + 'hook_session_login_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d', + this.pid, + errMsg(error), + renderParamsVerbose(this.toInfo()), + Date.now() - startedAt, + ]); + throw error; + } + }); + } + + // ─────────────── login reconcile (Docker auto-login safety net) ─────────── + // The local endpoint can identify an auto-restored account before the + // runtime is ready. Forward identity for reconciliation, but never synthesize + // online state from the probe. + + private startLoginReconcile(): void { + if (this.loginProbeTimer || this.disposed) { + return; } - } - } finally { - this.probing = false; - } - } - private resetLoginHint(): void { - this.acceptedLoginHintUin = ''; - this.loginHintAttemptUin = ''; - this.loginHintAttempts = 0; - this.nextLoginHintAt = 0; - this.nextLoginIdentityObservationAt = 0; - this.lastProbeFailure = ''; - } - - private handlePacket(packet: QqHookPacket): void { - if (!this.loggedIn) return; - const uin = packet.uin || this._uin; - // Routing requires a real UIN, but even a frame carrying UIN=0 proves the - // receive hook is alive. Attribute that evidence to the current epoch - // without forwarding the malformed packet into BridgeManager. - const receiveUin = isRealUin(uin) ? uin : (this.receiveWatchUin || this._uin); - if (isRealUin(receiveUin)) this.noteReceiveActivity(packet.cmd, receiveUin); - if (!isRealUin(uin)) return; - if (!this.onPacket) return; - // Re-shape the hook-client wire packet into BridgeManager's PacketInfo - // shape. Used to live in the deleted NtqqHandler.onHookPacket; field - // renaming was that module's entire purpose, so it lives at the source - // now (no need for a single-listener event-emitter in between). - this.onPacket({ - pid: this.pid, - uin, - serviceCmd: packet.cmd, - seqId: packet.seq, - retCode: packet.error, - fromClient: false, - body: Buffer.from(packet.body), - }); - } - - private setStatus(status: HookProcessStatus, error: string): void { - if (this._status === status && this._error === error) return; - this._status = status; - this._error = error; - this.emit('status-changed', status, error); - } - - private noteReceiveActivity(cmd: string, uin: string): void { - // BridgeManager treats packet.uin as authoritative and may move this PID - // before the next loginState edge. Keep the watchdog on that same epoch. - if (this.receiveWatchUin !== uin) this.resetReceiveWatch(uin); - - if (!this.receiveWatchArmed) { - if (cmd !== QQ_RECV_HEARTBEAT_CMD) return; - this.receiveWatchArmed = true; - this.log.debug('receive health armed by QQ heartbeat: PID=%d UIN=%s', this.pid, this.receiveWatchUin); - } - - const now = Date.now(); - const silentForMs = this.lastReceiveAt > 0 ? now - this.lastReceiveAt : 0; - this.lastReceiveAt = now; - this.scheduleReceiveStaleCheck(); - - if (!this._receiveHealthy) { - this.setReceiveHealthy(true); - this.log.info( - 'receive path recovered: PID=%d UIN=%s silentFor=%dms', - this.pid, - this.receiveWatchUin, - silentForMs, - ); - } - } - - private scheduleReceiveStaleCheck(): void { - if (this.receiveWatchTimer) clearTimeout(this.receiveWatchTimer); - this.receiveWatchTimer = setTimeout(() => { - this.receiveWatchTimer = null; - if (!this.shouldWatchReceive()) return; - - // A delayed event loop (notably system sleep/resume) lands here long - // after the nominal 90s deadline. Do not flip health immediately: give - // the real QQ heartbeat one short confirmation window to arrive. - this.receiveWatchTimer = setTimeout(() => { - this.receiveWatchTimer = null; - if (!this.shouldWatchReceive()) return; - const silentForMs = Date.now() - this.lastReceiveAt; - if (silentForMs < RECEIVE_STALE_AFTER_MS + RECEIVE_STALE_CONFIRM_MS) { - this.scheduleReceiveStaleCheck(); - return; - } - this.setReceiveHealthy(false); - this.log.warn( - 'receive path stale: PID=%d UIN=%s lastRecvAt=%s silentFor=%dms; reporting good=false', - this.pid, - this.receiveWatchUin, - new Date(this.lastReceiveAt).toISOString(), - silentForMs, + this.log.info('awaiting login: PID=%d', this.pid); + void this.probeLoginOnce(); // immediate — catch already-logged-in fast + this.loginProbeTimer = setInterval( + () => void this.probeLoginOnce(), + LOGIN_RECONCILE_INTERVAL_MS, ); - }, RECEIVE_STALE_CONFIRM_MS); - this.receiveWatchTimer.unref?.(); - }, RECEIVE_STALE_AFTER_MS); - this.receiveWatchTimer.unref?.(); - } - - private shouldWatchReceive(): boolean { - return !this.disposed && this.connected && this.loggedIn && this.receiveWatchArmed; - } - - private setReceiveHealthy(healthy: boolean): void { - if (this._receiveHealthy === healthy) return; - const previous = this.receiveHealthy; - this._receiveHealthy = healthy; - if (previous !== this.receiveHealthy) { - this.emit('receive-health-changed', this.receiveHealthy); + this.loginProbeTimer.unref?.(); } - } - private setOutboundHealthy(healthy: boolean): void { - if (this._outboundHealthy === healthy) return; - const previous = this.receiveHealthy; - this._outboundHealthy = healthy; - if (previous !== this.receiveHealthy) { - this.emit('receive-health-changed', this.receiveHealthy); + private stopLoginReconcile(): void { + if (this.loginProbeTimer) { + clearInterval(this.loginProbeTimer); + this.loginProbeTimer = null; + } } - if (healthy) { - this.log.info('request path recovered: PID=%d UIN=%s', this.pid, this._uin); - } else { - this.log.warn( - 'request path unavailable: PID=%d UIN=%s; reporting good=false', - this.pid, - this._uin, - ); - } - } - private resetReceiveWatch(uin = ''): void { - if (this.receiveWatchTimer) { - clearTimeout(this.receiveWatchTimer); - this.receiveWatchTimer = null; + private async probeLoginOnce(): Promise { + // A port-scan probe can outlast the interval; skip overlapping ticks so a + // slow probe never stacks concurrent subprocess-spawning scans. + if (this.probing) { + return; + } + + if (this.disposed || !this.connected || this.loggedIn) { + this.stopLoginReconcile(); + return; + } + + if (Date.now() < this.nextLoginIdentityObservationAt) { + return; + } + + this.probing = true; + + try { + let info: QqPortLoginInfo | null; + + try { + info = await this.probeLogin(this.pid); + } catch (error) { + const message = errMsg(error); + const note = `${this.pid}:${message}`; + + if (this.lastProbeFailure !== note) { + this.lastProbeFailure = note; + this.log.warn('login probe failed: PID=%d err=%s', this.pid, message); + } + + return; // best-effort; the interval retries + } + + // The await yielded — re-check we still want this before mutating state. + if (this.disposed || !this.connected || this.loggedIn) { + this.stopLoginReconcile(); + return; + } + + if (info?.identityKnown && isRealUin(info.uin)) { + const client = this.client; + + if (!client) { + return; + } + + if (this.acceptedLoginHintUin === info.uin) { + this.nextLoginIdentityObservationAt = + Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; + return; + } + + if (this.loginHintAttemptUin !== info.uin) { + this.loginHintAttemptUin = info.uin; + this.loginHintAttempts = 0; + this.nextLoginHintAt = 0; + this.nextLoginIdentityObservationAt = 0; + } + + if ( + this.loginHintAttempts >= LOGIN_HINT_MAX_ATTEMPTS || + Date.now() < this.nextLoginHintAt + ) { + return; + } + + const attempt = ++this.loginHintAttempts; + this.log.info( + 'login identity discovered: PID=%d UIN=%s; awaiting readiness', + this.pid, + info.uin, + ); + + try { + await client.reconcileLoginIdentity(info.uin); + + if ( + this.client !== client || + this.disposed || + !this.connected || + this.loggedIn + ) { + return; + } + + this.acceptedLoginHintUin = info.uin; + this.nextLoginIdentityObservationAt = + Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; + } catch (error) { + if (this.client !== client || this.disposed) { + return; + } + + if (attempt >= LOGIN_HINT_MAX_ATTEMPTS) { + this.log.warn( + 'login identity reconciliation failed: PID=%d UIN=%s attempts=%d err=%s', + this.pid, + info.uin, + attempt, + errMsg(error), + ); + this.nextLoginIdentityObservationAt = + Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS; + } else { + this.nextLoginHintAt = + Date.now() + LOGIN_HINT_RETRY_DELAYS_MS[attempt - 1]!; + this.log.trace( + 'login identity hint failed: PID=%d UIN=%s attempt=%d err=%s', + this.pid, + info.uin, + attempt, + errMsg(error), + ); + } + } + } + } finally { + this.probing = false; + } + } + + private resetLoginHint(): void { + this.acceptedLoginHintUin = ''; + this.loginHintAttemptUin = ''; + this.loginHintAttempts = 0; + this.nextLoginHintAt = 0; + this.nextLoginIdentityObservationAt = 0; + this.lastProbeFailure = ''; + } + + private handlePacket(packet: QqHookPacket): void { + if (!this.loggedIn) { + return; + } + + const uin = packet.uin || this._uin; + // Routing requires a real UIN, but even a frame carrying UIN=0 proves the + // receive hook is alive. Attribute that evidence to the current epoch + // without forwarding the malformed packet into BridgeManager. + const receiveUin = isRealUin(uin) ? uin : this.receiveWatchUin || this._uin; + + if (isRealUin(receiveUin)) { + this.noteReceiveActivity(packet.cmd, receiveUin); + } + + if (!isRealUin(uin)) { + return; + } + + if (!this.onPacket) { + return; + } + + // Re-shape the hook-client wire packet into BridgeManager's PacketInfo + // shape. Used to live in the deleted NtqqHandler.onHookPacket; field + // renaming was that module's entire purpose, so it lives at the source + // now (no need for a single-listener event-emitter in between). + this.onPacket({ + pid: this.pid, + uin, + serviceCmd: packet.cmd, + seqId: packet.seq, + retCode: packet.error, + fromClient: false, + body: Buffer.from(packet.body), + }); + } + + private setStatus(status: HookProcessStatus, error: string): void { + if (this._status === status && this._error === error) { + return; + } + + this._status = status; + this._error = error; + this.emit('status-changed', status, error); + } + + private noteReceiveActivity(cmd: string, uin: string): void { + // BridgeManager treats packet.uin as authoritative and may move this PID + // before the next loginState edge. Keep the watchdog on that same epoch. + if (this.receiveWatchUin !== uin) { + this.resetReceiveWatch(uin); + } + + if (!this.receiveWatchArmed) { + if (cmd !== QQ_RECV_HEARTBEAT_CMD) { + return; + } + + this.receiveWatchArmed = true; + this.log.debug( + 'receive health armed by QQ heartbeat: PID=%d UIN=%s', + this.pid, + this.receiveWatchUin, + ); + } + + const now = Date.now(); + const silentForMs = this.lastReceiveAt > 0 ? now - this.lastReceiveAt : 0; + this.lastReceiveAt = now; + this.scheduleReceiveStaleCheck(); + + if (!this._receiveHealthy) { + this.setReceiveHealthy(true); + this.log.info( + 'receive path recovered: PID=%d UIN=%s silentFor=%dms', + this.pid, + this.receiveWatchUin, + silentForMs, + ); + } + } + + private scheduleReceiveStaleCheck(): void { + if (this.receiveWatchTimer) { + clearTimeout(this.receiveWatchTimer); + } + + this.receiveWatchTimer = setTimeout(() => { + this.receiveWatchTimer = null; + + if (!this.shouldWatchReceive()) { + return; + } + + // A delayed event loop (notably system sleep/resume) lands here long + // after the nominal 90s deadline. Do not flip health immediately: give + // the real QQ heartbeat one short confirmation window to arrive. + this.receiveWatchTimer = setTimeout(() => { + this.receiveWatchTimer = null; + + if (!this.shouldWatchReceive()) { + return; + } + + const silentForMs = Date.now() - this.lastReceiveAt; + + if (silentForMs < RECEIVE_STALE_AFTER_MS + RECEIVE_STALE_CONFIRM_MS) { + this.scheduleReceiveStaleCheck(); + return; + } + + this.setReceiveHealthy(false); + this.log.warn( + 'receive path stale: PID=%d UIN=%s lastRecvAt=%s silentFor=%dms; reporting good=false', + this.pid, + this.receiveWatchUin, + new Date(this.lastReceiveAt).toISOString(), + silentForMs, + ); + }, RECEIVE_STALE_CONFIRM_MS); + this.receiveWatchTimer.unref?.(); + }, RECEIVE_STALE_AFTER_MS); + this.receiveWatchTimer.unref?.(); + } + + private shouldWatchReceive(): boolean { + return !this.disposed && this.connected && this.loggedIn && this.receiveWatchArmed; + } + + private setReceiveHealthy(healthy: boolean): void { + if (this._receiveHealthy === healthy) { + return; + } + + const previous = this.receiveHealthy; + this._receiveHealthy = healthy; + + if (previous !== this.receiveHealthy) { + this.emit('receive-health-changed', this.receiveHealthy); + } + } + + private setOutboundHealthy(healthy: boolean): void { + if (this._outboundHealthy === healthy) { + return; + } + + const previous = this.receiveHealthy; + this._outboundHealthy = healthy; + + if (previous !== this.receiveHealthy) { + this.emit('receive-health-changed', this.receiveHealthy); + } + + if (healthy) { + this.log.info('request path recovered: PID=%d UIN=%s', this.pid, this._uin); + } else { + this.log.warn( + 'request path unavailable: PID=%d UIN=%s; reporting good=false', + this.pid, + this._uin, + ); + } + } + + private resetReceiveWatch(uin = ''): void { + if (this.receiveWatchTimer) { + clearTimeout(this.receiveWatchTimer); + this.receiveWatchTimer = null; + } + + this.receiveWatchUin = uin; + this.receiveWatchArmed = false; + this.lastReceiveAt = 0; + this._receiveHealthy = true; } - this.receiveWatchUin = uin; - this.receiveWatchArmed = false; - this.lastReceiveAt = 0; - this._receiveHealthy = true; - } } function errMsg(value: unknown): string { - return value instanceof Error ? value.message : String(value); + return value instanceof Error ? value.message : String(value); } diff --git a/packages/bridge/src/hook-status.ts b/packages/bridge/src/hook-status.ts index 414b3199..3ec86e48 100644 --- a/packages/bridge/src/hook-status.ts +++ b/packages/bridge/src/hook-status.ts @@ -9,10 +9,10 @@ import type { HookProcessStatus } from './types'; * `loggedIn` *before* tearing the client down, since teardown clears it. */ export interface HookFlags { - injected: boolean; - connected: boolean; - loggedIn: boolean; - wasLoggedIn: boolean; + injected: boolean; + connected: boolean; + loggedIn: boolean; + wasLoggedIn: boolean; } /** @@ -25,7 +25,13 @@ export interface HookFlags { * here. */ export function statusFor(flags: HookFlags): HookProcessStatus { - if (!flags.injected) return 'available'; - if (flags.connected) return flags.loggedIn ? 'online' : 'loaded'; - return flags.wasLoggedIn ? 'disconnected' : 'connecting'; + if (!flags.injected) { + return 'available'; + } + + if (flags.connected) { + return flags.loggedIn ? 'online' : 'loaded'; + } + + return flags.wasLoggedIn ? 'disconnected' : 'connecting'; } diff --git a/packages/bridge/src/index.ts b/packages/bridge/src/index.ts index 4f7a4378..06411312 100644 --- a/packages/bridge/src/index.ts +++ b/packages/bridge/src/index.ts @@ -1,5 +1,9 @@ export { - HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo, - type HookProcessStatus, type QqPortLoginInfo + HookManager, + type BridgeManagerSink, + type HookManagerDeps, + type HookProcessBaseInfo, + type HookProcessInfo, + type HookProcessStatus, + type QqPortLoginInfo, } from './hook-manager'; - diff --git a/packages/bridge/src/injector.ts b/packages/bridge/src/injector.ts index 1cabeda5..e3830d99 100644 --- a/packages/bridge/src/injector.ts +++ b/packages/bridge/src/injector.ts @@ -7,135 +7,159 @@ import { listSnowlumaPipePidsSync } from './qq-hook-client'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); export interface ManualMapHandle { - base: bigint; - entry: bigint; - exceptionTable: bigint; - size: number; + base: bigint; + entry: bigint; + exceptionTable: bigint; + size: number; } interface NativeHookAddon { - getAllMainProcess(): number[]; - loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise; - unloadModuleManual(pid: number, handle: ManualMapHandle): void; + getAllMainProcess(): number[]; + loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise; + unloadModuleManual(pid: number, handle: ManualMapHandle): void; } export interface HookProcessBaseInfo { - pid: number; - name: string; - path: string; + pid: number; + name: string; + path: string; } export interface HookInjectResult { - method: 'loadModuleManual'; - handle?: ManualMapHandle; + method: 'loadModuleManual'; + handle?: ManualMapHandle; } let nativeAddon: NativeHookAddon | null = null; let nativeLoadError: string | null = null; function loadNativeAddon(addonPath: string): NativeHookAddon { - const mod = { exports: {} as Record }; - process.dlopen(mod, addonPath); - return mod.exports as unknown as NativeHookAddon; + const mod = { exports: {} as Record }; + process.dlopen(mod, addonPath); + return mod.exports as unknown as NativeHookAddon; } type HookBinaryExt = 'node' | 'dll' | 'so'; function platformBinaryName(ext: HookBinaryExt): string { - if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`; - return `snowluma-${process.platform}-${process.arch}.${ext}`; + if (process.platform === 'win32' && process.arch === 'x64') { + return `snowluma-win32-x64.${ext}`; + } + + return `snowluma-${process.platform}-${process.arch}.${ext}`; } function platformInjectableExt(): 'dll' | 'so' { - return process.platform === 'win32' ? 'dll' : 'so'; + return process.platform === 'win32' ? 'dll' : 'so'; } function defaultProcessName(): string { - return process.platform === 'win32' ? 'QQ.exe' : 'qq'; + return process.platform === 'win32' ? 'QQ.exe' : 'qq'; } function nativeSearchDirs(): string[] { - // Several layouts must be supported: - // 1. Released zip (flattened dist/): __dirname=/, native at /native - // 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=/packages/bridge/src - // → walk up to /packages and append runtime/native - // Same offset works for `packages/bridge/dist/index.mjs` after build. - // 3. cwd-based fallback when neither __dirname-relative path resolves. - return [ - path.resolve(__dirname, 'native'), - path.resolve(__dirname, '..', '..', 'runtime', 'native'), - path.resolve(process.cwd(), 'dist', 'native'), - path.resolve(process.cwd(), 'packages', 'runtime', 'native'), - ]; + // Several layouts must be supported: + // 1. Released zip (flattened dist/): __dirname=/, native at /native + // 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=/packages/bridge/src + // → walk up to /packages and append runtime/native + // Same offset works for `packages/bridge/dist/index.mjs` after build. + // 3. cwd-based fallback when neither __dirname-relative path resolves. + return [ + path.resolve(__dirname, 'native'), + path.resolve(__dirname, '..', '..', 'runtime', 'native'), + path.resolve(process.cwd(), 'dist', 'native'), + path.resolve(process.cwd(), 'packages', 'runtime', 'native'), + ]; } export function resolveHookNativePath(ext: HookBinaryExt): string | null { - const fileName = platformBinaryName(ext); - for (const dir of nativeSearchDirs()) { - const fullPath = path.join(dir, fileName); - if (existsSync(fullPath)) return fullPath; - } - return null; + const fileName = platformBinaryName(ext); + + for (const dir of nativeSearchDirs()) { + const fullPath = path.join(dir, fileName); + + if (existsSync(fullPath)) { + return fullPath; + } + } + + return null; } export function getNativeHookAddon(): NativeHookAddon | null { - if (nativeAddon) return nativeAddon; - const addonPath = resolveHookNativePath('node'); - if (!addonPath) { - nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`; - return null; - } - try { - nativeAddon = loadNativeAddon(addonPath); - nativeLoadError = null; - return nativeAddon; - } catch (error) { - nativeLoadError = error instanceof Error ? error.message : String(error); - return null; - } + if (nativeAddon) { + return nativeAddon; + } + + const addonPath = resolveHookNativePath('node'); + + if (!addonPath) { + nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`; + return null; + } + + try { + nativeAddon = loadNativeAddon(addonPath); + nativeLoadError = null; + return nativeAddon; + } catch (error) { + nativeLoadError = error instanceof Error ? error.message : String(error); + return null; + } } export function getNativeHookLoadError(): string | null { - return nativeLoadError; + return nativeLoadError; } export function listHookProcesses(): HookProcessBaseInfo[] { - // macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model - // means QQ ran with our dylib already mapped, so the dylib's listener - // socket IS the discovery signal. Treat every `mojo..control.sock` - // in the runtime dir as a known process (the watcher's subsequent - // connectable-probe gates the pipe-up emit, so a stale dangling socket - // here doesn't drive a false connect). - if (process.platform === 'darwin') { - return [...listSnowlumaPipePidsSync()] - .sort((a, b) => a - b) - .map(pid => ({ pid, name: defaultProcessName(), path: '' })); - } - const addon = getNativeHookAddon(); - if (!addon) return []; - return [...new Set(addon.getAllMainProcess())] - .filter(pid => Number.isInteger(pid) && pid > 0) - .sort((a, b) => a - b) - .map(pid => ({ pid, name: defaultProcessName(), path: '' })); + // macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model + // means QQ ran with our dylib already mapped, so the dylib's listener + // socket IS the discovery signal. Treat every `mojo..control.sock` + // in the runtime dir as a known process (the watcher's subsequent + // connectable-probe gates the pipe-up emit, so a stale dangling socket + // here doesn't drive a false connect). + if (process.platform === 'darwin') { + return [...listSnowlumaPipePidsSync()] + .sort((a, b) => a - b) + .map((pid) => ({ pid, name: defaultProcessName(), path: '' })); + } + + const addon = getNativeHookAddon(); + + if (!addon) { + return []; + } + + return [...new Set(addon.getAllMainProcess())] + .filter((pid) => Number.isInteger(pid) && pid > 0) + .sort((a, b) => a - b) + .map((pid) => ({ pid, name: defaultProcessName(), path: '' })); } export async function injectHookProcess(pid: number): Promise { - const addon = getNativeHookAddon(); - if (!addon) { - throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available'); - } - const injectableExt = platformInjectableExt(); - const dllPath = resolveHookNativePath(injectableExt); - if (!dllPath) { - throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`); - } - return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) }; + const addon = getNativeHookAddon(); + + if (!addon) { + throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available'); + } + + const injectableExt = platformInjectableExt(); + const dllPath = resolveHookNativePath(injectableExt); + + if (!dllPath) { + throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`); + } + + return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) }; } export function unloadHookProcess(pid: number, handle: ManualMapHandle): void { - const addon = getNativeHookAddon(); - if (!addon) { - throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available'); - } - addon.unloadModuleManual(pid, handle); + const addon = getNativeHookAddon(); + + if (!addon) { + throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available'); + } + + addon.unloadModuleManual(pid, handle); } diff --git a/packages/bridge/src/packet-timeout.ts b/packages/bridge/src/packet-timeout.ts index 264682ba..512ef5d6 100644 --- a/packages/bridge/src/packet-timeout.ts +++ b/packages/bridge/src/packet-timeout.ts @@ -4,5 +4,5 @@ import { positiveIntEnv } from '@snowluma/common/env'; export const DEFAULT_PACKET_TIMEOUT_MS = 15_000; export function packetTimeoutMs(env?: NodeJS.ProcessEnv): number { - return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env }); + return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env }); } diff --git a/packages/bridge/src/pipe-watcher.ts b/packages/bridge/src/pipe-watcher.ts index d763126b..400b9892 100644 --- a/packages/bridge/src/pipe-watcher.ts +++ b/packages/bridge/src/pipe-watcher.ts @@ -6,17 +6,17 @@ const DEFAULT_INTERVAL_MS = 1500; const MIN_INTERVAL_MS = 250; export type PipeWatcherDeps = { - /** Native: list QQ.exe processes currently running. May be async and may - * return `null` (UNKNOWN) when enumeration timed out / failed — in which - * case this tick keeps the prior process+pipe state instead of treating the - * missing data as "everything disappeared" (issue #158). */ - listProcesses: () => HookProcessBaseInfo[] | null | Promise; - /** Native: PIDs that currently have a live SnowLuma named pipe. The current - * process snapshot lets Linux inspect each target user's runtime directory. */ - listLivePipes: (processes: readonly HookProcessBaseInfo[]) => Promise>; - /** Polling interval in ms. Defaults to 1500, floored to 250. */ - intervalMs?: number; - log?: Logger; + /** Native: list QQ.exe processes currently running. May be async and may + * return `null` (UNKNOWN) when enumeration timed out / failed — in which + * case this tick keeps the prior process+pipe state instead of treating the + * missing data as "everything disappeared" (issue #158). */ + listProcesses: () => HookProcessBaseInfo[] | null | Promise; + /** Native: PIDs that currently have a live SnowLuma named pipe. The current + * process snapshot lets Linux inspect each target user's runtime directory. */ + listLivePipes: (processes: readonly HookProcessBaseInfo[]) => Promise>; + /** Polling interval in ms. Defaults to 1500, floored to 250. */ + intervalMs?: number; + log?: Logger; }; /** @@ -40,191 +40,224 @@ export type PipeWatcherDeps = { * dispose logic when QQ.exe is killed with a live pipe. */ export class PipeWatcher extends EventEmitter { - private readonly listProcesses: PipeWatcherDeps['listProcesses']; - private readonly listLivePipes: PipeWatcherDeps['listLivePipes']; - private readonly intervalMs: number; - private readonly log: Logger; + private readonly listProcesses: PipeWatcherDeps['listProcesses']; + private readonly listLivePipes: PipeWatcherDeps['listLivePipes']; + private readonly intervalMs: number; + private readonly log: Logger; - private livePipes = new Set(); - private knownPids = new Set(); - private timer: NodeJS.Timeout | null = null; - private ticking = false; - private pendingWake = false; - private startPromise: Promise | null = null; - private stopped = false; + private livePipes = new Set(); + private knownPids = new Set(); + private timer: NodeJS.Timeout | null = null; + private ticking = false; + private pendingWake = false; + private startPromise: Promise | null = null; + private stopped = false; - constructor(deps: PipeWatcherDeps) { - super(); - this.listProcesses = deps.listProcesses; - this.listLivePipes = deps.listLivePipes; - this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS); - this.log = deps.log ?? createLogger('PipeWatcher'); - } - - /** Was this PID's pipe live as of the last completed tick? */ - isPipeLive(pid: number): boolean { - return this.livePipes.has(pid); - } - - /** Was this PID alive as of the last completed tick? */ - isProcessAlive(pid: number): boolean { - return this.knownPids.has(pid); - } - - /** - * Run an initial tick (so isPipeLive/isProcessAlive return real data) - * and begin the polling loop. Idempotent. - */ - start(): Promise { - if (this.startPromise) return this.startPromise; - this.startPromise = (async () => { - try { - await this.tickOnce(); - } finally { - this.scheduleNext(this.intervalMs); - } - })(); - return this.startPromise; - } - - /** Pull the next scheduled tick forward to the next event-loop turn. */ - wake(): void { - if (this.stopped) return; - this.scheduleNext(0); - } - - /** Force a single tick now. Resolves after diff events have been emitted. */ - tickNow(): Promise { - return this.tickOnce(); - } - - stop(): void { - this.stopped = true; - if (this.timer) { - clearTimeout(this.timer); - this.timer = null; + constructor(deps: PipeWatcherDeps) { + super(); + this.listProcesses = deps.listProcesses; + this.listLivePipes = deps.listLivePipes; + this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS); + this.log = deps.log ?? createLogger('PipeWatcher'); } - } - dispose(): void { - this.stop(); - this.removeAllListeners(); - } - - private scheduleNext(delayMs: number): void { - if (this.stopped) return; - if (this.timer) { - clearTimeout(this.timer); - this.timer = null; + /** Was this PID's pipe live as of the last completed tick? */ + isPipeLive(pid: number): boolean { + return this.livePipes.has(pid); } - this.timer = setTimeout(() => { - this.timer = null; - void this.tickAndReschedule(); - }, Math.max(0, delayMs)); - } - private async tickAndReschedule(): Promise { - try { - await this.tickOnce(); - } finally { - this.scheduleNext(this.intervalMs); + /** Was this PID alive as of the last completed tick? */ + isProcessAlive(pid: number): boolean { + return this.knownPids.has(pid); } - } - /** - * Read processes + live pipes, emit diff events. If another tick is - * already running, mark a follow-up tick so we don't lose a wake(). - */ - private async tickOnce(): Promise { - if (this.ticking) { - this.pendingWake = true; - return; + /** + * Run an initial tick (so isPipeLive/isProcessAlive return real data) + * and begin the polling loop. Idempotent. + */ + start(): Promise { + if (this.startPromise) { + return this.startPromise; + } + + this.startPromise = (async () => { + try { + await this.tickOnce(); + } finally { + this.scheduleNext(this.intervalMs); + } + })(); + return this.startPromise; } - this.ticking = true; - try { - let processes: HookProcessBaseInfo[] | null; - try { - processes = await this.listProcesses(); - } catch (error) { - this.log.warn('listProcesses failed: %s', errMsg(error)); - processes = null; - } - // UNKNOWN (timeout / failure): keep the prior process + pipe snapshot. - // Treating missing data as "everything disappeared" would fire - // process-gone for every live PID and dispose healthy sessions — the - // freeze-then-teardown footgun behind issue #158. Still emit 'tick' so - // the manager's per-tick reconnect retries keep running off last-known - // live pipes. - if (processes === null) { - this.emit('tick'); - return; - } - let livePipes: Set | null; - try { - livePipes = await this.listLivePipes(processes); - } catch (error) { - this.log.warn('listLivePipes failed: %s', errMsg(error)); - livePipes = null; - } - const newKnownPids = new Set(); - for (const proc of processes) newKnownPids.add(proc.pid); - - // 1. Newly discovered processes. - for (const proc of processes) { - if (!this.knownPids.has(proc.pid)) { - this.emit('process-discovered', proc); + /** Pull the next scheduled tick forward to the next event-loop turn. */ + wake(): void { + if (this.stopped) { + return; } - } - // 2. Pipes that came up. Ignore pipes for processes we don't know - // about (would race against an out-of-order tick). - const newLivePipes = new Set(); - if (livePipes === null) { - // Keep the last known pipe state for processes that still exist, while - // allowing confirmed process exits to complete their normal teardown. - for (const pid of this.livePipes) { - if (newKnownPids.has(pid)) newLivePipes.add(pid); - } - } else { - for (const pid of livePipes) { - if (!newKnownPids.has(pid)) continue; - newLivePipes.add(pid); - if (!this.livePipes.has(pid)) { - this.emit('pipe-up', pid); - } - } - } - - // 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so - // subscribers can run disconnect logic before dispose logic. - for (const pid of this.livePipes) { - if (!newLivePipes.has(pid)) { - this.emit('pipe-down', pid); - } - } - - // 4. Processes that disappeared. - for (const pid of this.knownPids) { - if (!newKnownPids.has(pid)) { - this.emit('process-gone', pid); - } - } - - this.knownPids = newKnownPids; - this.livePipes = newLivePipes; - this.emit('tick'); - } finally { - this.ticking = false; - if (this.pendingWake) { - this.pendingWake = false; - // Defer to break sync recursion if a listener calls wake(). - setImmediate(() => { void this.tickOnce(); }); - } + this.scheduleNext(0); + } + + /** Force a single tick now. Resolves after diff events have been emitted. */ + tickNow(): Promise { + return this.tickOnce(); + } + + stop(): void { + this.stopped = true; + + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + } + + dispose(): void { + this.stop(); + this.removeAllListeners(); + } + + private scheduleNext(delayMs: number): void { + if (this.stopped) { + return; + } + + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + + this.timer = setTimeout( + () => { + this.timer = null; + void this.tickAndReschedule(); + }, + Math.max(0, delayMs), + ); + } + + private async tickAndReschedule(): Promise { + try { + await this.tickOnce(); + } finally { + this.scheduleNext(this.intervalMs); + } + } + + /** + * Read processes + live pipes, emit diff events. If another tick is + * already running, mark a follow-up tick so we don't lose a wake(). + */ + private async tickOnce(): Promise { + if (this.ticking) { + this.pendingWake = true; + return; + } + + this.ticking = true; + + try { + let processes: HookProcessBaseInfo[] | null; + + try { + processes = await this.listProcesses(); + } catch (error) { + this.log.warn('listProcesses failed: %s', errMsg(error)); + processes = null; + } + + // UNKNOWN (timeout / failure): keep the prior process + pipe snapshot. + // Treating missing data as "everything disappeared" would fire + // process-gone for every live PID and dispose healthy sessions — the + // freeze-then-teardown footgun behind issue #158. Still emit 'tick' so + // the manager's per-tick reconnect retries keep running off last-known + // live pipes. + if (processes === null) { + this.emit('tick'); + return; + } + + let livePipes: Set | null; + + try { + livePipes = await this.listLivePipes(processes); + } catch (error) { + this.log.warn('listLivePipes failed: %s', errMsg(error)); + livePipes = null; + } + + const newKnownPids = new Set(); + + for (const proc of processes) { + newKnownPids.add(proc.pid); + } + + // 1. Newly discovered processes. + for (const proc of processes) { + if (!this.knownPids.has(proc.pid)) { + this.emit('process-discovered', proc); + } + } + + // 2. Pipes that came up. Ignore pipes for processes we don't know + // about (would race against an out-of-order tick). + const newLivePipes = new Set(); + + if (livePipes === null) { + // Keep the last known pipe state for processes that still exist, while + // allowing confirmed process exits to complete their normal teardown. + for (const pid of this.livePipes) { + if (newKnownPids.has(pid)) { + newLivePipes.add(pid); + } + } + } else { + for (const pid of livePipes) { + if (!newKnownPids.has(pid)) { + continue; + } + + newLivePipes.add(pid); + + if (!this.livePipes.has(pid)) { + this.emit('pipe-up', pid); + } + } + } + + // 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so + // subscribers can run disconnect logic before dispose logic. + for (const pid of this.livePipes) { + if (!newLivePipes.has(pid)) { + this.emit('pipe-down', pid); + } + } + + // 4. Processes that disappeared. + for (const pid of this.knownPids) { + if (!newKnownPids.has(pid)) { + this.emit('process-gone', pid); + } + } + + this.knownPids = newKnownPids; + this.livePipes = newLivePipes; + this.emit('tick'); + } finally { + this.ticking = false; + + if (this.pendingWake) { + this.pendingWake = false; + // Defer to break sync recursion if a listener calls wake(). + setImmediate(() => { + void this.tickOnce(); + }); + } + } } - } } function errMsg(value: unknown): string { - return value instanceof Error ? value.message : String(value); + return value instanceof Error ? value.message : String(value); } diff --git a/packages/bridge/src/process-enumerator.ts b/packages/bridge/src/process-enumerator.ts index 82287745..b11579c9 100644 --- a/packages/bridge/src/process-enumerator.ts +++ b/packages/bridge/src/process-enumerator.ts @@ -29,30 +29,30 @@ import type { HookProcessBaseInfo } from './injector'; * exactly today's behaviour, no worse. */ export interface ProcessEnumerator { - /** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed - * out / failed and the caller should keep its prior state. */ - enumerate(): Promise; - dispose(): void; + /** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed + * out / failed and the caller should keep its prior state. */ + enumerate(): Promise; + dispose(): void; } export interface NativeEnumeratorDeps { - /** Resolved path to the hook `.node` addon, or null when there is none - * (macOS / missing) — in which case we never spawn a worker. */ - addonPath: string | null; - /** Synchronous lister used when worker isolation is unavailable. Returns - * today's value (and may itself block — that's the no-worse-than-before - * fallback). */ - fallbackSync: () => HookProcessBaseInfo[]; - /** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */ - processName: string; - /** Per-enumeration deadline. Default 4000ms — comfortably above a healthy - * enumeration (single-digit ms) but well under a human "is it dead?". */ - timeoutMs?: number; - /** Cap on abandoned (blocked) workers before we stop spawning more and just - * return UNKNOWN until they drain. Bounds thread growth across a long - * hot-update window. Default 4. */ - maxOrphans?: number; - log?: Logger; + /** Resolved path to the hook `.node` addon, or null when there is none + * (macOS / missing) — in which case we never spawn a worker. */ + addonPath: string | null; + /** Synchronous lister used when worker isolation is unavailable. Returns + * today's value (and may itself block — that's the no-worse-than-before + * fallback). */ + fallbackSync: () => HookProcessBaseInfo[]; + /** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */ + processName: string; + /** Per-enumeration deadline. Default 4000ms — comfortably above a healthy + * enumeration (single-digit ms) but well under a human "is it dead?". */ + timeoutMs?: number; + /** Cap on abandoned (blocked) workers before we stop spawning more and just + * return UNKNOWN until they drain. Bounds thread growth across a long + * hot-update window. Default 4. */ + maxOrphans?: number; + log?: Logger; } const DEFAULT_TIMEOUT_MS = 4000; @@ -87,152 +87,205 @@ if (addon) { `; function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] { - return [...new Set(pids)] - .filter((pid) => Number.isInteger(pid) && pid > 0) - .sort((a, b) => a - b) - .map((pid) => ({ pid, name: processName, path: '' })); + return [...new Set(pids)] + .filter((pid) => Number.isInteger(pid) && pid > 0) + .sort((a, b) => a - b) + .map((pid) => ({ pid, name: processName, path: '' })); } export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator { - const log = deps.log ?? createLogger('ProcessEnumerator'); - const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS; - const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS; + const log = deps.log ?? createLogger('ProcessEnumerator'); + const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS; - // No addon to isolate (macOS / missing) → never spawn a worker; the sync - // fallback there is a cheap socket read, not a /proc walk. - if (!deps.addonPath) { - return { - async enumerate() { - try { - return deps.fallbackSync(); - } catch (err) { - log.warn('enumerate fallback failed: %s', errMsg(err)); - return null; - } - }, - dispose() { /* nothing to tear down */ }, - }; - } - - const addonPath = deps.addonPath; - let worker: Worker | null = null; - /** Set once we learn the addon can't load in a worker — permanent fallback. */ - let isolationBroken = false; - let orphans = 0; - let seq = 0; - const pending = new Map void }>(); - let disposed = false; - - const spawnWorker = (): void => { - const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } }); - worker = w; - w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => { - if (msg.type === 'ready') return; - if (msg.type === 'fatal') { - // The addon won't load off-thread — give up on isolation for good and - // fall back to the synchronous path from here on. Resolve any in-flight - // request now (UNKNOWN) so it doesn't sit waiting for the timeout. - log.warn('process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration', msg.error ?? ''); - isolationBroken = true; - for (const { resolve } of pending.values()) resolve(null); - pending.clear(); - teardownWorker(); - return; - } - if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') { - const entry = pending.get(msg.id); - if (!entry) return; - pending.delete(msg.id); - entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null); - } - }); - w.on('error', (err) => { - log.warn('enumeration worker error: %s', errMsg(err)); - if (worker === w) teardownWorker(); - }); - }; - - const teardownWorker = (): void => { - const w = worker; - worker = null; - if (!w) return; - // terminate() can't preempt a thread blocked in the native call; it takes - // effect once the call returns. Track it as an orphan until it actually - // exits so we can bound how many we let pile up. - orphans += 1; - w.once('exit', () => { orphans = Math.max(0, orphans - 1); }); - void w.terminate().catch(() => { /* already gone */ }); - }; - - const syncFallback = (): HookProcessBaseInfo[] | null => { - try { - return deps.fallbackSync(); - } catch (err) { - log.warn('enumerate sync fallback failed: %s', errMsg(err)); - return null; + // No addon to isolate (macOS / missing) → never spawn a worker; the sync + // fallback there is a cheap socket read, not a /proc walk. + if (!deps.addonPath) { + return { + async enumerate() { + try { + return deps.fallbackSync(); + } catch (err) { + log.warn('enumerate fallback failed: %s', errMsg(err)); + return null; + } + }, + dispose() { + /* nothing to tear down */ + }, + }; } - }; - return { - async enumerate(): Promise { - if (disposed || isolationBroken) return syncFallback(); + const addonPath = deps.addonPath; + let worker: Worker | null = null; + /** Set once we learn the addon can't load in a worker — permanent fallback. */ + let isolationBroken = false; + let orphans = 0; + let seq = 0; + const pending = new Map void }>(); + let disposed = false; - if (!worker) { - if (orphans >= maxOrphans) { - // Too many blocked workers already piling up (a sustained hang) — - // don't spawn more; report UNKNOWN and let them drain. - return null; + const spawnWorker = (): void => { + const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } }); + worker = w; + w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => { + if (msg.type === 'ready') { + return; + } + + if (msg.type === 'fatal') { + // The addon won't load off-thread — give up on isolation for good and + // fall back to the synchronous path from here on. Resolve any in-flight + // request now (UNKNOWN) so it doesn't sit waiting for the timeout. + log.warn( + 'process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration', + msg.error ?? '', + ); + isolationBroken = true; + + for (const { resolve } of pending.values()) { + resolve(null); + } + + pending.clear(); + teardownWorker(); + return; + } + + if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') { + const entry = pending.get(msg.id); + + if (!entry) { + return; + } + + pending.delete(msg.id); + entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null); + } + }); + w.on('error', (err) => { + log.warn('enumeration worker error: %s', errMsg(err)); + + if (worker === w) { + teardownWorker(); + } + }); + }; + + const teardownWorker = (): void => { + const w = worker; + worker = null; + + if (!w) { + return; } - spawnWorker(); - } - const w = worker; - if (!w) return syncFallback(); - const id = ++seq; - const resultPromise = new Promise((resolve) => { - pending.set(id, { resolve }); - }); - try { - w.postMessage({ type: 'enumerate', id }); - } catch (err) { - pending.delete(id); - log.warn('failed to post enumerate request: %s', errMsg(err)); - teardownWorker(); - return syncFallback(); - } + // terminate() can't preempt a thread blocked in the native call; it takes + // effect once the call returns. Track it as an orphan until it actually + // exits so we can bound how many we let pile up. + orphans += 1; + w.once('exit', () => { + orphans = Math.max(0, orphans - 1); + }); + void w.terminate().catch(() => { + /* already gone */ + }); + }; - let timer: NodeJS.Timeout | undefined; - const timeout = new Promise<'timeout'>((resolve) => { - timer = setTimeout(() => resolve('timeout'), timeoutMs); - }); - const outcome = await Promise.race([resultPromise, timeout]); - if (timer) clearTimeout(timer); + const syncFallback = (): HookProcessBaseInfo[] | null => { + try { + return deps.fallbackSync(); + } catch (err) { + log.warn('enumerate sync fallback failed: %s', errMsg(err)); + return null; + } + }; - if (outcome === 'timeout') { - pending.delete(id); - log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs); - teardownWorker(); - return null; - } - if (outcome === null) { - // Native call threw inside the worker — treat as a transient failure, - // keep prior state rather than nuking every session. - return null; - } - return mapPids(outcome, deps.processName); - }, + return { + async enumerate(): Promise { + if (disposed || isolationBroken) { + return syncFallback(); + } - dispose() { - disposed = true; - for (const { resolve } of pending.values()) resolve(null); - pending.clear(); - const w = worker; - worker = null; - if (w) void w.terminate().catch(() => { /* ignore */ }); - }, - }; + if (!worker) { + if (orphans >= maxOrphans) { + // Too many blocked workers already piling up (a sustained hang) — + // don't spawn more; report UNKNOWN and let them drain. + return null; + } + + spawnWorker(); + } + + const w = worker; + + if (!w) { + return syncFallback(); + } + + const id = ++seq; + const resultPromise = new Promise((resolve) => { + pending.set(id, { resolve }); + }); + + try { + w.postMessage({ type: 'enumerate', id }); + } catch (err) { + pending.delete(id); + log.warn('failed to post enumerate request: %s', errMsg(err)); + teardownWorker(); + return syncFallback(); + } + + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise<'timeout'>((resolve) => { + timer = setTimeout(() => resolve('timeout'), timeoutMs); + }); + const outcome = await Promise.race([resultPromise, timeout]); + + if (timer) { + clearTimeout(timer); + } + + if (outcome === 'timeout') { + pending.delete(id); + log.warn( + 'process enumeration timed out after %dms (worker abandoned) — keeping prior process set', + timeoutMs, + ); + teardownWorker(); + return null; + } + + if (outcome === null) { + // Native call threw inside the worker — treat as a transient failure, + // keep prior state rather than nuking every session. + return null; + } + + return mapPids(outcome, deps.processName); + }, + + dispose() { + disposed = true; + + for (const { resolve } of pending.values()) { + resolve(null); + } + + pending.clear(); + const w = worker; + worker = null; + + if (w) { + void w.terminate().catch(() => { + /* ignore */ + }); + } + }, + }; } function errMsg(value: unknown): string { - return value instanceof Error ? value.message : String(value); + return value instanceof Error ? value.message : String(value); } diff --git a/packages/bridge/src/qq-hook-client.ts b/packages/bridge/src/qq-hook-client.ts index 6271cc2f..09cbb44f 100644 --- a/packages/bridge/src/qq-hook-client.ts +++ b/packages/bridge/src/qq-hook-client.ts @@ -1,9 +1,9 @@ import { EventEmitter } from 'events'; import { - createLogger, - renderTraceBytes, - runWithoutRequestContext, - runWithTraceRequest, + createLogger, + renderTraceBytes, + runWithoutRequestContext, + runWithTraceRequest, } from '@snowluma/common/logger'; import { renderParamsVerbose } from '@snowluma/common/log-summary'; import { isRealUin } from '@snowluma/common/uin'; @@ -30,93 +30,95 @@ const packetLog = createLogger('QQHook.Packet'); const runtimeLog = createLogger('QQHook.Runtime'); export enum PipeOp { - hello = 1, - sendRequest = 2, - sendAck = 3, - sendReply = 4, - error = 5, - recvPacket = 6, - loginState = 7, - loginIdentityHint = 17, + hello = 1, + sendRequest = 2, + sendAck = 3, + sendReply = 4, + error = 5, + recvPacket = 6, + loginState = 7, + loginIdentityHint = 17, } const PipeFlagWantReply = 1 << 0; const PipeFlagLoggedIn = 1 << 2; export interface QqHookLoginState { - loggedIn: boolean; - uin: string; - uinNumber: bigint; + loggedIn: boolean; + uin: string; + uinNumber: bigint; } export interface QqHookPacket { - seq: number; - error: number; - cmd: string; - uin: string; - body: Buffer; + seq: number; + error: number; + cmd: string; + uin: string; + body: Buffer; } export interface QqHookHello { - pipeName: string; - pid: number; - recvPipe: boolean; + pipeName: string; + pid: number; + recvPipe: boolean; } export interface QqHookSendReply { - requestId: number; - error: number; - message: string; - body: Buffer; + requestId: number; + error: number; + message: string; + body: Buffer; } export interface QqHookClientOptions { - ackTimeoutMs?: number; - replyTimeoutMs?: number; - runtimeDir?: string; + ackTimeoutMs?: number; + replyTimeoutMs?: number; + runtimeDir?: string; } export interface QqHookSendOptions { - wantReply?: boolean; - ackTimeoutMs?: number; - replyTimeoutMs?: number; + wantReply?: boolean; + ackTimeoutMs?: number; + replyTimeoutMs?: number; } interface PipeFrame { - op: number; - requestId: number; - status: number; - flags: number; - value0: bigint; - cmd: string; - msg: string; - body: Buffer; + op: number; + requestId: number; + status: number; + flags: number; + value0: bigint; + cmd: string; + msg: string; + body: Buffer; } interface Deferred { - promise: Promise; - resolve: (value: T | PromiseLike) => void; - reject: (reason?: unknown) => void; + promise: Promise; + resolve: (value: T | PromiseLike) => void; + reject: (reason?: unknown) => void; } interface PendingAck { - resolve: (value: { requestId: number; wantReply: boolean }) => void; - reject: (reason?: unknown) => void; - wantReply: boolean; + resolve: (value: { requestId: number; wantReply: boolean }) => void; + reject: (reason?: unknown) => void; + wantReply: boolean; } function isMissingDirectoryError(error: unknown): boolean { - const code = (error as NodeJS.ErrnoException | undefined)?.code; - return code === 'ENOENT' || code === 'ENOTDIR'; + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return code === 'ENOENT' || code === 'ENOTDIR'; } function isUnavailableSocketError(error: unknown): boolean { - const code = (error as NodeJS.ErrnoException | undefined)?.code; - return code === 'ENOENT' - || code === 'ENOTDIR' - || code === 'ENOTSOCK' - || code === 'ECONNREFUSED' - || code === 'ECONNRESET'; + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return ( + code === 'ENOENT' || + code === 'ENOTDIR' || + code === 'ENOTSOCK' || + code === 'ECONNREFUSED' || + code === 'ECONNRESET' + ); } /** @@ -132,980 +134,1233 @@ function isUnavailableSocketError(error: unknown): boolean { * sufficient signal for "process exists with our dylib mapped". The async * variant still gates the subsequent `pipe-up` emit via a real connect. */ -export function listSnowlumaPipePidsSync( - runtimeDir = resolveHookRuntimeDir(), -): Set { - const result = new Set(); - let names: string[]; - try { - names = readdirSync(runtimeDir); - } catch (error) { - if (isMissingDirectoryError(error)) return result; - throw error; - } - for (const name of names) { - const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name); - if (!m) continue; - const pid = Number(m[1]); - if (Number.isInteger(pid) && pid > 0) result.add(pid); - } - return result; +export function listSnowlumaPipePidsSync(runtimeDir = resolveHookRuntimeDir()): Set { + const result = new Set(); + let names: string[]; + + try { + names = readdirSync(runtimeDir); + } catch (error) { + if (isMissingDirectoryError(error)) { + return result; + } + + throw error; + } + + for (const name of names) { + const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name); + + if (!m) { + continue; + } + + const pid = Number(m[1]); + + if (Number.isInteger(pid) && pid > 0) { + result.add(pid); + } + } + + return result; } -function mojoPipeName(pid: number, suffix: string, runtimeDir = resolveHookRuntimeDir(pid)): string { - if (process.platform === 'win32') { - return `\\\\.\\pipe\\mojo.${pid}.${suffix}`; - } - return path.join(runtimeDir, `mojo.${pid}.${suffix}.sock`); +function mojoPipeName( + pid: number, + suffix: string, + runtimeDir = resolveHookRuntimeDir(pid), +): string { + if (process.platform === 'win32') { + return `\\\\.\\pipe\\mojo.${pid}.${suffix}`; + } + + return path.join(runtimeDir, `mojo.${pid}.${suffix}.sock`); } type LinuxPipeProbe = (socketPath: string) => Promise; async function isConnectableUnixSocket(socketPath: string): Promise { - try { - const stat = await fs.stat(socketPath); - if (!stat.isSocket()) return false; - } catch (error) { - if (isUnavailableSocketError(error)) return false; - throw error; - } - - return new Promise((resolve, reject) => { - let socket: net.Socket; try { - socket = net.createConnection(socketPath); + const stat = await fs.stat(socketPath); + + if (!stat.isSocket()) { + return false; + } } catch (error) { - if (isUnavailableSocketError(error)) resolve(false); - else reject(error); - return; + if (isUnavailableSocketError(error)) { + return false; + } + + throw error; } - let done = false; - let timer: NodeJS.Timeout; - const finish = (ok: boolean) => { - if (done) return; - done = true; - clearTimeout(timer); - socket.removeAllListeners(); - socket.destroy(); - resolve(ok); - }; - timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS); - socket.once('connect', () => finish(true)); - socket.once('error', error => { - if (isUnavailableSocketError(error)) finish(false); - else { - if (done) return; - done = true; - clearTimeout(timer); - socket.removeAllListeners(); - socket.destroy(); - reject(error); - } + + return new Promise((resolve, reject) => { + let socket: net.Socket; + + try { + socket = net.createConnection(socketPath); + } catch (error) { + if (isUnavailableSocketError(error)) { + resolve(false); + } else { + reject(error); + } + + return; + } + + let done = false; + let timer: NodeJS.Timeout; + + const finish = (ok: boolean) => { + if (done) { + return; + } + + done = true; + clearTimeout(timer); + socket.removeAllListeners(); + socket.destroy(); + resolve(ok); + }; + + timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS); + socket.once('connect', () => finish(true)); + socket.once('error', (error) => { + if (isUnavailableSocketError(error)) { + finish(false); + } else { + if (done) { + return; + } + + done = true; + clearTimeout(timer); + socket.removeAllListeners(); + socket.destroy(); + reject(error); + } + }); }); - }); } export async function listLiveLinuxPipePids( - runtimeDir = resolveHookRuntimeDir(), - probe: LinuxPipeProbe = isConnectableUnixSocket, + runtimeDir = resolveHookRuntimeDir(), + probe: LinuxPipeProbe = isConnectableUnixSocket, ): Promise> { - const result = new Set(); - let names: string[]; - try { - names = await fs.readdir(runtimeDir); - } catch (error) { - if (isMissingDirectoryError(error)) return result; - throw error; - } + const result = new Set(); + let names: string[]; - await Promise.all(names.map(async (name) => { - const m = /^mojo\.(\d+)\.control\.sock$/.exec(name); - if (!m) return; - const pid = Number(m[1]); - if (!Number.isInteger(pid) || pid <= 0) return; - if (await probe(path.join(runtimeDir, name))) result.add(pid); - })); + try { + names = await fs.readdir(runtimeDir); + } catch (error) { + if (isMissingDirectoryError(error)) { + return result; + } - return result; + throw error; + } + + await Promise.all( + names.map(async (name) => { + const m = /^mojo\.(\d+)\.control\.sock$/.exec(name); + + if (!m) { + return; + } + + const pid = Number(m[1]); + + if (!Number.isInteger(pid) || pid <= 0) { + return; + } + + if (await probe(path.join(runtimeDir, name))) { + result.add(pid); + } + }), + ); + + return result; } function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer { - if (Buffer.isBuffer(body)) return body; - if (body instanceof Uint8Array) return Buffer.from(body); - if (typeof body === 'string') return Buffer.from(body, 'utf8'); - if (body == null) return Buffer.alloc(0); - throw new TypeError('body must be Buffer, Uint8Array, string, or null'); + if (Buffer.isBuffer(body)) { + return body; + } + + if (body instanceof Uint8Array) { + return Buffer.from(body); + } + + if (typeof body === 'string') { + return Buffer.from(body, 'utf8'); + } + + if (body == null) { + return Buffer.alloc(0); + } + + throw new TypeError('body must be Buffer, Uint8Array, string, or null'); } function createDeferred(): Deferred { - let resolve!: (value: T | PromiseLike) => void; - let reject!: (reason?: unknown) => void; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { promise, resolve, reject }; + let resolve!: (value: T | PromiseLike) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; } class OperationTimeoutError extends Error { - constructor( - readonly label: string, - timeoutMs: number, - ) { - super(`${label} timed out after ${timeoutMs} ms`); - this.name = 'OperationTimeoutError'; - } + constructor( + readonly label: string, + timeoutMs: number, + ) { + super(`${label} timed out after ${timeoutMs} ms`); + this.name = 'OperationTimeoutError'; + } } function withTimeout(promise: Promise, timeoutMs: number, label: string): Promise { - if (!timeoutMs || timeoutMs <= 0) return promise; - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - reject(new OperationTimeoutError(label, timeoutMs)); - }, timeoutMs); - promise.then( - value => { - clearTimeout(timer); - resolve(value); - }, - error => { - clearTimeout(timer); - reject(error); - }); - }); + if (!timeoutMs || timeoutMs <= 0) { + return promise; + } + + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new OperationTimeoutError(label, timeoutMs)); + }, timeoutMs); + promise.then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + (error) => { + clearTimeout(timer); + reject(error); + }, + ); + }); } export class HookPipeRequestError extends Error { - constructor( - message: string, - readonly status: number, - readonly requestId: number, - ) { - super(message); - this.name = 'HookPipeRequestError'; - } + constructor( + message: string, + readonly status: number, + readonly requestId: number, + ) { + super(message); + this.name = 'HookPipeRequestError'; + } } function packetFailureReason( - error: unknown, - requestId: number, + error: unknown, + requestId: number, ): 'ack_timeout' | 'reply_timeout' | 'request_failed' | 'transport_failure' { - if (error instanceof HookPipeRequestError) return 'request_failed'; - if (error instanceof OperationTimeoutError) { - if (error.label === `send ack ${requestId}`) return 'ack_timeout'; - if (error.label === `send reply ${requestId}`) return 'reply_timeout'; - } - return 'transport_failure'; + if (error instanceof HookPipeRequestError) { + return 'request_failed'; + } + + if (error instanceof OperationTimeoutError) { + if (error.label === `send ack ${requestId}`) { + return 'ack_timeout'; + } + + if (error.label === `send reply ${requestId}`) { + return 'reply_timeout'; + } + } + + return 'transport_failure'; } function encodeFrame({ - op, - requestId = 0, - status = 0, - flags = 0, - value0 = 0n, - cmd = '', - msg = '', - body = Buffer.alloc(0), + op, + requestId = 0, + status = 0, + flags = 0, + value0 = 0n, + cmd = '', + msg = '', + body = Buffer.alloc(0), }: { - op: number; - requestId?: number; - status?: number; - flags?: number; - value0?: bigint | number; - cmd?: string; - msg?: string; - body?: Buffer | Uint8Array | string | null; + op: number; + requestId?: number; + status?: number; + flags?: number; + value0?: bigint | number; + cmd?: string; + msg?: string; + body?: Buffer | Uint8Array | string | null; }): Buffer { - const cmdBuf = Buffer.from(cmd, 'utf8'); - const msgBuf = Buffer.from(msg, 'utf8'); - const bodyBuf = toBuffer(body); - validatePipeFrameLengths(cmdBuf.length, msgBuf.length, bodyBuf.length); - const header = Buffer.alloc(HEADER_SIZE); - header.writeUInt32LE(PIPE_MAGIC, 0); - header.writeUInt16LE(PIPE_VERSION, 4); - header.writeUInt16LE(op, 6); - header.writeUInt32LE(requestId >>> 0, 8); - header.writeInt32LE(status | 0, 12); - header.writeUInt32LE(flags >>> 0, 16); - header.writeUInt32LE(cmdBuf.length >>> 0, 20); - header.writeUInt32LE(msgBuf.length >>> 0, 24); - header.writeUInt32LE(bodyBuf.length >>> 0, 28); - header.writeBigUInt64LE(BigInt(value0), 32); - return Buffer.concat([header, cmdBuf, msgBuf, bodyBuf]); + const cmdBuf = Buffer.from(cmd, 'utf8'); + const msgBuf = Buffer.from(msg, 'utf8'); + const bodyBuf = toBuffer(body); + validatePipeFrameLengths(cmdBuf.length, msgBuf.length, bodyBuf.length); + const header = Buffer.alloc(HEADER_SIZE); + header.writeUInt32LE(PIPE_MAGIC, 0); + header.writeUInt16LE(PIPE_VERSION, 4); + header.writeUInt16LE(op, 6); + header.writeUInt32LE(requestId >>> 0, 8); + header.writeInt32LE(status | 0, 12); + header.writeUInt32LE(flags >>> 0, 16); + header.writeUInt32LE(cmdBuf.length >>> 0, 20); + header.writeUInt32LE(msgBuf.length >>> 0, 24); + header.writeUInt32LE(bodyBuf.length >>> 0, 28); + header.writeBigUInt64LE(BigInt(value0), 32); + return Buffer.concat([header, cmdBuf, msgBuf, bodyBuf]); } function validatePipeFrameLengths(cmdLen: number, msgLen: number, bodyLen: number): void { - const lengths = [ - ['command', cmdLen, MAX_PIPE_CMD_BYTES], - ['message', msgLen, MAX_PIPE_MSG_BYTES], - ['body', bodyLen, MAX_PIPE_BODY_BYTES], - ] as const; - for (const [name, length, limit] of lengths) { - if (length > limit) { - throw new Error(`pipe frame ${name} length ${length} exceeds limit ${limit}`); + const lengths = [ + ['command', cmdLen, MAX_PIPE_CMD_BYTES], + ['message', msgLen, MAX_PIPE_MSG_BYTES], + ['body', bodyLen, MAX_PIPE_BODY_BYTES], + ] as const; + + for (const [name, length, limit] of lengths) { + if (length > limit) { + throw new Error(`pipe frame ${name} length ${length} exceeds limit ${limit}`); + } } - } } interface PendingPipeFrame { - op: number; - requestId: number; - status: number; - flags: number; - value0: bigint; - cmdLen: number; - msgLen: number; - bodyLen: number; - payload: Buffer; - received: number; + op: number; + requestId: number; + status: number; + flags: number; + value0: bigint; + cmdLen: number; + msgLen: number; + bodyLen: number; + payload: Buffer; + received: number; } class FrameReader { - private readonly header = Buffer.alloc(HEADER_SIZE); - private headerBytes = 0; - private pending: PendingPipeFrame | null = null; + private readonly header = Buffer.alloc(HEADER_SIZE); + private headerBytes = 0; + private pending: PendingPipeFrame | null = null; - constructor(private readonly onFrame: (frame: PipeFrame) => void) { } + constructor(private readonly onFrame: (frame: PipeFrame) => void) {} - push(chunk: Buffer): void { - let chunkOffset = 0; - while (chunkOffset < chunk.length) { - if (!this.pending) { - const headerBytes = Math.min(HEADER_SIZE - this.headerBytes, chunk.length - chunkOffset); - chunk.copy( - this.header, - this.headerBytes, - chunkOffset, - chunkOffset + headerBytes, - ); - this.headerBytes += headerBytes; - chunkOffset += headerBytes; - if (this.headerBytes < HEADER_SIZE) return; + push(chunk: Buffer): void { + let chunkOffset = 0; - this.headerBytes = 0; - const magic = this.header.readUInt32LE(0); - const version = this.header.readUInt16LE(4); - if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) { - throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`); + while (chunkOffset < chunk.length) { + if (!this.pending) { + const headerBytes = Math.min( + HEADER_SIZE - this.headerBytes, + chunk.length - chunkOffset, + ); + chunk.copy(this.header, this.headerBytes, chunkOffset, chunkOffset + headerBytes); + this.headerBytes += headerBytes; + chunkOffset += headerBytes; + + if (this.headerBytes < HEADER_SIZE) { + return; + } + + this.headerBytes = 0; + const magic = this.header.readUInt32LE(0); + const version = this.header.readUInt16LE(4); + + if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) { + throw new Error( + `bad frame header magic=0x${magic.toString(16)} version=${version}`, + ); + } + + const cmdLen = this.header.readUInt32LE(20); + const msgLen = this.header.readUInt32LE(24); + const bodyLen = this.header.readUInt32LE(28); + validatePipeFrameLengths(cmdLen, msgLen, bodyLen); + const payloadLength = cmdLen + msgLen + bodyLen; + this.pending = { + op: this.header.readUInt16LE(6), + requestId: this.header.readUInt32LE(8), + status: this.header.readInt32LE(12), + flags: this.header.readUInt32LE(16), + value0: this.header.readBigUInt64LE(32), + cmdLen, + msgLen, + bodyLen, + payload: + payloadLength === 0 ? Buffer.alloc(0) : Buffer.allocUnsafe(payloadLength), + received: 0, + }; + } + + const pending = this.pending; + const payloadBytes = Math.min( + pending.payload.length - pending.received, + chunk.length - chunkOffset, + ); + + if (payloadBytes > 0) { + chunk.copy( + pending.payload, + pending.received, + chunkOffset, + chunkOffset + payloadBytes, + ); + pending.received += payloadBytes; + chunkOffset += payloadBytes; + } + + if (pending.received < pending.payload.length) { + return; + } + + this.pending = null; + const frame: PipeFrame = { + op: pending.op, + requestId: pending.requestId, + status: pending.status, + flags: pending.flags, + value0: pending.value0, + cmd: '', + msg: '', + body: Buffer.alloc(0), + }; + + let offset = 0; + frame.cmd = pending.payload.subarray(offset, offset + pending.cmdLen).toString('utf8'); + offset += pending.cmdLen; + frame.msg = pending.payload.subarray(offset, offset + pending.msgLen).toString('utf8'); + offset += pending.msgLen; + frame.body = Buffer.from(pending.payload.subarray(offset, offset + pending.bodyLen)); + this.onFrame(frame); } - - const cmdLen = this.header.readUInt32LE(20); - const msgLen = this.header.readUInt32LE(24); - const bodyLen = this.header.readUInt32LE(28); - validatePipeFrameLengths(cmdLen, msgLen, bodyLen); - const payloadLength = cmdLen + msgLen + bodyLen; - this.pending = { - op: this.header.readUInt16LE(6), - requestId: this.header.readUInt32LE(8), - status: this.header.readInt32LE(12), - flags: this.header.readUInt32LE(16), - value0: this.header.readBigUInt64LE(32), - cmdLen, - msgLen, - bodyLen, - payload: payloadLength === 0 ? Buffer.alloc(0) : Buffer.allocUnsafe(payloadLength), - received: 0, - }; - } - - const pending = this.pending; - const payloadBytes = Math.min( - pending.payload.length - pending.received, - chunk.length - chunkOffset, - ); - if (payloadBytes > 0) { - chunk.copy( - pending.payload, - pending.received, - chunkOffset, - chunkOffset + payloadBytes, - ); - pending.received += payloadBytes; - chunkOffset += payloadBytes; - } - if (pending.received < pending.payload.length) return; - - this.pending = null; - const frame: PipeFrame = { - op: pending.op, - requestId: pending.requestId, - status: pending.status, - flags: pending.flags, - value0: pending.value0, - cmd: '', - msg: '', - body: Buffer.alloc(0), - }; - - let offset = 0; - frame.cmd = pending.payload.subarray(offset, offset + pending.cmdLen).toString('utf8'); - offset += pending.cmdLen; - frame.msg = pending.payload.subarray(offset, offset + pending.msgLen).toString('utf8'); - offset += pending.msgLen; - frame.body = Buffer.from(pending.payload.subarray(offset, offset + pending.bodyLen)); - this.onFrame(frame); } - } } export class QqHookClient extends EventEmitter { - readonly pid: number; - readonly runtimeDir: string; - readonly defaultAckTimeoutMs: number; - readonly defaultReplyTimeoutMs: number; + readonly pid: number; + readonly runtimeDir: string; + readonly defaultAckTimeoutMs: number; + readonly defaultReplyTimeoutMs: number; - private controlSocket: net.Socket | null = null; - private recvSocket: net.Socket | null = null; - private controlConnectPromise: Promise | null = null; - private recvConnectPromise: Promise | null = null; - private nextRequestId = 1; - private pendingAcks = new Map(); - private pendingReplies = new Map>(); - private controlHello: QqHookHello | null = null; - private recvHello: QqHookHello | null = null; - private controlHelloResolver: Deferred | null = null; - private recvHelloResolver: Deferred | null = null; - private controlWriteChain: Promise = Promise.resolve(); - private closed = false; - private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n }; - private loginWaiters: Deferred[] = []; + private controlSocket: net.Socket | null = null; + private recvSocket: net.Socket | null = null; + private controlConnectPromise: Promise | null = null; + private recvConnectPromise: Promise | null = null; + private nextRequestId = 1; + private pendingAcks = new Map(); + private pendingReplies = new Map>(); + private controlHello: QqHookHello | null = null; + private recvHello: QqHookHello | null = null; + private controlHelloResolver: Deferred | null = null; + private recvHelloResolver: Deferred | null = null; + private controlWriteChain: Promise = Promise.resolve(); + private closed = false; + private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n }; + private loginWaiters: Deferred[] = []; - constructor(pid: number, { - ackTimeoutMs = positiveIntEnv('SNOWLUMA_HOOK_ACK_TIMEOUT_MS', DEFAULT_ACK_TIMEOUT_MS), - replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS, - runtimeDir = resolveHookRuntimeDir(pid), - }: QqHookClientOptions = {}) { - super(); - this.pid = pid; - this.runtimeDir = runtimeDir; - this.defaultAckTimeoutMs = ackTimeoutMs; - this.defaultReplyTimeoutMs = replyTimeoutMs; - } - - get isLoggedIn(): boolean { - return this.loginState.loggedIn; - } - - get isClosed(): boolean { - return this.closed; - } - - get currentUin(): string { - return this.loginState.uin; - } - - get currentUinNumber(): bigint { - return this.loginState.uinNumber; - } - - getLoginState(): QqHookLoginState { - return { ...this.loginState }; - } - - /** - * Forward an observed account identity for reconciliation. This does not - * change login state; readiness still requires peer confirmation. - */ - async reconcileLoginIdentity(uin: string): Promise { - if (!isRealUin(uin)) { - throw new Error(`invalid QQ login identity hint: ${JSON.stringify(uin)}`); - } - await this.sendAckOnly(PipeOp.loginIdentityHint, BigInt(uin), 'login identity hint'); - } - - async waitForLogin({ timeoutMs = 0 } = {}): Promise { - await this.connect(); - if (this.loginState.loggedIn) { - return this.getLoginState(); - } - const deferred = createDeferred(); - this.loginWaiters.push(deferred); - return withTimeout(deferred.promise, timeoutMs, 'waitForLogin'); - } - - static controlPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string { - return mojoPipeName(pid, 'control', runtimeDir); - } - - static recvPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string { - return mojoPipeName(pid, 'recv', runtimeDir); - } - - /** - * Lightweight liveness check for the control pipe. Used to detect whether an - * existing SnowLuma hook is still hosted inside the QQ.exe process without - * opening the pipe, so probing cannot disturb the first real client connect. - */ - static async probePipe(pid: number): Promise { - const live = await QqHookClient.listLivePipes([pid]); - return live.has(pid); - } - - /** - * Enumerate every PID currently hosting a SnowLuma `mojo..control` pipe - * in a single filesystem listing. The HookManager's pipe-watcher uses this - * to drive connect/reconnect decisions without per-PID stat calls. - */ - static async listLivePipes(pids: readonly number[] = []): Promise> { - const result = new Set(); - if (process.platform === 'win32') { - const names = await fs.readdir('\\\\.\\pipe\\'); - for (const name of names) { - const m = /^mojo\.(\d+)\.control$/i.exec(name); - if (m) result.add(Number(m[1])); - } - } else { - const runtimeDirs = new Set(); - if (pids.length === 0) { - runtimeDirs.add(resolveHookRuntimeDir()); - } else { - for (const pid of pids) runtimeDirs.add(resolveHookRuntimeDir(pid)); - } - for (const runtimeDir of runtimeDirs) { - for (const pid of await listLiveLinuxPipePids(runtimeDir)) result.add(pid); - } - } - return result; - } - - async connect(): Promise { - if (this.closed) { - throw new Error('qq_hook client is closed'); - } - if (this.controlSocket && this.controlHello) { - return this.controlHello; - } - if (this.controlConnectPromise) { - return this.controlConnectPromise; - } - this.controlConnectPromise = this.connectPipe('control'); - try { - return await this.controlConnectPromise; - } finally { - this.controlConnectPromise = null; - } - } - - async startRecv(onPacket?: (packet: QqHookPacket) => void): Promise { - if (this.closed) { - throw new Error('qq_hook client is closed'); - } - if (typeof onPacket === 'function') { - this.on('packet', onPacket); - } - if (this.recvSocket && this.recvHello) { - return this.recvHello; - } - if (this.recvConnectPromise) { - return this.recvConnectPromise; - } - this.recvConnectPromise = this.connectPipe('recv'); - try { - return await this.recvConnectPromise; - } finally { - this.recvConnectPromise = null; - } - } - - async connectAll({ recv = true } = {}): Promise<{ control: QqHookHello; recv: QqHookHello | null }> { - const control = await this.connect(); - const recvInfo = recv ? await this.startRecv() : null; - return { control, recv: recvInfo }; - } - - async send(cmd: string, body: Buffer | Uint8Array | string | null | undefined, { - wantReply = true, - ackTimeoutMs = this.defaultAckTimeoutMs, - replyTimeoutMs = this.defaultReplyTimeoutMs, - }: QqHookSendOptions = {}): Promise { - await this.connect(); - - const requestId = this.allocateRequestId(); - const startedAt = Date.now(); - const bodyBytes = toBuffer(body); - const payload = encodeFrame({ - op: PipeOp.sendRequest, - requestId, - flags: wantReply ? PipeFlagWantReply : 0, - cmd, - body: bodyBytes, - }); - packetLog.trace(() => [ - 'packet_send serviceCmd=%j requestId=%d length=%d body=%s', - cmd, - requestId, - bodyBytes.length, - renderTraceBytes(bodyBytes), - ]); - - const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>(); - // Always attach a handler so a rejection can never become "unhandled" (which - // crashes Node). When the pipe closes, rejectControlPending() rejects every - // pending deferred — but the reply is only `await`ed AFTER the ack, so if the - // ack fails first the reply promise is rejected with NO awaiter. The real - // `await` below still observes the value/rejection (a separate continuation). - ackDeferred.promise.catch(() => { /* observed by the await, or harmless */ }); - this.pendingAcks.set(requestId, { - resolve: ackDeferred.resolve, - reject: ackDeferred.reject, - wantReply, - }); - - let replyDeferred: Deferred | null = null; - if (wantReply) { - replyDeferred = createDeferred(); - replyDeferred.promise.catch(() => { /* see note above — prevents unhandled rejection */ }); - this.pendingReplies.set(requestId, replyDeferred); + constructor( + pid: number, + { + ackTimeoutMs = positiveIntEnv('SNOWLUMA_HOOK_ACK_TIMEOUT_MS', DEFAULT_ACK_TIMEOUT_MS), + replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS, + runtimeDir = resolveHookRuntimeDir(pid), + }: QqHookClientOptions = {}, + ) { + super(); + this.pid = pid; + this.runtimeDir = runtimeDir; + this.defaultAckTimeoutMs = ackTimeoutMs; + this.defaultReplyTimeoutMs = replyTimeoutMs; } - try { - await this.writeControl(payload); - await withTimeout(ackDeferred.promise, ackTimeoutMs, `send ack ${requestId}`); - if (!wantReply) { - packetLog.trace(() => [ - 'packet_terminal serviceCmd=%j requestId=%d outcome=ok reason=ack_received elapsedMs=%d', - cmd, - requestId, - Date.now() - startedAt, - ]); - return { requestId }; - } - const reply = await withTimeout( - replyDeferred!.promise, - replyTimeoutMs, - `send reply ${requestId}`); - packetLog.trace(() => [ - 'packet_recv serviceCmd=%j requestId=%d error=%d message=%j length=%d body=%s', - cmd, - requestId, - reply.error, - reply.message, - reply.body.length, - renderTraceBytes(reply.body), - ]); - packetLog.trace(() => [ - 'packet_terminal serviceCmd=%j requestId=%d outcome=%s reason=%s error=%d elapsedMs=%d', - cmd, - requestId, - reply.error === 0 ? 'ok' : 'failed', - reply.error === 0 ? 'reply_received' : 'reply_error', - reply.error, - Date.now() - startedAt, - ]); - return reply; - } catch (error) { - this.pendingAcks.delete(requestId); - this.pendingReplies.delete(requestId); - const reason = packetFailureReason(error, requestId); - packetLog.trace(() => [ - 'packet_terminal serviceCmd=%j requestId=%d outcome=%s reason=%s error=%j elapsedMs=%d', - cmd, - requestId, - reason.endsWith('_timeout') ? 'timeout' : 'failed', - reason, - error instanceof Error ? error.message : String(error), - Date.now() - startedAt, - ]); - throw error; + get isLoggedIn(): boolean { + return this.loginState.loggedIn; } - } - async sendNoReply(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit = {}): Promise<{ requestId: number }> { - return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{ requestId: number }>; - } + get isClosed(): boolean { + return this.closed; + } - async sendAndWait(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit = {}): Promise { - return this.send(cmd, body, { ...options, wantReply: true }) as Promise; - } + get currentUin(): string { + return this.loginState.uin; + } - async sendMany(items: Array<{ cmd: string; body?: Buffer | Uint8Array | string | null; wantReply?: boolean; ackTimeoutMs?: number; replyTimeoutMs?: number }>, { - concurrency = 64, - wantReply = true, - ackTimeoutMs = this.defaultAckTimeoutMs, - replyTimeoutMs = this.defaultReplyTimeoutMs, - }: QqHookSendOptions & { concurrency?: number } = {}): Promise> { - const results = new Array(items.length); - let nextIndex = 0; - const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1)); + get currentUinNumber(): bigint { + return this.loginState.uinNumber; + } - const worker = async () => { - for (; ;) { - const index = nextIndex; - nextIndex += 1; - if (index >= items.length) return; - const item = items[index]; - const itemWantReply = item.wantReply ?? wantReply; - results[index] = await this.send(item.cmd, item.body, { - wantReply: itemWantReply, - ackTimeoutMs: item.ackTimeoutMs ?? ackTimeoutMs, - replyTimeoutMs: item.replyTimeoutMs ?? replyTimeoutMs, - }); - } - }; + getLoginState(): QqHookLoginState { + return { ...this.loginState }; + } - await Promise.all(Array.from({ length: workerCount }, () => worker())); - return results; - } - - waitForPacket(predicate: (packet: QqHookPacket) => boolean = () => true, { timeoutMs = 0 } = {}): Promise { - return new Promise((resolve, reject) => { - let timer: NodeJS.Timeout | null = null; - const cleanup = () => { - this.off('packet', onPacket); - if (timer) { - clearTimeout(timer); - timer = null; + /** + * Forward an observed account identity for reconciliation. This does not + * change login state; readiness still requires peer confirmation. + */ + async reconcileLoginIdentity(uin: string): Promise { + if (!isRealUin(uin)) { + throw new Error(`invalid QQ login identity hint: ${JSON.stringify(uin)}`); } - }; - const onPacket = (packet: QqHookPacket) => { + + await this.sendAckOnly(PipeOp.loginIdentityHint, BigInt(uin), 'login identity hint'); + } + + async waitForLogin({ timeoutMs = 0 } = {}): Promise { + await this.connect(); + + if (this.loginState.loggedIn) { + return this.getLoginState(); + } + + const deferred = createDeferred(); + this.loginWaiters.push(deferred); + return withTimeout(deferred.promise, timeoutMs, 'waitForLogin'); + } + + static controlPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string { + return mojoPipeName(pid, 'control', runtimeDir); + } + + static recvPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string { + return mojoPipeName(pid, 'recv', runtimeDir); + } + + /** + * Lightweight liveness check for the control pipe. Used to detect whether an + * existing SnowLuma hook is still hosted inside the QQ.exe process without + * opening the pipe, so probing cannot disturb the first real client connect. + */ + static async probePipe(pid: number): Promise { + const live = await QqHookClient.listLivePipes([pid]); + return live.has(pid); + } + + /** + * Enumerate every PID currently hosting a SnowLuma `mojo..control` pipe + * in a single filesystem listing. The HookManager's pipe-watcher uses this + * to drive connect/reconnect decisions without per-PID stat calls. + */ + static async listLivePipes(pids: readonly number[] = []): Promise> { + const result = new Set(); + + if (process.platform === 'win32') { + const names = await fs.readdir('\\\\.\\pipe\\'); + + for (const name of names) { + const m = /^mojo\.(\d+)\.control$/i.exec(name); + + if (m) { + result.add(Number(m[1])); + } + } + } else { + const runtimeDirs = new Set(); + + if (pids.length === 0) { + runtimeDirs.add(resolveHookRuntimeDir()); + } else { + for (const pid of pids) { + runtimeDirs.add(resolveHookRuntimeDir(pid)); + } + } + + for (const runtimeDir of runtimeDirs) { + for (const pid of await listLiveLinuxPipePids(runtimeDir)) { + result.add(pid); + } + } + } + + return result; + } + + async connect(): Promise { + if (this.closed) { + throw new Error('qq_hook client is closed'); + } + + if (this.controlSocket && this.controlHello) { + return this.controlHello; + } + + if (this.controlConnectPromise) { + return this.controlConnectPromise; + } + + this.controlConnectPromise = this.connectPipe('control'); + try { - if (!predicate(packet)) return; - cleanup(); - resolve(packet); - } catch (error) { - cleanup(); - reject(error); + return await this.controlConnectPromise; + } finally { + this.controlConnectPromise = null; } - }; - this.on('packet', onPacket); - if (timeoutMs > 0) { - timer = setTimeout(() => { - cleanup(); - reject(new Error(`recv packet timed out after ${timeoutMs} ms`)); - }, timeoutMs); - } - }); - } - - close(): void { - if (this.closed) return; - this.closed = true; - this.rejectControlPending(new Error('qq_hook client closed')); - this.rejectRecvPending(new Error('qq_hook client closed')); - this.rejectLoginWaiters(new Error('qq_hook client closed')); - - if (this.controlSocket) { - this.controlSocket.destroy(); - this.controlSocket = null; } - if (this.recvSocket) { - this.recvSocket.destroy(); - this.recvSocket = null; - } - this.controlHello = null; - this.recvHello = null; - this.controlWriteChain = Promise.resolve(); - } - private rejectLoginWaiters(error: Error): void { - const waiters = this.loginWaiters; - this.loginWaiters = []; - for (const waiter of waiters) waiter.reject(error); - } + async startRecv(onPacket?: (packet: QqHookPacket) => void): Promise { + if (this.closed) { + throw new Error('qq_hook client is closed'); + } - private rejectControlPending(error: Error): void { - for (const pending of this.pendingAcks.values()) { - pending.reject(error); - } - for (const pending of this.pendingReplies.values()) { - pending.reject(error); - } - this.pendingAcks.clear(); - this.pendingReplies.clear(); - if (this.controlHelloResolver) { - this.controlHelloResolver.reject(error); - this.controlHelloResolver = null; - } - } + if (typeof onPacket === 'function') { + this.on('packet', onPacket); + } - private rejectRecvPending(error: Error): void { - if (this.recvHelloResolver) { - this.recvHelloResolver.reject(error); - this.recvHelloResolver = null; - } - } + if (this.recvSocket && this.recvHello) { + return this.recvHello; + } - private writeControl(payload: Buffer): Promise { - const socket = this.controlSocket; - if (!socket || socket.destroyed) { - return Promise.reject(new Error('control pipe is not connected')); - } - const writePromise = this.controlWriteChain.then(() => new Promise((resolve, reject) => { - if (!this.controlSocket || this.controlSocket.destroyed) { - reject(new Error('control pipe is not connected')); - return; - } - socket.write(payload, error => { - if (error) reject(error); - else resolve(); - }); - })); - this.controlWriteChain = writePromise.catch(() => { }); - return writePromise; - } + if (this.recvConnectPromise) { + return this.recvConnectPromise; + } - private allocateRequestId(): number { - // Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would lose - // precision past Number.MAX_SAFE_INTEGER. Zero remains the wire sentinel. - let requestId = this.nextRequestId; - while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) { - requestId = (requestId + 1) >>> 0; - if (requestId === 0) requestId = 1; - } - this.nextRequestId = (requestId + 1) >>> 0; - if (this.nextRequestId === 0) this.nextRequestId = 1; - return requestId; - } + this.recvConnectPromise = this.connectPipe('recv'); - private async sendAckOnly(op: PipeOp, value0: bigint, label: string): Promise { - await this.connect(); - const requestId = this.allocateRequestId(); - const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>(); - ackDeferred.promise.catch(() => { /* observed by the await below */ }); - this.pendingAcks.set(requestId, { - resolve: ackDeferred.resolve, - reject: ackDeferred.reject, - wantReply: false, - }); - try { - await this.writeControl(encodeFrame({ op, requestId, value0 })); - await withTimeout( - ackDeferred.promise, - this.defaultAckTimeoutMs, - `${label} ack ${requestId}`, - ); - return requestId; - } catch (error) { - this.pendingAcks.delete(requestId); - throw error; + try { + return await this.recvConnectPromise; + } finally { + this.recvConnectPromise = null; + } } - } - private async connectPipe(kind: 'control' | 'recv'): Promise { - return runWithTraceRequest(async () => { - const startedAt = Date.now(); - const pipeName = kind === 'control' - ? QqHookClient.controlPipeName(this.pid, this.runtimeDir) - : QqHookClient.recvPipeName(this.pid, this.runtimeDir); - let phase: 'connect' | 'hello' = 'connect'; - runtimeLog.trace( - 'hook_pipe_start pid=%d kind=%s pipeName=%j', - this.pid, - kind, - pipeName, - ); - try { - const socket = await runWithoutRequestContext(() => this.connectSocket( - pipeName, - kind, - kind === 'control' - ? frame => this.handleControlFrame(frame) - : frame => this.handleRecvFrame(frame), - )); - if (kind === 'control') this.controlSocket = socket; - else this.recvSocket = socket; - runtimeLog.trace( - 'hook_pipe_branch pid=%d kind=%s branch=socket_connected', - this.pid, - kind, - ); - phase = 'hello'; - const hello = await this.waitForHello(kind === 'recv'); - if (kind === 'control') this.controlHello = hello; - else this.recvHello = hello; - runtimeLog.trace(() => [ - 'hook_pipe_terminal pid=%d kind=%s outcome=completed reason=hello_received hello=%s elapsedMs=%d', - this.pid, - kind, - renderParamsVerbose(hello), - Date.now() - startedAt, + async connectAll({ recv = true } = {}): Promise<{ + control: QqHookHello; + recv: QqHookHello | null; + }> { + const control = await this.connect(); + const recvInfo = recv ? await this.startRecv() : null; + return { control, recv: recvInfo }; + } + + async send( + cmd: string, + body: Buffer | Uint8Array | string | null | undefined, + { + wantReply = true, + ackTimeoutMs = this.defaultAckTimeoutMs, + replyTimeoutMs = this.defaultReplyTimeoutMs, + }: QqHookSendOptions = {}, + ): Promise { + await this.connect(); + + const requestId = this.allocateRequestId(); + const startedAt = Date.now(); + const bodyBytes = toBuffer(body); + const payload = encodeFrame({ + op: PipeOp.sendRequest, + requestId, + flags: wantReply ? PipeFlagWantReply : 0, + cmd, + body: bodyBytes, + }); + packetLog.trace(() => [ + 'packet_send serviceCmd=%j requestId=%d length=%d body=%s', + cmd, + requestId, + bodyBytes.length, + renderTraceBytes(bodyBytes), ]); - return hello; - } catch (error) { - runtimeLog.trace(() => [ - 'hook_pipe_terminal pid=%d kind=%s outcome=failed reason=%s error=%j elapsedMs=%d', - this.pid, - kind, - phase === 'connect' ? 'connect_failed' : 'hello_failed', - error instanceof Error ? error.message : String(error), - Date.now() - startedAt, - ]); - throw error; - } - }); - } - private connectSocket(pipeName: string, kind: 'control' | 'recv', onFrame: (frame: PipeFrame) => void): Promise { - return new Promise((resolve, reject) => { - const socket = net.createConnection(pipeName); - const reader = new FrameReader(onFrame); - const onInitialError = (error: Error) => reject(error); - socket.once('error', onInitialError); - socket.once('connect', () => { - socket.off('error', onInitialError); - socket.on('data', chunk => { - try { - reader.push(chunk); - } catch (error) { - this.emit('error', error); - socket.destroy(); - } + const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>(); + // Always attach a handler so a rejection can never become "unhandled" (which + // crashes Node). When the pipe closes, rejectControlPending() rejects every + // pending deferred — but the reply is only `await`ed AFTER the ack, so if the + // ack fails first the reply promise is rejected with NO awaiter. The real + // `await` below still observes the value/rejection (a separate continuation). + ackDeferred.promise.catch(() => { + /* observed by the await, or harmless */ }); - socket.on('error', error => { - this.emit('error', error); + this.pendingAcks.set(requestId, { + resolve: ackDeferred.resolve, + reject: ackDeferred.reject, + wantReply, }); - socket.on('close', () => { - runWithTraceRequest(() => { - this.handleSocketClose(kind); - this.emit('close', kind); - }); + + let replyDeferred: Deferred | null = null; + + if (wantReply) { + replyDeferred = createDeferred(); + replyDeferred.promise.catch(() => { + /* see note above — prevents unhandled rejection */ + }); + this.pendingReplies.set(requestId, replyDeferred); + } + + try { + await this.writeControl(payload); + await withTimeout(ackDeferred.promise, ackTimeoutMs, `send ack ${requestId}`); + + if (!wantReply) { + packetLog.trace(() => [ + 'packet_terminal serviceCmd=%j requestId=%d outcome=ok reason=ack_received elapsedMs=%d', + cmd, + requestId, + Date.now() - startedAt, + ]); + return { requestId }; + } + + const reply = await withTimeout( + replyDeferred!.promise, + replyTimeoutMs, + `send reply ${requestId}`, + ); + packetLog.trace(() => [ + 'packet_recv serviceCmd=%j requestId=%d error=%d message=%j length=%d body=%s', + cmd, + requestId, + reply.error, + reply.message, + reply.body.length, + renderTraceBytes(reply.body), + ]); + packetLog.trace(() => [ + 'packet_terminal serviceCmd=%j requestId=%d outcome=%s reason=%s error=%d elapsedMs=%d', + cmd, + requestId, + reply.error === 0 ? 'ok' : 'failed', + reply.error === 0 ? 'reply_received' : 'reply_error', + reply.error, + Date.now() - startedAt, + ]); + return reply; + } catch (error) { + this.pendingAcks.delete(requestId); + this.pendingReplies.delete(requestId); + const reason = packetFailureReason(error, requestId); + packetLog.trace(() => [ + 'packet_terminal serviceCmd=%j requestId=%d outcome=%s reason=%s error=%j elapsedMs=%d', + cmd, + requestId, + reason.endsWith('_timeout') ? 'timeout' : 'failed', + reason, + error instanceof Error ? error.message : String(error), + Date.now() - startedAt, + ]); + throw error; + } + } + + async sendNoReply( + cmd: string, + body: Buffer | Uint8Array | string | null | undefined, + options: Omit = {}, + ): Promise<{ requestId: number }> { + return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{ + requestId: number; + }>; + } + + async sendAndWait( + cmd: string, + body: Buffer | Uint8Array | string | null | undefined, + options: Omit = {}, + ): Promise { + return this.send(cmd, body, { ...options, wantReply: true }) as Promise; + } + + async sendMany( + items: Array<{ + cmd: string; + body?: Buffer | Uint8Array | string | null; + wantReply?: boolean; + ackTimeoutMs?: number; + replyTimeoutMs?: number; + }>, + { + concurrency = 64, + wantReply = true, + ackTimeoutMs = this.defaultAckTimeoutMs, + replyTimeoutMs = this.defaultReplyTimeoutMs, + }: QqHookSendOptions & { concurrency?: number } = {}, + ): Promise> { + const results = new Array(items.length); + let nextIndex = 0; + const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1)); + + const worker = async () => { + for (;;) { + const index = nextIndex; + nextIndex += 1; + + if (index >= items.length) { + return; + } + + const item = items[index]; + const itemWantReply = item.wantReply ?? wantReply; + results[index] = await this.send(item.cmd, item.body, { + wantReply: itemWantReply, + ackTimeoutMs: item.ackTimeoutMs ?? ackTimeoutMs, + replyTimeoutMs: item.replyTimeoutMs ?? replyTimeoutMs, + }); + } + }; + + await Promise.all(Array.from({ length: workerCount }, () => worker())); + return results; + } + + waitForPacket( + predicate: (packet: QqHookPacket) => boolean = () => true, + { timeoutMs = 0 } = {}, + ): Promise { + return new Promise((resolve, reject) => { + let timer: NodeJS.Timeout | null = null; + + const cleanup = () => { + this.off('packet', onPacket); + + if (timer) { + clearTimeout(timer); + timer = null; + } + }; + + const onPacket = (packet: QqHookPacket) => { + try { + if (!predicate(packet)) { + return; + } + + cleanup(); + resolve(packet); + } catch (error) { + cleanup(); + reject(error); + } + }; + + this.on('packet', onPacket); + + if (timeoutMs > 0) { + timer = setTimeout(() => { + cleanup(); + reject(new Error(`recv packet timed out after ${timeoutMs} ms`)); + }, timeoutMs); + } }); - resolve(socket); - }); - }); - } - - private waitForHello(recvPipe: boolean): Promise { - const deferred = createDeferred(); - if (recvPipe) { - this.recvHelloResolver = deferred; - } else { - this.controlHelloResolver = deferred; } - return deferred.promise; - } - private resolveHello(frame: PipeFrame, recvPipe: boolean): void { - const resolver = recvPipe ? this.recvHelloResolver : this.controlHelloResolver; - if (!resolver) return; - if (recvPipe) this.recvHelloResolver = null; - else this.controlHelloResolver = null; - resolver.resolve({ - pipeName: frame.msg, - pid: Number(frame.value0), - recvPipe, - }); - } + close(): void { + if (this.closed) { + return; + } - private handleSocketClose(kind: 'control' | 'recv'): void { - runtimeLog.trace( - 'hook_runtime_fact pid=%d event=pipe_closed kind=%s loggedIn=%s uin=%j', - this.pid, - kind, - this.loginState.loggedIn, - this.loginState.uin, - ); - if (kind === 'control') { - this.controlSocket = null; - this.controlHello = null; - this.rejectControlPending(new Error('control pipe closed')); - return; + this.closed = true; + this.rejectControlPending(new Error('qq_hook client closed')); + this.rejectRecvPending(new Error('qq_hook client closed')); + this.rejectLoginWaiters(new Error('qq_hook client closed')); + + if (this.controlSocket) { + this.controlSocket.destroy(); + this.controlSocket = null; + } + + if (this.recvSocket) { + this.recvSocket.destroy(); + this.recvSocket = null; + } + + this.controlHello = null; + this.recvHello = null; + this.controlWriteChain = Promise.resolve(); } - this.recvSocket = null; - this.recvHello = null; - this.rejectRecvPending(new Error('recv pipe closed')); - } - private applyLoginStateFrame(frame: PipeFrame): void { - const flaggedLoggedIn = (frame.flags & PipeFlagLoggedIn) !== 0; - const statusLoggedIn = frame.status !== 0; - const loggedIn = flaggedLoggedIn || statusLoggedIn; - const uinNumber = BigInt(frame.value0); - const uin = frame.msg || uinNumber.toString(); - this.applyLoginState({ loggedIn, uin, uinNumber }); - } - - private applyLoginState(next: QqHookLoginState): void { - const previous = this.loginState; - this.loginState = next; - if (previous.loggedIn === next.loggedIn && previous.uin === next.uin) { - this.emit('loginState', next); - return; - } - runWithTraceRequest(() => { - runtimeLog.trace( - 'hook_runtime_fact pid=%d event=login_state_changed previousLoggedIn=%s previousUin=%j loggedIn=%s uin=%j', - this.pid, - previous.loggedIn, - previous.uin, - next.loggedIn, - next.uin, - ); - this.emit('loginState', next); - if (next.loggedIn) { + private rejectLoginWaiters(error: Error): void { const waiters = this.loginWaiters; this.loginWaiters = []; - for (const waiter of waiters) waiter.resolve({ ...next }); - } - }); - } - private handleControlFrame(frame: PipeFrame): void { - if (frame.op === PipeOp.hello) { - this.resolveHello(frame, false); - return; + for (const waiter of waiters) { + waiter.reject(error); + } } - if (frame.op === PipeOp.loginState) { - this.applyLoginStateFrame(frame); - return; - } - if (frame.op === PipeOp.sendAck) { - const pending = this.pendingAcks.get(frame.requestId); - if (!pending) return; - this.pendingAcks.delete(frame.requestId); - pending.resolve({ requestId: frame.requestId, wantReply: pending.wantReply }); - return; - } - if (frame.op === PipeOp.sendReply) { - const pending = this.pendingReplies.get(frame.requestId); - if (!pending) return; - this.pendingReplies.delete(frame.requestId); - pending.resolve({ - requestId: frame.requestId, - error: frame.status, - message: frame.msg, - body: Buffer.from(frame.body), - }); - return; - } - if (frame.op === PipeOp.error) { - const error = new HookPipeRequestError( - frame.msg || `pipe error ${frame.status}`, - frame.status, - frame.requestId, - ); - const ack = this.pendingAcks.get(frame.requestId); - if (ack) { - this.pendingAcks.delete(frame.requestId); - ack.reject(error); - } - const reply = this.pendingReplies.get(frame.requestId); - if (reply) { - this.pendingReplies.delete(frame.requestId); - reply.reject(error); - } - } - } - private handleRecvFrame(frame: PipeFrame): void { - if (frame.op === PipeOp.hello) { - this.resolveHello(frame, true); - return; + private rejectControlPending(error: Error): void { + for (const pending of this.pendingAcks.values()) { + pending.reject(error); + } + + for (const pending of this.pendingReplies.values()) { + pending.reject(error); + } + + this.pendingAcks.clear(); + this.pendingReplies.clear(); + + if (this.controlHelloResolver) { + this.controlHelloResolver.reject(error); + this.controlHelloResolver = null; + } } - if (frame.op === PipeOp.loginState) { - this.applyLoginStateFrame(frame); - return; + + private rejectRecvPending(error: Error): void { + if (this.recvHelloResolver) { + this.recvHelloResolver.reject(error); + this.recvHelloResolver = null; + } + } + + private writeControl(payload: Buffer): Promise { + const socket = this.controlSocket; + + if (!socket || socket.destroyed) { + return Promise.reject(new Error('control pipe is not connected')); + } + + const writePromise = this.controlWriteChain.then( + () => + new Promise((resolve, reject) => { + if (!this.controlSocket || this.controlSocket.destroyed) { + reject(new Error('control pipe is not connected')); + return; + } + + socket.write(payload, (error) => { + if (error) { + reject(error); + } else { + resolve(); + } + }); + }), + ); + this.controlWriteChain = writePromise.catch(() => {}); + return writePromise; + } + + private allocateRequestId(): number { + // Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would lose + // precision past Number.MAX_SAFE_INTEGER. Zero remains the wire sentinel. + let requestId = this.nextRequestId; + + while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) { + requestId = (requestId + 1) >>> 0; + + if (requestId === 0) { + requestId = 1; + } + } + + this.nextRequestId = (requestId + 1) >>> 0; + + if (this.nextRequestId === 0) { + this.nextRequestId = 1; + } + + return requestId; + } + + private async sendAckOnly(op: PipeOp, value0: bigint, label: string): Promise { + await this.connect(); + const requestId = this.allocateRequestId(); + const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>(); + ackDeferred.promise.catch(() => { + /* observed by the await below */ + }); + this.pendingAcks.set(requestId, { + resolve: ackDeferred.resolve, + reject: ackDeferred.reject, + wantReply: false, + }); + + try { + await this.writeControl(encodeFrame({ op, requestId, value0 })); + await withTimeout( + ackDeferred.promise, + this.defaultAckTimeoutMs, + `${label} ack ${requestId}`, + ); + return requestId; + } catch (error) { + this.pendingAcks.delete(requestId); + throw error; + } + } + + private async connectPipe(kind: 'control' | 'recv'): Promise { + return runWithTraceRequest(async () => { + const startedAt = Date.now(); + const pipeName = + kind === 'control' + ? QqHookClient.controlPipeName(this.pid, this.runtimeDir) + : QqHookClient.recvPipeName(this.pid, this.runtimeDir); + let phase: 'connect' | 'hello' = 'connect'; + runtimeLog.trace( + 'hook_pipe_start pid=%d kind=%s pipeName=%j', + this.pid, + kind, + pipeName, + ); + + try { + const socket = await runWithoutRequestContext(() => + this.connectSocket( + pipeName, + kind, + kind === 'control' + ? (frame) => this.handleControlFrame(frame) + : (frame) => this.handleRecvFrame(frame), + ), + ); + + if (kind === 'control') { + this.controlSocket = socket; + } else { + this.recvSocket = socket; + } + + runtimeLog.trace( + 'hook_pipe_branch pid=%d kind=%s branch=socket_connected', + this.pid, + kind, + ); + phase = 'hello'; + const hello = await this.waitForHello(kind === 'recv'); + + if (kind === 'control') { + this.controlHello = hello; + } else { + this.recvHello = hello; + } + + runtimeLog.trace(() => [ + 'hook_pipe_terminal pid=%d kind=%s outcome=completed reason=hello_received hello=%s elapsedMs=%d', + this.pid, + kind, + renderParamsVerbose(hello), + Date.now() - startedAt, + ]); + return hello; + } catch (error) { + runtimeLog.trace(() => [ + 'hook_pipe_terminal pid=%d kind=%s outcome=failed reason=%s error=%j elapsedMs=%d', + this.pid, + kind, + phase === 'connect' ? 'connect_failed' : 'hello_failed', + error instanceof Error ? error.message : String(error), + Date.now() - startedAt, + ]); + throw error; + } + }); + } + + private connectSocket( + pipeName: string, + kind: 'control' | 'recv', + onFrame: (frame: PipeFrame) => void, + ): Promise { + return new Promise((resolve, reject) => { + const socket = net.createConnection(pipeName); + const reader = new FrameReader(onFrame); + const onInitialError = (error: Error) => reject(error); + socket.once('error', onInitialError); + socket.once('connect', () => { + socket.off('error', onInitialError); + socket.on('data', (chunk) => { + try { + reader.push(chunk); + } catch (error) { + this.emit('error', error); + socket.destroy(); + } + }); + socket.on('error', (error) => { + this.emit('error', error); + }); + socket.on('close', () => { + runWithTraceRequest(() => { + this.handleSocketClose(kind); + this.emit('close', kind); + }); + }); + resolve(socket); + }); + }); + } + + private waitForHello(recvPipe: boolean): Promise { + const deferred = createDeferred(); + + if (recvPipe) { + this.recvHelloResolver = deferred; + } else { + this.controlHelloResolver = deferred; + } + + return deferred.promise; + } + + private resolveHello(frame: PipeFrame, recvPipe: boolean): void { + const resolver = recvPipe ? this.recvHelloResolver : this.controlHelloResolver; + + if (!resolver) { + return; + } + + if (recvPipe) { + this.recvHelloResolver = null; + } else { + this.controlHelloResolver = null; + } + + resolver.resolve({ + pipeName: frame.msg, + pid: Number(frame.value0), + recvPipe, + }); + } + + private handleSocketClose(kind: 'control' | 'recv'): void { + runtimeLog.trace( + 'hook_runtime_fact pid=%d event=pipe_closed kind=%s loggedIn=%s uin=%j', + this.pid, + kind, + this.loginState.loggedIn, + this.loginState.uin, + ); + + if (kind === 'control') { + this.controlSocket = null; + this.controlHello = null; + this.rejectControlPending(new Error('control pipe closed')); + return; + } + + this.recvSocket = null; + this.recvHello = null; + this.rejectRecvPending(new Error('recv pipe closed')); + } + + private applyLoginStateFrame(frame: PipeFrame): void { + const flaggedLoggedIn = (frame.flags & PipeFlagLoggedIn) !== 0; + const statusLoggedIn = frame.status !== 0; + const loggedIn = flaggedLoggedIn || statusLoggedIn; + const uinNumber = BigInt(frame.value0); + const uin = frame.msg || uinNumber.toString(); + this.applyLoginState({ loggedIn, uin, uinNumber }); + } + + private applyLoginState(next: QqHookLoginState): void { + const previous = this.loginState; + this.loginState = next; + + if (previous.loggedIn === next.loggedIn && previous.uin === next.uin) { + this.emit('loginState', next); + return; + } + + runWithTraceRequest(() => { + runtimeLog.trace( + 'hook_runtime_fact pid=%d event=login_state_changed previousLoggedIn=%s previousUin=%j loggedIn=%s uin=%j', + this.pid, + previous.loggedIn, + previous.uin, + next.loggedIn, + next.uin, + ); + this.emit('loginState', next); + + if (next.loggedIn) { + const waiters = this.loginWaiters; + this.loginWaiters = []; + + for (const waiter of waiters) { + waiter.resolve({ ...next }); + } + } + }); + } + + private handleControlFrame(frame: PipeFrame): void { + if (frame.op === PipeOp.hello) { + this.resolveHello(frame, false); + return; + } + + if (frame.op === PipeOp.loginState) { + this.applyLoginStateFrame(frame); + return; + } + + if (frame.op === PipeOp.sendAck) { + const pending = this.pendingAcks.get(frame.requestId); + + if (!pending) { + return; + } + + this.pendingAcks.delete(frame.requestId); + pending.resolve({ requestId: frame.requestId, wantReply: pending.wantReply }); + return; + } + + if (frame.op === PipeOp.sendReply) { + const pending = this.pendingReplies.get(frame.requestId); + + if (!pending) { + return; + } + + this.pendingReplies.delete(frame.requestId); + pending.resolve({ + requestId: frame.requestId, + error: frame.status, + message: frame.msg, + body: Buffer.from(frame.body), + }); + return; + } + + if (frame.op === PipeOp.error) { + const error = new HookPipeRequestError( + frame.msg || `pipe error ${frame.status}`, + frame.status, + frame.requestId, + ); + const ack = this.pendingAcks.get(frame.requestId); + + if (ack) { + this.pendingAcks.delete(frame.requestId); + ack.reject(error); + } + + const reply = this.pendingReplies.get(frame.requestId); + + if (reply) { + this.pendingReplies.delete(frame.requestId); + reply.reject(error); + } + } + } + + private handleRecvFrame(frame: PipeFrame): void { + if (frame.op === PipeOp.hello) { + this.resolveHello(frame, true); + return; + } + + if (frame.op === PipeOp.loginState) { + this.applyLoginStateFrame(frame); + return; + } + + if (frame.op !== PipeOp.recvPacket) { + return; + } + + this.emit('packet', { + seq: Number(frame.value0), + error: frame.status, + cmd: frame.cmd, + uin: frame.msg, + body: Buffer.from(frame.body), + } satisfies QqHookPacket); } - if (frame.op !== PipeOp.recvPacket) return; - this.emit('packet', { - seq: Number(frame.value0), - error: frame.status, - cmd: frame.cmd, - uin: frame.msg, - body: Buffer.from(frame.body), - } satisfies QqHookPacket); - } } export { mojoPipeName }; diff --git a/packages/bridge/src/qq-port-probe.ts b/packages/bridge/src/qq-port-probe.ts index 76e62fac..cd6afe41 100644 --- a/packages/bridge/src/qq-port-probe.ts +++ b/packages/bridge/src/qq-port-probe.ts @@ -9,11 +9,15 @@ const log = createLogger('LoginProbe'); const probeNotes = new Map(); function noteProbe(pid: number, result: string, ports: number, processes: number | null): void { - const processText = processes === null ? '' : ` processes=${processes}`; - const message = `login probe: PID=${pid} result=${result} ports=${ports}${processText}`; - if (probeNotes.get(pid) === message) return; - probeNotes.set(pid, message); - log.info(message); + const processText = processes === null ? '' : ` processes=${processes}`; + const message = `login probe: PID=${pid} result=${result} ports=${ports}${processText}`; + + if (probeNotes.get(pid) === message) { + return; + } + + probeNotes.set(pid, message); + log.info(message); } const CONNECTION_TIMEOUT_MS = 500; @@ -29,21 +33,21 @@ const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as con const LOGGED_OUT_PROCESS_COUNT_MAX = 6; export interface QqPortLoginInfo { - port: number; - uin: string; - uid?: string; - nickName?: string; - /** The local QQ endpoint exposed an account identity. This does not prove - * the native protocol session is ready to send or receive packets. */ - identityKnown: boolean; + port: number; + uin: string; + uid?: string; + nickName?: string; + /** The local QQ endpoint exposed an account identity. This does not prove + * the native protocol session is ready to send or receive packets. */ + identityKnown: boolean; } /** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the * probe reads are modelled; QQ sends more but they're irrelevant here. */ interface PtloginUin { - uin?: string | number; - account?: string | number; - nickname?: string; + uin?: string | number; + account?: string | number; + nickname?: string; } /** @@ -55,192 +59,236 @@ interface PtloginUin { * problem, no answer" and should fall through to the deep-link fallback. */ async function fetchPtlogin(port: number, useHttps: boolean): Promise { - return new Promise((resolve) => { - const protocol = useHttps ? 'https' : 'http'; - const url = `${protocol}://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`; + return new Promise((resolve) => { + const protocol = useHttps ? 'https' : 'http'; + const url = `${protocol}://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`; - const headers = { - Host: 'localhost.ptlogin2.qq.com', - Referer: 'https://xui.ptlogin2.qq.com/', - Cookie: 'pt_local_token=0', - }; + const headers = { + Host: 'localhost.ptlogin2.qq.com', + Referer: 'https://xui.ptlogin2.qq.com/', + Cookie: 'pt_local_token=0', + }; - const handleResponse = (res: http.IncomingMessage) => { - let text = ''; - res.on('data', (chunk) => { text += chunk.toString(); }); - res.on('end', () => { - try { - const inner = text.split('[')[1].split(']')[0]; - const data = JSON.parse('[' + inner + ']') as PtloginUin[]; - resolve(data); - } catch { - resolve(null); - } - }); - }; + const handleResponse = (res: http.IncomingMessage) => { + let text = ''; + res.on('data', (chunk) => { + text += chunk.toString(); + }); + res.on('end', () => { + try { + const inner = text.split('[')[1].split(']')[0]; + const data = JSON.parse('[' + inner + ']') as PtloginUin[]; + resolve(data); + } catch { + resolve(null); + } + }); + }; - const req = useHttps - ? https.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false }, handleResponse) - : http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse); + const req = useHttps + ? https.get( + url, + { headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false }, + handleResponse, + ) + : http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse); - req.on('error', () => resolve(null)); - req.on('timeout', () => { - req.destroy(); - resolve(null); + req.on('error', () => resolve(null)); + req.on('timeout', () => { + req.destroy(); + resolve(null); + }); }); - }); } async function tryPtloginMethod(port: number): Promise { - const useHttps = port % 2 !== 0; + const useHttps = port % 2 !== 0; - const res1 = await fetchPtlogin(port, useHttps); - const res2 = await fetchPtlogin(port, useHttps); + const res1 = await fetchPtlogin(port, useHttps); + const res2 = await fetchPtlogin(port, useHttps); - if (res1 === null && res2 === null) return 'fallback'; + if (res1 === null && res2 === null) { + return 'fallback'; + } - const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null); - const target = usable.reduce((a, b) => (a.length <= b.length ? a : b)); + const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null); + const target = usable.reduce((a, b) => (a.length <= b.length ? a : b)); - if (target.length === 1) { - const account = target[0]; - return { - port, - uin: String(account.uin || account.account || ''), - nickName: account.nickname || '', - identityKnown: true, - }; - } + if (target.length === 1) { + const account = target[0]; + return { + port, + uin: String(account.uin || account.account || ''), + nickName: account.nickname || '', + identityKnown: true, + }; + } - return 'fallback'; + return 'fallback'; } - async function getQqProcessCount(): Promise { - try { - if (process.platform === 'win32') { - const { stdout } = await execAsync( - 'tasklist /fi "imagename eq QQ.exe" /nh', - EXEC_OPTIONS, - ); - return stdout.toLowerCase().split('\n').filter(line => line.includes('qq.exe')).length; - } else { - const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS); - return parseInt(stdout.trim(), 10) || 0; + try { + if (process.platform === 'win32') { + const { stdout } = await execAsync( + 'tasklist /fi "imagename eq QQ.exe" /nh', + EXEC_OPTIONS, + ); + return stdout + .toLowerCase() + .split('\n') + .filter((line) => line.includes('qq.exe')).length; + } else { + const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS); + return parseInt(stdout.trim(), 10) || 0; + } + } catch { + // On failure report the ambiguous threshold so we never falsely + // conclude "logged out". + return LOGGED_OUT_PROCESS_COUNT_MAX; } - } catch { - // On failure report the ambiguous threshold so we never falsely - // conclude "logged out". - return LOGGED_OUT_PROCESS_COUNT_MAX; - } } async function getProcessPorts(pid: number): Promise { - try { - if (process.platform === 'win32') { - const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS); - const ports = new Set(); - const lines = stdout.split('\n'); - for (const line of lines) { - const parts = line.trim().split(/\s+/); - if (parts.length < 5) continue; - const owningPid = parts[parts.length - 1]; - if (owningPid !== String(pid)) continue; + try { + if (process.platform === 'win32') { + const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS); + const ports = new Set(); + const lines = stdout.split('\n'); - const localAddr = parts[1]; - const portMatch = localAddr.match(/:(\d+)$/); - if (!portMatch) continue; - ports.add(Number(portMatch[1])); - } - return Array.from(ports); - } else { - const { stdout } = await execAsync('ss -tlnp', EXEC_OPTIONS); - const ports = new Set(); - const lines = stdout.split('\n'); - for (const line of lines) { - if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) continue; - const match = line.match(/:(\d+)\s/); - if (match) { - ports.add(Number(match[1])); + for (const line of lines) { + const parts = line.trim().split(/\s+/); + + if (parts.length < 5) { + continue; + } + + const owningPid = parts[parts.length - 1]; + + if (owningPid !== String(pid)) { + continue; + } + + const localAddr = parts[1]; + const portMatch = localAddr.match(/:(\d+)$/); + + if (!portMatch) { + continue; + } + + ports.add(Number(portMatch[1])); + } + + return Array.from(ports); + } else { + const { stdout } = await execAsync('ss -tlnp', EXEC_OPTIONS); + const ports = new Set(); + const lines = stdout.split('\n'); + + for (const line of lines) { + if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) { + continue; + } + + const match = line.match(/:(\d+)\s/); + + if (match) { + ports.add(Number(match[1])); + } + } + + return Array.from(ports); } - } - return Array.from(ports); + } catch { + return null; } - } catch { - return null; - } } async function probeQqLoginInfoInternal(pid: number): Promise { - const ports = await getProcessPorts(pid); - if (ports === null) { - noteProbe(pid, 'unavailable', 0, null); - return null; - } + const ports = await getProcessPorts(pid); - if (ports.length === 0) { - const totalPids = await getQqProcessCount(); - if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) { - noteProbe(pid, 'no-ports', 0, totalPids); - return { port: 0, uin: '', identityKnown: false }; + if (ports === null) { + noteProbe(pid, 'unavailable', 0, null); + return null; } - noteProbe(pid, 'inconclusive', 0, totalPids); - return null; - } - const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309]; - const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310]; - const matchedOddPorts = ports.filter(p => ODD_PT_PORTS.includes(p)); - const matchedEvenPorts = ports.filter(p => EVEN_PT_PORTS.includes(p)); + if (ports.length === 0) { + const totalPids = await getQqProcessCount(); - let ptPortsToTry: number[] = []; - if (matchedOddPorts.length > 0) { - ptPortsToTry = matchedOddPorts; - } else if (matchedEvenPorts.length > 0) { - ptPortsToTry = matchedEvenPorts; - } + if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) { + noteProbe(pid, 'no-ports', 0, totalPids); + return { port: 0, uin: '', identityKnown: false }; + } - if (ptPortsToTry.length > 0) { - for (const port of ptPortsToTry) { - const ptResult = await tryPtloginMethod(port); - if (ptResult !== 'fallback') { - return ptResult; - } + noteProbe(pid, 'inconclusive', 0, totalPids); + return null; } - } else { - const totalPids = await getQqProcessCount(); - if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) { - noteProbe(pid, 'no-ports', ports.length, totalPids); - return { - port: ports[0] || 0, - uin: '', - identityKnown: false, - }; - } - noteProbe(pid, 'inconclusive', ports.length, totalPids); - return null; - } - // Background discovery must remain passive. Interactive application - // endpoints are deliberately excluded from automatic probing. - noteProbe(pid, 'no-match', ptPortsToTry.length, null); - return null; + const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309]; + const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310]; + + const matchedOddPorts = ports.filter((p) => ODD_PT_PORTS.includes(p)); + const matchedEvenPorts = ports.filter((p) => EVEN_PT_PORTS.includes(p)); + + let ptPortsToTry: number[] = []; + + if (matchedOddPorts.length > 0) { + ptPortsToTry = matchedOddPorts; + } else if (matchedEvenPorts.length > 0) { + ptPortsToTry = matchedEvenPorts; + } + + if (ptPortsToTry.length > 0) { + for (const port of ptPortsToTry) { + const ptResult = await tryPtloginMethod(port); + + if (ptResult !== 'fallback') { + return ptResult; + } + } + } else { + const totalPids = await getQqProcessCount(); + + if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) { + noteProbe(pid, 'no-ports', ports.length, totalPids); + return { + port: ports[0] || 0, + uin: '', + identityKnown: false, + }; + } + + noteProbe(pid, 'inconclusive', ports.length, totalPids); + return null; + } + + // Background discovery must remain passive. Interactive application + // endpoints are deliberately excluded from automatic probing. + noteProbe(pid, 'no-match', ptPortsToTry.length, null); + return null; } export async function probeQqLoginInfo(pid: number): Promise { - let timer: ReturnType | undefined; - let timedOut = false; - const timeout = new Promise(resolve => { - timer = setTimeout(() => { - timedOut = true; - resolve(null); - }, OVERALL_PROBE_TIMEOUT_MS); - }); - try { - const result = await Promise.race([probeQqLoginInfoInternal(pid), timeout]); - if (timedOut) log.warn('login check timed out: PID=%d', pid); - return result; - } finally { - if (timer) clearTimeout(timer); - } + let timer: ReturnType | undefined; + let timedOut = false; + const timeout = new Promise((resolve) => { + timer = setTimeout(() => { + timedOut = true; + resolve(null); + }, OVERALL_PROBE_TIMEOUT_MS); + }); + + try { + const result = await Promise.race([probeQqLoginInfoInternal(pid), timeout]); + + if (timedOut) { + log.warn('login check timed out: PID=%d', pid); + } + + return result; + } finally { + if (timer) { + clearTimeout(timer); + } + } } diff --git a/packages/bridge/src/types.ts b/packages/bridge/src/types.ts index 9fe03b0d..4f8de478 100644 --- a/packages/bridge/src/types.ts +++ b/packages/bridge/src/types.ts @@ -1,21 +1,15 @@ import type { HookProcessBaseInfo } from './injector'; export type HookProcessStatus = - | 'available' - | 'loading' - | 'connecting' - | 'loaded' - | 'online' - | 'error' - | 'disconnected'; + 'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected'; /** Public-facing snapshot of a per-PID HookSession. */ export interface HookProcessInfo extends HookProcessBaseInfo { - injected: boolean; - connected: boolean; - loggedIn: boolean; - uin: string; - status: HookProcessStatus; - error: string; - method: string; + injected: boolean; + connected: boolean; + loggedIn: boolean; + uin: string; + status: HookProcessStatus; + error: string; + method: string; } diff --git a/packages/bridge/tests/hook-manager-state-notify.test.ts b/packages/bridge/tests/hook-manager-state-notify.test.ts index 49115863..0ddc4bff 100644 --- a/packages/bridge/tests/hook-manager-state-notify.test.ts +++ b/packages/bridge/tests/hook-manager-state-notify.test.ts @@ -13,203 +13,228 @@ import type { QqHookClient } from '../src/qq-hook-client'; // browser without REST polling. const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; -const flush = () => new Promise(r => setImmediate(r)); +const flush = () => new Promise((r) => setImmediate(r)); interface Harness { - manager: HookManager; - pipeWatcher: PipeWatcher; - bridgeManager: BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType }; - setProcesses: (next: number[]) => void; - setLivePipes: (next: number[]) => void; - onSessionsChanged: ReturnType; - clientFactory: ReturnType; + manager: HookManager; + pipeWatcher: PipeWatcher; + bridgeManager: BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType }; + setProcesses: (next: number[]) => void; + setLivePipes: (next: number[]) => void; + onSessionsChanged: ReturnType; + clientFactory: ReturnType; } function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness { - let pids = opts.processes ?? []; - let live = new Set(opts.livePipes ?? []); - const pipeWatcher = new PipeWatcher({ - listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })), - listLivePipes: async () => new Set(live), - intervalMs: 60_000, - }); - const clientFactory = vi.fn(() => { - const c = new EventEmitter() as EventEmitter & Partial; - (c as any).isClosed = false; - (c as any).isLoggedIn = false; - (c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n }); - (c as any).connectAll = async () => { /* succeed without doing anything */ }; - (c as any).close = () => { (c as any).isClosed = true; }; - return c as unknown as QqHookClient; - }); - const bridgeManager = { - onPacket: vi.fn(), - onHookLogin: vi.fn(), - onPidDisconnected: vi.fn(), - onPidReceiveHealthChanged: vi.fn(), - } as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType }; - const onSessionsChanged = vi.fn(); - const manager = new HookManager({ - bridgeManager, - pipeWatcher, - injector: { - inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), - unload: vi.fn(), - }, - makeClient: clientFactory, - listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })), - onSessionsChanged, - }); - return { - manager, - pipeWatcher, - bridgeManager, - onSessionsChanged, - clientFactory, - setProcesses: (next) => { pids = next; }, - setLivePipes: (next) => { live = new Set(next); }, - }; -} - -describe('HookManager.onSessionsChanged', () => { - it('fires when the watcher discovers a new QQ process', async () => { - const ctx = makeManager({ processes: [] }); - await ctx.pipeWatcher.start(); - expect(ctx.onSessionsChanged).not.toHaveBeenCalled(); - - ctx.setProcesses([4242]); - await ctx.pipeWatcher.tickNow(); - await flush(); - expect(ctx.onSessionsChanged).toHaveBeenCalled(); - - ctx.manager.dispose(); - }); - - it('fires when the watcher reports a process is gone', async () => { - const ctx = makeManager({ processes: [4242] }); - await ctx.pipeWatcher.start(); - await flush(); - ctx.onSessionsChanged.mockClear(); - - ctx.setProcesses([]); - await ctx.pipeWatcher.tickNow(); - await flush(); - expect(ctx.onSessionsChanged).toHaveBeenCalled(); - - ctx.manager.dispose(); - }); - - it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => { - const ctx = makeManager({ processes: [4242] }); - await ctx.pipeWatcher.start(); - await flush(); - // Inject so the session is in 'connecting' state; the next pipe-up - // makes attemptConnect succeed and status flips to 'loaded'. - await ctx.manager.loadProcess(4242); - await flush(); - ctx.onSessionsChanged.mockClear(); - - ctx.setLivePipes([4242]); - await ctx.pipeWatcher.tickNow(); - await flush(); - await flush(); - expect(ctx.onSessionsChanged).toHaveBeenCalled(); - - ctx.manager.dispose(); - }); - - it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => { - const ctx = makeManager({ processes: [] }); - ctx.onSessionsChanged.mockImplementation(() => { throw new Error('listener boom'); }); - await ctx.pipeWatcher.start(); - ctx.setProcesses([4242]); - await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow(); - await flush(); - // A second tick still fires the callback — it wasn't unregistered by - // the prior throw. - ctx.onSessionsChanged.mockClear(); - ctx.setProcesses([4242, 5555]); - await ctx.pipeWatcher.tickNow(); - await flush(); - expect(ctx.onSessionsChanged).toHaveBeenCalled(); - - ctx.manager.dispose(); - }); - - it('is OPTIONAL — omitting it leaves the manager fully functional', async () => { - const pids = [4242]; + let pids = opts.processes ?? []; + let live = new Set(opts.livePipes ?? []); const pipeWatcher = new PipeWatcher({ - listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })), - listLivePipes: async () => new Set(), - intervalMs: 60_000, + listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), + listLivePipes: async () => new Set(live), + intervalMs: 60_000, }); - const manager = new HookManager({ - bridgeManager: { + const clientFactory = vi.fn(() => { + const c = new EventEmitter() as EventEmitter & Partial; + (c as any).isClosed = false; + (c as any).isLoggedIn = false; + (c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n }); + + (c as any).connectAll = async () => { + /* succeed without doing anything */ + }; + + (c as any).close = () => { + (c as any).isClosed = true; + }; + + return c as unknown as QqHookClient; + }); + const bridgeManager = { onPacket: vi.fn(), onHookLogin: vi.fn(), onPidDisconnected: vi.fn(), - } as unknown as BridgeManagerSink, - pipeWatcher, - injector: { - inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), - unload: vi.fn(), - }, - makeClient: vi.fn(() => { - const c = new EventEmitter() as any; - c.isClosed = false; c.isLoggedIn = false; - c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n }); - c.connectAll = async () => undefined; - c.close = () => { c.isClosed = true; }; - return c; - }), - listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })), - // onSessionsChanged deliberately omitted + onPidReceiveHealthChanged: vi.fn(), + } as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType }; + const onSessionsChanged = vi.fn(); + const manager = new HookManager({ + bridgeManager, + pipeWatcher, + injector: { + inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), + unload: vi.fn(), + }, + makeClient: clientFactory, + listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), + onSessionsChanged, + }); + return { + manager, + pipeWatcher, + bridgeManager, + onSessionsChanged, + clientFactory, + setProcesses: (next) => { + pids = next; + }, + setLivePipes: (next) => { + live = new Set(next); + }, + }; +} + +describe('HookManager.onSessionsChanged', () => { + it('fires when the watcher discovers a new QQ process', async () => { + const ctx = makeManager({ processes: [] }); + await ctx.pipeWatcher.start(); + expect(ctx.onSessionsChanged).not.toHaveBeenCalled(); + + ctx.setProcesses([4242]); + await ctx.pipeWatcher.tickNow(); + await flush(); + expect(ctx.onSessionsChanged).toHaveBeenCalled(); + + ctx.manager.dispose(); + }); + + it('fires when the watcher reports a process is gone', async () => { + const ctx = makeManager({ processes: [4242] }); + await ctx.pipeWatcher.start(); + await flush(); + ctx.onSessionsChanged.mockClear(); + + ctx.setProcesses([]); + await ctx.pipeWatcher.tickNow(); + await flush(); + expect(ctx.onSessionsChanged).toHaveBeenCalled(); + + ctx.manager.dispose(); + }); + + it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => { + const ctx = makeManager({ processes: [4242] }); + await ctx.pipeWatcher.start(); + await flush(); + // Inject so the session is in 'connecting' state; the next pipe-up + // makes attemptConnect succeed and status flips to 'loaded'. + await ctx.manager.loadProcess(4242); + await flush(); + ctx.onSessionsChanged.mockClear(); + + ctx.setLivePipes([4242]); + await ctx.pipeWatcher.tickNow(); + await flush(); + await flush(); + expect(ctx.onSessionsChanged).toHaveBeenCalled(); + + ctx.manager.dispose(); + }); + + it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => { + const ctx = makeManager({ processes: [] }); + ctx.onSessionsChanged.mockImplementation(() => { + throw new Error('listener boom'); + }); + await ctx.pipeWatcher.start(); + ctx.setProcesses([4242]); + await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow(); + await flush(); + // A second tick still fires the callback — it wasn't unregistered by + // the prior throw. + ctx.onSessionsChanged.mockClear(); + ctx.setProcesses([4242, 5555]); + await ctx.pipeWatcher.tickNow(); + await flush(); + expect(ctx.onSessionsChanged).toHaveBeenCalled(); + + ctx.manager.dispose(); + }); + + it('is OPTIONAL — omitting it leaves the manager fully functional', async () => { + const pids = [4242]; + const pipeWatcher = new PipeWatcher({ + listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), + listLivePipes: async () => new Set(), + intervalMs: 60_000, + }); + const manager = new HookManager({ + bridgeManager: { + onPacket: vi.fn(), + onHookLogin: vi.fn(), + onPidDisconnected: vi.fn(), + } as unknown as BridgeManagerSink, + pipeWatcher, + injector: { + inject: vi.fn(() => ({ + method: 'loadModuleManual' as const, + handle: DUMMY_HANDLE, + })), + unload: vi.fn(), + }, + makeClient: vi.fn(() => { + const c = new EventEmitter() as any; + c.isClosed = false; + c.isLoggedIn = false; + c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n }); + c.connectAll = async () => undefined; + + c.close = () => { + c.isClosed = true; + }; + + return c; + }), + listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), + // onSessionsChanged deliberately omitted + }); + await pipeWatcher.start(); + await pipeWatcher.tickNow(); + await flush(); + const list = await manager.listProcesses(); + expect(list).toHaveLength(1); + expect(list[0].pid).toBe(4242); + manager.dispose(); }); - await pipeWatcher.start(); - await pipeWatcher.tickNow(); - await flush(); - const list = await manager.listProcesses(); - expect(list).toHaveLength(1); - expect(list[0].pid).toBe(4242); - manager.dispose(); - }); }); describe('HookManager receive-health wiring (#233)', () => { - it('forwards stale and recovered receive health for the owning PID', async () => { - const ctx = makeManager({ processes: [4242], livePipes: [4242] }); - await ctx.pipeWatcher.start(); - await ctx.manager.loadProcess(4242); - await ctx.manager.refreshProcess(4242); - await flush(); + it('forwards stale and recovered receive health for the owning PID', async () => { + const ctx = makeManager({ processes: [4242], livePipes: [4242] }); + await ctx.pipeWatcher.start(); + await ctx.manager.loadProcess(4242); + await ctx.manager.refreshProcess(4242); + await flush(); - const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter; - client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n }); + const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter; + client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n }); - vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); - try { - client.emit('packet', { - seq: 1, - error: 0, - cmd: 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat', - uin: '10001', - body: Buffer.alloc(0), - }); - vi.advanceTimersByTime(105_000); + vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); - expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenCalledWith(4242, false); + try { + client.emit('packet', { + seq: 1, + error: 0, + cmd: 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat', + uin: '10001', + body: Buffer.alloc(0), + }); + vi.advanceTimersByTime(105_000); - client.emit('packet', { - seq: 2, - error: 0, - cmd: 'trpc.msg.olpush.OlPushService.MsgPush', - uin: '10001', - body: Buffer.alloc(0), - }); - expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(4242, true); - } finally { - vi.useRealTimers(); - ctx.manager.dispose(); - } - }); + expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenCalledWith(4242, false); + + client.emit('packet', { + seq: 2, + error: 0, + cmd: 'trpc.msg.olpush.OlPushService.MsgPush', + uin: '10001', + body: Buffer.alloc(0), + }); + expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith( + 4242, + true, + ); + } finally { + vi.useRealTimers(); + ctx.manager.dispose(); + } + }); }); diff --git a/packages/bridge/tests/hook-manager.test.ts b/packages/bridge/tests/hook-manager.test.ts index 5b3d2fb8..ae62f079 100644 --- a/packages/bridge/tests/hook-manager.test.ts +++ b/packages/bridge/tests/hook-manager.test.ts @@ -9,420 +9,463 @@ import type { HookInjectResult, ManualMapHandle } from '../src/injector'; import type { BridgeManagerSink } from '../src/hook-manager'; import type { QqHookClient } from '../src/qq-hook-client'; import { - createLogger, - getLogLevel, - setLogLevel, - subscribeLogs, - type LogEntry, + createLogger, + getLogLevel, + setLogLevel, + subscribeLogs, + type LogEntry, } from '@snowluma/common/logger'; const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; -const flush = () => new Promise(r => setImmediate(r)); +const flush = () => new Promise((r) => setImmediate(r)); const previousLogLevel = getLogLevel(); function managerTrace(entries: LogEntry[]): LogEntry[] { - return entries.filter( - (entry) => entry.level === 'trace' && entry.scope === 'Hook', - ); + return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Hook'); } function makeManager(opts: { - autoLoadOnDiscovery?: boolean; - processes?: number[]; - onSessionsChanged?: () => void; - inject?: (pid: number) => HookInjectResult | Promise; + autoLoadOnDiscovery?: boolean; + processes?: number[]; + onSessionsChanged?: () => void; + inject?: (pid: number) => HookInjectResult | Promise; }) { - let pids = opts.processes ?? []; - const live = new Set(); - const inject = vi.fn(opts.inject ?? (() => ({ - method: 'loadModuleManual' as const, - handle: DUMMY_HANDLE, - }))); - const unload = vi.fn(); - const pipeWatcher = new PipeWatcher({ - listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })), - listLivePipes: async () => new Set(live), - intervalMs: 60_000, // disable internal timer; tests drive ticks manually - }); - // FakeClient — never connected; just needs to satisfy EventEmitter + - // a minimal subset of QqHookClient for HookSession.tearDownClient(). - const makeClient = vi.fn(() => { - const c = new EventEmitter() as EventEmitter & Partial; - (c as any).isClosed = false; - (c as any).isLoggedIn = false; - (c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n }); - (c as any).connectAll = async () => { throw new Error('test: never really connect'); }; - (c as any).close = () => { (c as any).isClosed = true; }; - return c as unknown as QqHookClient; - }); - const bridgeManager = { - onPacket: vi.fn(), - onHookLogin: vi.fn(), - onPidDisconnected: vi.fn(), - } as unknown as BridgeManagerSink; - const manager = new HookManager({ - bridgeManager, - pipeWatcher, - injector: { inject, unload }, - makeClient, - autoLoadOnDiscovery: opts.autoLoadOnDiscovery, - onSessionsChanged: opts.onSessionsChanged, - listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })), - }); - return { - manager, - inject, - pipeWatcher, - setProcesses: (next: number[]) => { pids = next; }, - }; + let pids = opts.processes ?? []; + const live = new Set(); + const inject = vi.fn( + opts.inject ?? + (() => ({ + method: 'loadModuleManual' as const, + handle: DUMMY_HANDLE, + })), + ); + const unload = vi.fn(); + const pipeWatcher = new PipeWatcher({ + listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), + listLivePipes: async () => new Set(live), + intervalMs: 60_000, // disable internal timer; tests drive ticks manually + }); + // FakeClient — never connected; just needs to satisfy EventEmitter + + // a minimal subset of QqHookClient for HookSession.tearDownClient(). + const makeClient = vi.fn(() => { + const c = new EventEmitter() as EventEmitter & Partial; + (c as any).isClosed = false; + (c as any).isLoggedIn = false; + (c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n }); + + (c as any).connectAll = async () => { + throw new Error('test: never really connect'); + }; + + (c as any).close = () => { + (c as any).isClosed = true; + }; + + return c as unknown as QqHookClient; + }); + const bridgeManager = { + onPacket: vi.fn(), + onHookLogin: vi.fn(), + onPidDisconnected: vi.fn(), + } as unknown as BridgeManagerSink; + const manager = new HookManager({ + bridgeManager, + pipeWatcher, + injector: { inject, unload }, + makeClient, + autoLoadOnDiscovery: opts.autoLoadOnDiscovery, + onSessionsChanged: opts.onSessionsChanged, + listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), + }); + return { + manager, + inject, + pipeWatcher, + setProcesses: (next: number[]) => { + pids = next; + }, + }; } afterEach(() => { - setLogLevel(previousLogLevel); + setLogLevel(previousLogLevel); }); describe('HookManager runtime TRACE', () => { - it('records discovery and process-gone facts while unchanged ticks stay silent', async () => { - const entries: LogEntry[] = []; - const sessionsChanged = vi.fn(); - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const ctx = makeManager({ - autoLoadOnDiscovery: false, - processes: [], - onSessionsChanged: sessionsChanged, + it('records discovery and process-gone facts while unchanged ticks stay silent', async () => { + const entries: LogEntry[] = []; + const sessionsChanged = vi.fn(); + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const ctx = makeManager({ + autoLoadOnDiscovery: false, + processes: [], + onSessionsChanged: sessionsChanged, + }); + + try { + await ctx.pipeWatcher.start(); + const baseline = managerTrace(entries).length; + await ctx.pipeWatcher.tickNow(); + await ctx.pipeWatcher.tickNow(); + expect(managerTrace(entries)).toHaveLength(baseline); + + ctx.setProcesses([4242]); + await ctx.pipeWatcher.tickNow(); + ctx.setProcesses([]); + await ctx.pipeWatcher.tickNow(); + await flush(); + + const facts = managerTrace(entries).filter((entry) => + entry.message.startsWith('hook_manager_fact '), + ); + expect(facts.map((entry) => entry.message)).toEqual([ + expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'), + 'hook_manager_fact event=process_gone pid=4242 tracked=true', + ]); + expect(facts.every((entry) => entry.req !== undefined)).toBe(true); + } finally { + unsubscribe(); + ctx.manager.dispose(); + } }); - try { - await ctx.pipeWatcher.start(); - const baseline = managerTrace(entries).length; - await ctx.pipeWatcher.tickNow(); - await ctx.pipeWatcher.tickNow(); - expect(managerTrace(entries)).toHaveLength(baseline); - ctx.setProcesses([4242]); - await ctx.pipeWatcher.tickNow(); - ctx.setProcesses([]); - await ctx.pipeWatcher.tickNow(); - await flush(); + it('records bounded transient retries and recovery as separate attempts', async () => { + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); + ctx.inject + .mockImplementationOnce(() => { + throw new Error( + 'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap', + ); + }) + .mockImplementationOnce(() => ({ + method: 'loadModuleManual' as const, + handle: DUMMY_HANDLE, + })); - const facts = managerTrace(entries).filter( - (entry) => entry.message.startsWith('hook_manager_fact '), - ); - expect(facts.map((entry) => entry.message)).toEqual([ - expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'), - 'hook_manager_fact event=process_gone pid=4242 tracked=true', - ]); - expect(facts.every((entry) => entry.req !== undefined)).toBe(true); - } finally { - unsubscribe(); - ctx.manager.dispose(); - } - }); + try { + await ctx.pipeWatcher.start(); + await flush(); + await flush(); + await ctx.pipeWatcher.tickNow(); + await flush(); + await flush(); - it('records bounded transient retries and recovery as separate attempts', async () => { - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); - ctx.inject - .mockImplementationOnce(() => { - throw new Error( - 'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap', - ); - }) - .mockImplementationOnce(() => ({ - method: 'loadModuleManual' as const, - handle: DUMMY_HANDLE, - })); - try { - await ctx.pipeWatcher.start(); - await flush(); - await flush(); - await ctx.pipeWatcher.tickNow(); - await flush(); - await flush(); - - const attempts = managerTrace(entries).filter( - (entry) => entry.message.startsWith('hook_autoload_'), - ); - expect(attempts.map((entry) => entry.message)).toEqual([ - 'hook_autoload_start pid=4242 attempt=1 maxAttempts=3', - expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/), - 'hook_autoload_start pid=4242 attempt=2 maxAttempts=3', - expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/), - ]); - expect(attempts[0]!.req).toBe(attempts[1]!.req); - expect(attempts[2]!.req).toBe(attempts[3]!.req); - expect(attempts[0]!.req).not.toBe(attempts[2]!.req); - } finally { - unsubscribe(); - ctx.manager.dispose(); - } - }); - - it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => { - const entries: LogEntry[] = []; - let resolveInjection!: (result: HookInjectResult) => void; - const injection = new Promise((resolve) => { - resolveInjection = resolve; + const attempts = managerTrace(entries).filter((entry) => + entry.message.startsWith('hook_autoload_'), + ); + expect(attempts.map((entry) => entry.message)).toEqual([ + 'hook_autoload_start pid=4242 attempt=1 maxAttempts=3', + expect.stringMatching( + /^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/, + ), + 'hook_autoload_start pid=4242 attempt=2 maxAttempts=3', + expect.stringMatching( + /^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/, + ), + ]); + expect(attempts[0]!.req).toBe(attempts[1]!.req); + expect(attempts[2]!.req).toBe(attempts[3]!.req); + expect(attempts[0]!.req).not.toBe(attempts[2]!.req); + } finally { + unsubscribe(); + ctx.manager.dispose(); + } }); - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const ctx = makeManager({ - autoLoadOnDiscovery: true, - processes: [4242], - inject: () => injection, + + it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => { + const entries: LogEntry[] = []; + let resolveInjection!: (result: HookInjectResult) => void; + const injection = new Promise((resolve) => { + resolveInjection = resolve; + }); + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const ctx = makeManager({ + autoLoadOnDiscovery: true, + processes: [4242], + inject: () => injection, + }); + + try { + await ctx.pipeWatcher.start(); + await flush(); + const manualLoad = ctx.manager.loadProcess(4242); + resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE }); + await manualLoad; + await flush(); + + const attempts = managerTrace(entries).filter((entry) => + entry.message.startsWith('hook_autoload_'), + ); + expect(attempts.map((entry) => entry.message)).toEqual([ + 'hook_autoload_start pid=4242 attempt=1 maxAttempts=3', + expect.stringMatching( + /^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/, + ), + ]); + expect(attempts[0]!.req).toBe(attempts[1]!.req); + } finally { + unsubscribe(); + ctx.manager.dispose(); + } }); - try { - await ctx.pipeWatcher.start(); - await flush(); - const manualLoad = ctx.manager.loadProcess(4242); - resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE }); - await manualLoad; - await flush(); - const attempts = managerTrace(entries).filter( - (entry) => entry.message.startsWith('hook_autoload_'), - ); - expect(attempts.map((entry) => entry.message)).toEqual([ - 'hook_autoload_start pid=4242 attempt=1 maxAttempts=3', - expect.stringMatching( - /^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/, - ), - ]); - expect(attempts[0]!.req).toBe(attempts[1]!.req); - } finally { - unsubscribe(); - ctx.manager.dispose(); - } - }); + it.each([ + { + name: 'permanent failure', + error: 'ptrace denied', + ticks: 1, + attempts: 1, + reason: 'permanent_failure', + }, + { + name: 'retry exhaustion', + error: 'target process does not map /lib/libc.so.6 while resolving mmap', + ticks: 4, + attempts: 3, + reason: 'retry_exhausted', + }, + ])('records $name terminal', async ({ error, ticks, attempts, reason }) => { + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); + ctx.inject.mockImplementation(() => { + throw new Error(error); + }); - it.each([ - { - name: 'permanent failure', - error: 'ptrace denied', - ticks: 1, - attempts: 1, - reason: 'permanent_failure', - }, - { - name: 'retry exhaustion', - error: 'target process does not map /lib/libc.so.6 while resolving mmap', - ticks: 4, - attempts: 3, - reason: 'retry_exhausted', - }, - ])('records $name terminal', async ({ error, ticks, attempts, reason }) => { - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); - ctx.inject.mockImplementation(() => { throw new Error(error); }); - try { - await ctx.pipeWatcher.start(); - await flush(); - await flush(); - for (let tick = 0; tick < ticks; tick += 1) { - await ctx.pipeWatcher.tickNow(); - await flush(); - await flush(); - } + try { + await ctx.pipeWatcher.start(); + await flush(); + await flush(); - const starts = managerTrace(entries).filter( - (entry) => entry.message.startsWith('hook_autoload_start '), - ); - const terminals = managerTrace(entries).filter( - (entry) => entry.message.startsWith('hook_autoload_terminal '), - ); - expect(starts).toHaveLength(attempts); - expect(terminals).toHaveLength(attempts); - expect(terminals.at(-1)!.message).toContain(`reason=${reason}`); - } finally { - unsubscribe(); - ctx.manager.dispose(); - } - }); + for (let tick = 0; tick < ticks; tick += 1) { + await ctx.pipeWatcher.tickNow(); + await flush(); + await flush(); + } + + const starts = managerTrace(entries).filter((entry) => + entry.message.startsWith('hook_autoload_start '), + ); + const terminals = managerTrace(entries).filter((entry) => + entry.message.startsWith('hook_autoload_terminal '), + ); + expect(starts).toHaveLength(attempts); + expect(terminals).toHaveLength(attempts); + expect(terminals.at(-1)!.message).toContain(`reason=${reason}`); + } finally { + unsubscribe(); + ctx.manager.dispose(); + } + }); }); describe('HookManager.autoLoadOnDiscovery', () => { - it('does NOT inject on process-discovered when flag is off', async () => { - const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] }); - await ctx.pipeWatcher.start(); - await flush(); - expect(ctx.inject).not.toHaveBeenCalled(); - ctx.manager.dispose(); - }); - - it('injects every newly-discovered PID when flag is on', async () => { - const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); - await ctx.pipeWatcher.start(); - // session.load() is queued via a per-session promise chain; flush twice - // so the auto-load runs to completion before we assert. - await flush(); - await flush(); - expect(ctx.inject).toHaveBeenCalledTimes(1); - expect(ctx.inject).toHaveBeenCalledWith(4242); - - // A second PID appearing mid-flight should also trigger an inject. - ctx.setProcesses([4242, 9999]); - await ctx.pipeWatcher.tickNow(); - await flush(); - await flush(); - expect(ctx.inject).toHaveBeenCalledTimes(2); - expect(ctx.inject).toHaveBeenLastCalledWith(9999); - - ctx.manager.dispose(); - }); - - it('swallows inject errors so the watcher keeps running', async () => { - const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); - ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); }); - await ctx.pipeWatcher.start(); - await flush(); - await flush(); - - // Second PID should still be auto-loaded — the failure on 4242 must - // not leak out of the listener and break the watcher's emit loop. - ctx.setProcesses([4242, 9999]); - await ctx.pipeWatcher.tickNow(); - await flush(); - await flush(); - expect(ctx.inject).toHaveBeenCalledTimes(2); - - ctx.manager.dispose(); - }); - - it('retries a transient libc mapping failure on the next watcher tick', async () => { - const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); - ctx.inject.mockImplementationOnce(() => { - throw new Error( - 'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap', - ); + it('does NOT inject on process-discovered when flag is off', async () => { + const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] }); + await ctx.pipeWatcher.start(); + await flush(); + expect(ctx.inject).not.toHaveBeenCalled(); + ctx.manager.dispose(); }); - await ctx.pipeWatcher.start(); - await flush(); - await flush(); - expect(ctx.inject).toHaveBeenCalledTimes(1); + it('injects every newly-discovered PID when flag is on', async () => { + const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); + await ctx.pipeWatcher.start(); + // session.load() is queued via a per-session promise chain; flush twice + // so the auto-load runs to completion before we assert. + await flush(); + await flush(); + expect(ctx.inject).toHaveBeenCalledTimes(1); + expect(ctx.inject).toHaveBeenCalledWith(4242); - await ctx.pipeWatcher.tickNow(); - await flush(); - await flush(); - expect(ctx.inject).toHaveBeenCalledTimes(2); - expect(ctx.inject).toHaveBeenLastCalledWith(4242); + // A second PID appearing mid-flight should also trigger an inject. + ctx.setProcesses([4242, 9999]); + await ctx.pipeWatcher.tickNow(); + await flush(); + await flush(); + expect(ctx.inject).toHaveBeenCalledTimes(2); + expect(ctx.inject).toHaveBeenLastCalledWith(9999); - ctx.manager.dispose(); - }); - - it('does not retry permanent auto-load errors', async () => { - const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); - ctx.inject.mockImplementation(() => { throw new Error('ptrace denied'); }); - - await ctx.pipeWatcher.start(); - await flush(); - await flush(); - - await ctx.pipeWatcher.tickNow(); - await flush(); - await flush(); - expect(ctx.inject).toHaveBeenCalledTimes(1); - - ctx.manager.dispose(); - }); - - it('stops retrying a transient libc mapping failure after three attempts', async () => { - const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); - ctx.inject.mockImplementation(() => { - throw new Error( - 'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap', - ); + ctx.manager.dispose(); }); - await ctx.pipeWatcher.start(); - await flush(); - await flush(); + it('swallows inject errors so the watcher keeps running', async () => { + const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); + ctx.inject.mockImplementationOnce(() => { + throw new Error('ptrace denied'); + }); + await ctx.pipeWatcher.start(); + await flush(); + await flush(); - for (let tick = 0; tick < 4; tick += 1) { - await ctx.pipeWatcher.tickNow(); - await flush(); - await flush(); - } - expect(ctx.inject).toHaveBeenCalledTimes(3); + // Second PID should still be auto-loaded — the failure on 4242 must + // not leak out of the listener and break the watcher's emit loop. + ctx.setProcesses([4242, 9999]); + await ctx.pipeWatcher.tickNow(); + await flush(); + await flush(); + expect(ctx.inject).toHaveBeenCalledTimes(2); - ctx.manager.dispose(); - }); + ctx.manager.dispose(); + }); + + it('retries a transient libc mapping failure on the next watcher tick', async () => { + const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); + ctx.inject.mockImplementationOnce(() => { + throw new Error( + 'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap', + ); + }); + + await ctx.pipeWatcher.start(); + await flush(); + await flush(); + expect(ctx.inject).toHaveBeenCalledTimes(1); + + await ctx.pipeWatcher.tickNow(); + await flush(); + await flush(); + expect(ctx.inject).toHaveBeenCalledTimes(2); + expect(ctx.inject).toHaveBeenLastCalledWith(4242); + + ctx.manager.dispose(); + }); + + it('does not retry permanent auto-load errors', async () => { + const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); + ctx.inject.mockImplementation(() => { + throw new Error('ptrace denied'); + }); + + await ctx.pipeWatcher.start(); + await flush(); + await flush(); + + await ctx.pipeWatcher.tickNow(); + await flush(); + await flush(); + expect(ctx.inject).toHaveBeenCalledTimes(1); + + ctx.manager.dispose(); + }); + + it('stops retrying a transient libc mapping failure after three attempts', async () => { + const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] }); + ctx.inject.mockImplementation(() => { + throw new Error( + 'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap', + ); + }); + + await ctx.pipeWatcher.start(); + await flush(); + await flush(); + + for (let tick = 0; tick < 4; tick += 1) { + await ctx.pipeWatcher.tickNow(); + await flush(); + await flush(); + } + + expect(ctx.inject).toHaveBeenCalledTimes(3); + + ctx.manager.dispose(); + }); }); // `shouldAutoLoadPid` reads /proc//cmdline directly, so we point // it at a temporary directory that mimics the procfs layout. This lets // the tests run on macOS / CI without a live Linux QQ process. describe('shouldAutoLoadPid', () => { - let tmpProc: string; - const originalReadFileSync = fs.readFileSync; - const log = createLogger('test'); - const originalPlatform = process.platform; - const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL; + let tmpProc: string; + const originalReadFileSync = fs.readFileSync; + const log = createLogger('test'); + const originalPlatform = process.platform; + const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL; - beforeEach(() => { - tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-')); - Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }); - delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL; - // Redirect readFileSync('/proc//cmdline') to the tmp dir. - (fs.readFileSync as unknown as typeof fs.readFileSync) = ((p: string, ...rest: unknown[]) => { - const match = /^\/proc\/(\d+)\/cmdline$/.exec(p); - if (match) { - return originalReadFileSync(path.join(tmpProc, match[1], 'cmdline'), ...(rest as [BufferEncoding])); - } - return originalReadFileSync(p, ...(rest as [BufferEncoding])); - }) as typeof fs.readFileSync; - }); + beforeEach(() => { + tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-')); + Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }); + delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL; + // Redirect readFileSync('/proc//cmdline') to the tmp dir. + (fs.readFileSync as unknown as typeof fs.readFileSync) = (( + p: string, + ...rest: unknown[] + ) => { + const match = /^\/proc\/(\d+)\/cmdline$/.exec(p); - afterEach(() => { - (fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync; - Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }); - if (originalAutoLoadAll === undefined) delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL; - else process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll; - fs.rmSync(tmpProc, { recursive: true, force: true }); - }); + if (match) { + return originalReadFileSync( + path.join(tmpProc, match[1], 'cmdline'), + ...(rest as [BufferEncoding]), + ); + } - function writeCmdline(pid: number, args: string[]): void { - const dir = path.join(tmpProc, String(pid)); - fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0'); - } + return originalReadFileSync(p, ...(rest as [BufferEncoding])); + }) as typeof fs.readFileSync; + }); - it('allows the QQ main process (no --type=)', () => { - writeCmdline(50, ['qq', '--no-sandbox']); - expect(shouldAutoLoadPid(50, log)).toBe(true); - }); + afterEach(() => { + (fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync; + Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }); - it('rejects Electron zygotes', () => { - writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']); - expect(shouldAutoLoadPid(59, log)).toBe(false); - }); + if (originalAutoLoadAll === undefined) { + delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL; + } else { + process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll; + } - it('rejects renderer/gpu/utility children', () => { - writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']); - writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']); - writeCmdline(72, ['/opt/QQ/qq', '--type=utility', '--utility-sub-type=network.mojom.NetworkService']); - expect(shouldAutoLoadPid(70, log)).toBe(false); - expect(shouldAutoLoadPid(71, log)).toBe(false); - expect(shouldAutoLoadPid(72, log)).toBe(false); - }); + fs.rmSync(tmpProc, { recursive: true, force: true }); + }); - it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => { - writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']); - process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1'; - expect(shouldAutoLoadPid(59, log)).toBe(true); - }); + function writeCmdline(pid: number, args: string[]): void { + const dir = path.join(tmpProc, String(pid)); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0'); + } - it('allows on non-linux platforms (filter is a Linux-only workaround)', () => { - Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }); - // No cmdline file needed — we return true before touching procfs. - expect(shouldAutoLoadPid(59, log)).toBe(true); - }); + it('allows the QQ main process (no --type=)', () => { + writeCmdline(50, ['qq', '--no-sandbox']); + expect(shouldAutoLoadPid(50, log)).toBe(true); + }); - it('allows when /proc is unreadable (dead PID, permission issue)', () => { - expect(shouldAutoLoadPid(99999, log)).toBe(true); - }); + it('rejects Electron zygotes', () => { + writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']); + expect(shouldAutoLoadPid(59, log)).toBe(false); + }); + + it('rejects renderer/gpu/utility children', () => { + writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']); + writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']); + writeCmdline(72, [ + '/opt/QQ/qq', + '--type=utility', + '--utility-sub-type=network.mojom.NetworkService', + ]); + expect(shouldAutoLoadPid(70, log)).toBe(false); + expect(shouldAutoLoadPid(71, log)).toBe(false); + expect(shouldAutoLoadPid(72, log)).toBe(false); + }); + + it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => { + writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']); + process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1'; + expect(shouldAutoLoadPid(59, log)).toBe(true); + }); + + it('allows on non-linux platforms (filter is a Linux-only workaround)', () => { + Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }); + // No cmdline file needed — we return true before touching procfs. + expect(shouldAutoLoadPid(59, log)).toBe(true); + }); + + it('allows when /proc is unreadable (dead PID, permission issue)', () => { + expect(shouldAutoLoadPid(99999, log)).toBe(true); + }); }); diff --git a/packages/bridge/tests/hook-packet-client.test.ts b/packages/bridge/tests/hook-packet-client.test.ts index e6502f9c..55bf8e8a 100644 --- a/packages/bridge/tests/hook-packet-client.test.ts +++ b/packages/bridge/tests/hook-packet-client.test.ts @@ -1,60 +1,70 @@ import { describe, expect, it, vi } from 'vitest'; import { HookPacketClient } from '../src/hook-packet-client'; import { - HookPipeRequestError, - PIPE_STATUS_CONNECTION_UNAVAILABLE, - type QqHookClient, + HookPipeRequestError, + PIPE_STATUS_CONNECTION_UNAVAILABLE, + type QqHookClient, } from '../src/qq-hook-client'; function fakeClient(send: QqHookClient['send']): QqHookClient { - return { - isLoggedIn: true, - send, - } as unknown as QqHookClient; + return { + isLoggedIn: true, + send, + } as unknown as QqHookClient; } describe('HookPacketClient outbound health', () => { - it('reports native connection loss once and recovers after a successful request', async () => { - const healthChanged = vi.fn(); - const send = vi - .fn() - .mockRejectedValueOnce(new HookPipeRequestError( - 'The QQ connection changed. Please restart QQ and try again.', - PIPE_STATUS_CONNECTION_UNAVAILABLE, - 1, - )) - .mockRejectedValueOnce(new HookPipeRequestError( - 'The QQ connection changed. Please restart QQ and try again.', - PIPE_STATUS_CONNECTION_UNAVAILABLE, - 2, - )) - .mockResolvedValueOnce({ - requestId: 3, - error: 0, - message: '', - body: Buffer.from('ok'), - }); - const sender = new HookPacketClient(fakeClient(send), healthChanged); + it('reports native connection loss once and recovers after a successful request', async () => { + const healthChanged = vi.fn(); + const send = vi + .fn() + .mockRejectedValueOnce( + new HookPipeRequestError( + 'The QQ connection changed. Please restart QQ and try again.', + PIPE_STATUS_CONNECTION_UNAVAILABLE, + 1, + ), + ) + .mockRejectedValueOnce( + new HookPipeRequestError( + 'The QQ connection changed. Please restart QQ and try again.', + PIPE_STATUS_CONNECTION_UNAVAILABLE, + 2, + ), + ) + .mockResolvedValueOnce({ + requestId: 3, + error: 0, + message: '', + body: Buffer.from('ok'), + }); + const sender = new HookPacketClient(fakeClient(send), healthChanged); - await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))) - .resolves.toMatchObject({ success: false, gotResponse: false }); - await sender.sendPacket('Test.Command', Buffer.alloc(0)); - await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))) - .resolves.toMatchObject({ success: true, gotResponse: true }); + await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({ + success: false, + gotResponse: false, + }); + await sender.sendPacket('Test.Command', Buffer.alloc(0)); + await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({ + success: true, + gotResponse: true, + }); - expect(healthChanged.mock.calls).toEqual([[false], [true]]); - }); + expect(healthChanged.mock.calls).toEqual([[false], [true]]); + }); - it('does not classify ordinary request rejection as connection loss', async () => { - const healthChanged = vi.fn(); - const send = vi.fn().mockRejectedValue( - new HookPipeRequestError('This request is not valid.', -38, 1), - ); - const sender = new HookPacketClient(fakeClient(send), healthChanged); + it('does not classify ordinary request rejection as connection loss', async () => { + const healthChanged = vi.fn(); + const send = vi + .fn() + .mockRejectedValue(new HookPipeRequestError('This request is not valid.', -38, 1)); + const sender = new HookPacketClient(fakeClient(send), healthChanged); - await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))) - .resolves.toMatchObject({ success: false, gotResponse: false }); + await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({ + success: false, + gotResponse: false, + }); - expect(healthChanged).not.toHaveBeenCalled(); - }); + expect(healthChanged).not.toHaveBeenCalled(); + }); }); diff --git a/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts b/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts index 61ef7d08..e2e8dcbf 100644 --- a/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts +++ b/packages/bridge/tests/hook-reconnect-no-login-e2e.test.ts @@ -13,87 +13,101 @@ import type { BridgeManagerSink } from '../src/hook-manager'; import type { QqHookClient } from '../src/qq-hook-client'; const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; -const flush = () => new Promise(r => setImmediate(r)); +const flush = () => new Promise((r) => setImmediate(r)); class FakeClient extends EventEmitter { - isClosed = false; - isLoggedIn = false; - async connectAll(_opts: { recv: boolean }) { - if (this.isClosed) throw new Error('client is closed'); - } - getLoginState() { return { loggedIn: false, uin: '0', uinNumber: 0n }; } - close() { - if (this.isClosed) return; - this.isClosed = true; - this.emit('close'); - } + isClosed = false; + isLoggedIn = false; + async connectAll(_opts: { recv: boolean }) { + if (this.isClosed) { + throw new Error('client is closed'); + } + } + getLoginState() { + return { loggedIn: false, uin: '0', uinNumber: 0n }; + } + close() { + if (this.isClosed) { + return; + } + + this.isClosed = true; + this.emit('close'); + } } describe('HookManager — Docker reconnect-without-login leak guard', () => { - it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => { - const PID = 61; - const liveSet = new Set([PID]); - const clients: FakeClient[] = []; + it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => { + const PID = 61; + const liveSet = new Set([PID]); + const clients: FakeClient[] = []; - const pipeWatcher = new PipeWatcher({ - listProcesses: () => [{ pid: PID, name: 'qq', path: '' }], - listLivePipes: async () => new Set(liveSet), - intervalMs: 60_000, // manual ticks only + const pipeWatcher = new PipeWatcher({ + listProcesses: () => [{ pid: PID, name: 'qq', path: '' }], + listLivePipes: async () => new Set(liveSet), + intervalMs: 60_000, // manual ticks only + }); + + const bridgeManager = { + onPacket: vi.fn(), + onHookLogin: vi.fn(), + onPidDisconnected: vi.fn(), + } as unknown as BridgeManagerSink; + + const manager = new HookManager({ + bridgeManager, + pipeWatcher, + injector: { + inject: vi.fn(() => ({ + method: 'loadModuleManual' as const, + handle: DUMMY_HANDLE, + })), + unload: vi.fn(), + }, + makeClient: () => { + const c = new FakeClient(); + clients.push(c); + return c as unknown as QqHookClient; + }, + autoLoadOnDiscovery: true, + listProcesses: () => [{ pid: PID, name: 'qq', path: '' }], + }); + + // Initial discovery + first connect. + await pipeWatcher.start(); + await flush(); + await flush(); + + // Drive 50 pipe up/down cycles with the QQ process staying alive but + // the pipe (= QQ control socket) bouncing every "tick". + const CYCLES = 50; + + for (let i = 0; i < CYCLES; i++) { + liveSet.delete(PID); + await pipeWatcher.tickNow(); + await flush(); + liveSet.add(PID); + await pipeWatcher.tickNow(); + await flush(); + } + + // The "QQ never logs in" hypothesis: BridgeManager should never have + // been told about a login or a disconnect. + expect(bridgeManager.onHookLogin).not.toHaveBeenCalled(); + expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled(); + expect(bridgeManager.onPacket).not.toHaveBeenCalled(); + + // Hook layer should hold at most one live client. + const alive = clients.filter((c) => !c.isClosed); + expect( + alive.length, + `live clients after ${CYCLES} cycles: ${alive.length}`, + ).toBeLessThanOrEqual(1); + + // Total clients minted = roughly one per up cycle. Sanity bound: + // we must have actually exercised the reconnect path. + expect(clients.length).toBeGreaterThan(1); + + manager.dispose(); }); - - const bridgeManager = { - onPacket: vi.fn(), - onHookLogin: vi.fn(), - onPidDisconnected: vi.fn(), - } as unknown as BridgeManagerSink; - - const manager = new HookManager({ - bridgeManager, - pipeWatcher, - injector: { - inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), - unload: vi.fn(), - }, - makeClient: () => { - const c = new FakeClient(); - clients.push(c); - return c as unknown as QqHookClient; - }, - autoLoadOnDiscovery: true, - listProcesses: () => [{ pid: PID, name: 'qq', path: '' }], - }); - - // Initial discovery + first connect. - await pipeWatcher.start(); - await flush(); - await flush(); - - // Drive 50 pipe up/down cycles with the QQ process staying alive but - // the pipe (= QQ control socket) bouncing every "tick". - const CYCLES = 50; - for (let i = 0; i < CYCLES; i++) { - liveSet.delete(PID); - await pipeWatcher.tickNow(); - await flush(); - liveSet.add(PID); - await pipeWatcher.tickNow(); - await flush(); - } - - // The "QQ never logs in" hypothesis: BridgeManager should never have - // been told about a login or a disconnect. - expect(bridgeManager.onHookLogin).not.toHaveBeenCalled(); - expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled(); - expect(bridgeManager.onPacket).not.toHaveBeenCalled(); - - // Hook layer should hold at most one live client. - const alive = clients.filter(c => !c.isClosed); - expect(alive.length, `live clients after ${CYCLES} cycles: ${alive.length}`).toBeLessThanOrEqual(1); - - // Total clients minted = roughly one per up cycle. Sanity bound: - // we must have actually exercised the reconnect path. - expect(clients.length).toBeGreaterThan(1); - - manager.dispose(); - }); }); diff --git a/packages/bridge/tests/hook-reconnect-no-login.test.ts b/packages/bridge/tests/hook-reconnect-no-login.test.ts index fc2f6d7d..3e996194 100644 --- a/packages/bridge/tests/hook-reconnect-no-login.test.ts +++ b/packages/bridge/tests/hook-reconnect-no-login.test.ts @@ -24,100 +24,119 @@ import type { QqHookClient } from '../src/qq-hook-client'; const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; class FakeClient extends EventEmitter { - isClosed = false; - isLoggedIn = false; - private loginState = { loggedIn: false, uin: '0', uinNumber: 0n }; + isClosed = false; + isLoggedIn = false; + private loginState = { loggedIn: false, uin: '0', uinNumber: 0n }; - async connectAll(_opts: { recv: boolean }): Promise { - if (this.isClosed) throw new Error('client is closed'); - } - getLoginState() { return { ...this.loginState }; } - close(): void { - if (this.isClosed) return; - this.isClosed = true; - this.emit('close'); - } + async connectAll(_opts: { recv: boolean }): Promise { + if (this.isClosed) { + throw new Error('client is closed'); + } + } + getLoginState() { + return { ...this.loginState }; + } + close(): void { + if (this.isClosed) { + return; + } + + this.isClosed = true; + this.emit('close'); + } } function totalListenerCount(emitter: EventEmitter): number { - return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0); + return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0); } -const flush = () => new Promise(r => setImmediate(r)); +const flush = () => new Promise((r) => setImmediate(r)); describe('HookSession — pipe reconnect with QQ never logging in', () => { - it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => { - let pipeLive = true; - const clients: FakeClient[] = []; - const session = new HookSession(61, { - injector: { - inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), - unload: vi.fn(), - }, - makeClient: () => { - const c = new FakeClient(); - clients.push(c); - return c as unknown as QqHookClient; - }, - pipeWatcher: { isPipeLive: () => pipeLive }, + it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => { + let pipeLive = true; + const clients: FakeClient[] = []; + const session = new HookSession(61, { + injector: { + inject: vi.fn(() => ({ + method: 'loadModuleManual' as const, + handle: DUMMY_HANDLE, + })), + unload: vi.fn(), + }, + makeClient: () => { + const c = new FakeClient(); + clients.push(c); + return c as unknown as QqHookClient; + }, + pipeWatcher: { isPipeLive: () => pipeLive }, + }); + + await session.load(); + session.onPipeUp(); + await flush(); + + const CYCLES = 50; + + for (let i = 0; i < CYCLES; i++) { + pipeLive = false; + session.onPipeDown(); + await flush(); + pipeLive = true; + session.onPipeUp(); + await flush(); + } + + const alive = clients.filter((c) => !c.isClosed); + expect.soft(clients.length).toBeGreaterThan(1); + expect( + alive.length, + `expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`, + ).toBeLessThanOrEqual(1); }); - await session.load(); - session.onPipeUp(); - await flush(); + it('drops all listeners from each torn-down client', async () => { + let pipeLive = true; + const clients: FakeClient[] = []; + const session = new HookSession(61, { + injector: { + inject: vi.fn(() => ({ + method: 'loadModuleManual' as const, + handle: DUMMY_HANDLE, + })), + unload: vi.fn(), + }, + makeClient: () => { + const c = new FakeClient(); + clients.push(c); + return c as unknown as QqHookClient; + }, + pipeWatcher: { isPipeLive: () => pipeLive }, + }); - const CYCLES = 50; - for (let i = 0; i < CYCLES; i++) { - pipeLive = false; - session.onPipeDown(); - await flush(); - pipeLive = true; - session.onPipeUp(); - await flush(); - } + await session.load(); + session.onPipeUp(); + await flush(); - const alive = clients.filter(c => !c.isClosed); - expect.soft(clients.length).toBeGreaterThan(1); - expect(alive.length, `expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`) - .toBeLessThanOrEqual(1); - }); + const CYCLES = 20; - it('drops all listeners from each torn-down client', async () => { - let pipeLive = true; - const clients: FakeClient[] = []; - const session = new HookSession(61, { - injector: { - inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), - unload: vi.fn(), - }, - makeClient: () => { - const c = new FakeClient(); - clients.push(c); - return c as unknown as QqHookClient; - }, - pipeWatcher: { isPipeLive: () => pipeLive }, + for (let i = 0; i < CYCLES; i++) { + pipeLive = false; + session.onPipeDown(); + await flush(); + pipeLive = true; + session.onPipeUp(); + await flush(); + } + + // Every client except the current one should have 0 listeners attached. + // (HookSession.tearDownClient does client.removeAllListeners().) + for (let i = 0; i < clients.length - 1; i++) { + const lc = totalListenerCount(clients[i]); + expect( + lc, + `client #${i} of ${clients.length} still has ${lc} listeners after teardown`, + ).toBe(0); + } }); - - await session.load(); - session.onPipeUp(); - await flush(); - - const CYCLES = 20; - for (let i = 0; i < CYCLES; i++) { - pipeLive = false; - session.onPipeDown(); - await flush(); - pipeLive = true; - session.onPipeUp(); - await flush(); - } - - // Every client except the current one should have 0 listeners attached. - // (HookSession.tearDownClient does client.removeAllListeners().) - for (let i = 0; i < clients.length - 1; i++) { - const lc = totalListenerCount(clients[i]); - expect(lc, `client #${i} of ${clients.length} still has ${lc} listeners after teardown`) - .toBe(0); - } - }); }); diff --git a/packages/bridge/tests/hook-runtime-dir.test.ts b/packages/bridge/tests/hook-runtime-dir.test.ts index f8a6e14b..29a8f72a 100644 --- a/packages/bridge/tests/hook-runtime-dir.test.ts +++ b/packages/bridge/tests/hook-runtime-dir.test.ts @@ -2,66 +2,84 @@ import { describe, expect, it } from 'vitest'; import { resolveHookRuntimeDir } from '../src/hook-runtime-dir'; function procReader(files: Record) { - return (file: string): string => { - const value = files[file]; - if (value === undefined) throw new Error(`missing fixture: ${file}`); - return value; - }; + return (file: string): string => { + const value = files[file]; + + if (value === undefined) { + throw new Error(`missing fixture: ${file}`); + } + + return value; + }; } describe('resolveHookRuntimeDir — Linux target process ownership', () => { - it('uses the QQ process runtime directory instead of the supervisor user directory', () => { - expect(resolveHookRuntimeDir(46301, { - platform: 'linux', - env: { XDG_RUNTIME_DIR: '/run/user/0' }, - ownUid: 0, - readText: procReader({ - '/proc/46301/environ': 'HOME=/home/rikka\0XDG_RUNTIME_DIR=/run/user/1000\0', - '/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n', - }), - })).toBe('/run/user/1000'); - }); + it('uses the QQ process runtime directory instead of the supervisor user directory', () => { + expect( + resolveHookRuntimeDir(46301, { + platform: 'linux', + env: { XDG_RUNTIME_DIR: '/run/user/0' }, + ownUid: 0, + readText: procReader({ + '/proc/46301/environ': 'HOME=/home/rikka\0XDG_RUNTIME_DIR=/run/user/1000\0', + '/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n', + }), + }), + ).toBe('/run/user/1000'); + }); - it('falls back to the QQ process uid when its environment has no runtime directory', () => { - expect(resolveHookRuntimeDir(46301, { - platform: 'linux', - env: { XDG_RUNTIME_DIR: '/run/user/0' }, - ownUid: 0, - readText: procReader({ - '/proc/46301/environ': 'HOME=/home/rikka\0', - '/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n', - }), - })).toBe('/tmp/snowluma-1000'); - }); + it('falls back to the QQ process uid when its environment has no runtime directory', () => { + expect( + resolveHookRuntimeDir(46301, { + platform: 'linux', + env: { XDG_RUNTIME_DIR: '/run/user/0' }, + ownUid: 0, + readText: procReader({ + '/proc/46301/environ': 'HOME=/home/rikka\0', + '/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n', + }), + }), + ).toBe('/tmp/snowluma-1000'); + }); - it('fails visibly when target ownership cannot be determined', () => { - expect(() => resolveHookRuntimeDir(46301, { - platform: 'linux', - env: { XDG_RUNTIME_DIR: '/run/user/0' }, - ownUid: 0, - readText: () => { throw new Error('permission denied'); }, - })).toThrow(/cannot resolve hook runtime directory.*permission denied/); - }); + it('fails visibly when target ownership cannot be determined', () => { + expect(() => + resolveHookRuntimeDir(46301, { + platform: 'linux', + env: { XDG_RUNTIME_DIR: '/run/user/0' }, + ownUid: 0, + readText: () => { + throw new Error('permission denied'); + }, + }), + ).toThrow(/cannot resolve hook runtime directory.*permission denied/); + }); - it('uses the current convention when the target disappears during discovery', () => { - const gone = Object.assign(new Error('process disappeared'), { code: 'ENOENT' }); - expect(resolveHookRuntimeDir(46301, { - platform: 'linux', - env: { XDG_RUNTIME_DIR: '/run/user/0' }, - ownUid: 0, - readText: () => { throw gone; }, - })).toBe('/run/user/0'); - }); + it('uses the current convention when the target disappears during discovery', () => { + const gone = Object.assign(new Error('process disappeared'), { code: 'ENOENT' }); + expect( + resolveHookRuntimeDir(46301, { + platform: 'linux', + env: { XDG_RUNTIME_DIR: '/run/user/0' }, + ownUid: 0, + readText: () => { + throw gone; + }, + }), + ).toBe('/run/user/0'); + }); - it('honours an explicit runtime directory inherited by the QQ process', () => { - expect(resolveHookRuntimeDir(46301, { - platform: 'linux', - env: {}, - ownUid: 0, - readText: procReader({ - '/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0', - '/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n', - }), - })).toBe('/srv/snowluma-hook'); - }); + it('honours an explicit runtime directory inherited by the QQ process', () => { + expect( + resolveHookRuntimeDir(46301, { + platform: 'linux', + env: {}, + ownUid: 0, + readText: procReader({ + '/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0', + '/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n', + }), + }), + ).toBe('/srv/snowluma-hook'); + }); }); diff --git a/packages/bridge/tests/hook-session.test.ts b/packages/bridge/tests/hook-session.test.ts index 89267e14..404f56ad 100644 --- a/packages/bridge/tests/hook-session.test.ts +++ b/packages/bridge/tests/hook-session.test.ts @@ -3,31 +3,24 @@ import { EventEmitter } from 'events'; import { HookSession } from '../src/hook-session'; import type { ManualMapHandle } from '../src/injector'; import { - HookPipeRequestError, - PIPE_STATUS_CONNECTION_UNAVAILABLE, - type QqHookClient, - type QqHookPacket, + HookPipeRequestError, + PIPE_STATUS_CONNECTION_UNAVAILABLE, + type QqHookClient, + type QqHookPacket, } from '../src/qq-hook-client'; import type { QqPortLoginInfo } from '../src/qq-port-probe'; import type { PacketSender } from '@snowluma/common/packet-sender'; import type { PacketSink } from '@snowluma/common/protocol-types'; -import { - getLogLevel, - setLogLevel, - subscribeLogs, - type LogEntry, -} from '@snowluma/common/logger'; +import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger'; const previousLogLevel = getLogLevel(); function sessionTrace(entries: LogEntry[]): LogEntry[] { - return entries.filter( - (entry) => entry.level === 'trace' && entry.scope === 'HookSession', - ); + return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'HookSession'); } afterEach(() => { - setLogLevel(previousLogLevel); + setLogLevel(previousLogLevel); }); const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; @@ -35,1285 +28,1415 @@ const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, /** Minimal stand-in for QqHookClient. Tests drive login/packet/error/close * events directly via fire* helpers. connectAll succeeds unless told otherwise. */ class FakeClient extends EventEmitter { - isClosed = false; - isLoggedIn = false; - shouldFailConnect = false; - nativeReadyOnIdentityHint = false; - identityHintFailures = 0; - sendError: Error | null = null; - readonly sentPackets: Array<{ serviceCmd: string; body: Buffer }> = []; - readonly loginIdentityHints: string[] = []; - private loginState = { loggedIn: false, uin: '0', uinNumber: 0n }; + isClosed = false; + isLoggedIn = false; + shouldFailConnect = false; + nativeReadyOnIdentityHint = false; + identityHintFailures = 0; + sendError: Error | null = null; + readonly sentPackets: Array<{ serviceCmd: string; body: Buffer }> = []; + readonly loginIdentityHints: string[] = []; + private loginState = { loggedIn: false, uin: '0', uinNumber: 0n }; - async connectAll(_opts: { recv: boolean }): Promise { - if (this.shouldFailConnect) throw new Error('connect failed'); - if (this.isClosed) throw new Error('client is closed'); - } - getLoginState() { return { ...this.loginState }; } - reconcileLoginState(state: { loggedIn: boolean; uin: string; uinNumber: bigint }): void { - this.isLoggedIn = state.loggedIn; - this.loginState = { ...state }; - this.emit('loginState', { ...this.loginState }); - } - async reconcileLoginIdentity(uin: string): Promise { - this.loginIdentityHints.push(uin); - if (this.identityHintFailures > 0) { - this.identityHintFailures--; - throw new Error('identity hint unavailable'); + async connectAll(_opts: { recv: boolean }): Promise { + if (this.shouldFailConnect) { + throw new Error('connect failed'); + } + + if (this.isClosed) { + throw new Error('client is closed'); + } } - if (this.nativeReadyOnIdentityHint) this.fireLogin(uin); - } - async send(serviceCmd: string, body: Buffer) { - if (this.sendError) throw this.sendError; - this.sentPackets.push({ serviceCmd, body: Buffer.from(body) }); - return { - requestId: this.sentPackets.length, - error: 0, - message: '', - body: Buffer.from('reply'), + getLoginState() { + return { ...this.loginState }; + } + reconcileLoginState(state: { loggedIn: boolean; uin: string; uinNumber: bigint }): void { + this.isLoggedIn = state.loggedIn; + this.loginState = { ...state }; + this.emit('loginState', { ...this.loginState }); + } + async reconcileLoginIdentity(uin: string): Promise { + this.loginIdentityHints.push(uin); + + if (this.identityHintFailures > 0) { + this.identityHintFailures--; + throw new Error('identity hint unavailable'); + } + + if (this.nativeReadyOnIdentityHint) { + this.fireLogin(uin); + } + } + async send(serviceCmd: string, body: Buffer) { + if (this.sendError) { + throw this.sendError; + } + + this.sentPackets.push({ serviceCmd, body: Buffer.from(body) }); + return { + requestId: this.sentPackets.length, + error: 0, + message: '', + body: Buffer.from('reply'), + }; + } + close(): void { + if (this.isClosed) { + return; + } + + this.isClosed = true; + this.emit('close'); + } + + fireLogin(uin: string): void { + this.reconcileLoginState({ loggedIn: true, uin, uinNumber: BigInt(uin) }); + } + + firePacket(packet: QqHookPacket): void { + this.emit('packet', packet); + } +} + +function makeSession( + opts: { + pid?: number; + pipeLive?: boolean; + clientFailsConnect?: boolean; + onPacket?: PacketSink; + probeLogin?: (pid: number) => Promise; + nativeReadyOnIdentityHint?: boolean; + identityHintFailures?: number; + } = {}, +) { + const pid = opts.pid ?? 1234; + let pipeLive = opts.pipeLive ?? false; + const clients: FakeClient[] = []; + const injector = { + inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), + unload: vi.fn(), }; - } - close(): void { - if (this.isClosed) return; - this.isClosed = true; - this.emit('close'); - } + // Default probe exposes no identity so the reconcile safety net is inert + // unless a test opts into a known account. + const probeLogin = + opts.probeLogin ?? (async () => ({ port: 0, uin: '', identityKnown: false })); - fireLogin(uin: string): void { - this.reconcileLoginState({ loggedIn: true, uin, uinNumber: BigInt(uin) }); - } + const session = new HookSession(pid, { + injector, + makeClient: () => { + const c = new FakeClient(); - firePacket(packet: QqHookPacket): void { - this.emit('packet', packet); - } + if (opts.clientFailsConnect) { + c.shouldFailConnect = true; + } + + c.nativeReadyOnIdentityHint = opts.nativeReadyOnIdentityHint ?? false; + c.identityHintFailures = opts.identityHintFailures ?? 0; + clients.push(c); + // Cast: FakeClient mirrors only the surface HookSession touches. + return c as unknown as QqHookClient; + }, + probeLogin, + pipeWatcher: { isPipeLive: () => pipeLive }, + onPacket: opts.onPacket, + }); + + return { + session, + injector, + clients, + currentClient: () => clients[clients.length - 1]!, + setPipeLive: (v: boolean) => { + pipeLive = v; + }, + }; } -function makeSession(opts: { - pid?: number; - pipeLive?: boolean; - clientFailsConnect?: boolean; - onPacket?: PacketSink; - probeLogin?: (pid: number) => Promise; - nativeReadyOnIdentityHint?: boolean; - identityHintFailures?: number; -} = {}) { - const pid = opts.pid ?? 1234; - let pipeLive = opts.pipeLive ?? false; - const clients: FakeClient[] = []; - const injector = { - inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), - unload: vi.fn(), - }; - // Default probe exposes no identity so the reconcile safety net is inert - // unless a test opts into a known account. - const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', identityKnown: false })); - - const session = new HookSession(pid, { - injector, - makeClient: () => { - const c = new FakeClient(); - if (opts.clientFailsConnect) c.shouldFailConnect = true; - c.nativeReadyOnIdentityHint = opts.nativeReadyOnIdentityHint ?? false; - c.identityHintFailures = opts.identityHintFailures ?? 0; - clients.push(c); - // Cast: FakeClient mirrors only the surface HookSession touches. - return c as unknown as QqHookClient; - }, - probeLogin, - pipeWatcher: { isPipeLive: () => pipeLive }, - onPacket: opts.onPacket, - }); - - return { - session, - injector, - clients, - currentClient: () => clients[clients.length - 1]!, - setPipeLive: (v: boolean) => { pipeLive = v; }, - }; -} - -const flush = () => new Promise(r => setImmediate(r)); +const flush = () => new Promise((r) => setImmediate(r)); describe('HookSession — runtime TRACE', () => { - it('records injection and existing-pipe load branches with unique terminals', async () => { - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - try { - const injected = makeSession({ pid: 7101, pipeLive: false }); - const reconnect = makeSession({ pid: 7102, pipeLive: true }); - await injected.session.load(); - await reconnect.session.load(); + it('records injection and existing-pipe load branches with unique terminals', async () => { + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const messages = sessionTrace(entries).map((entry) => entry.message); - expect(messages).toEqual(expect.arrayContaining([ - expect.stringContaining('hook_session_start pid=7101 operation=load'), - 'hook_session_branch pid=7101 operation=load branch=inject_begin', - 'hook_session_branch pid=7101 operation=load branch=inject_completed method="loadModuleManual"', - expect.stringMatching(/^hook_session_terminal pid=7101 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/), - expect.stringContaining('hook_session_start pid=7102 operation=load'), - 'hook_session_branch pid=7102 operation=load branch=existing_pipe method="reconnect"', - expect.stringMatching(/^hook_session_terminal pid=7102 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/), - ])); - for (const pid of [7101, 7102]) { - expect(messages.filter( - (message) => message.startsWith(`hook_session_terminal pid=${pid} operation=load `), - )).toHaveLength(1); - } - } finally { - unsubscribe(); - } - }); + try { + const injected = makeSession({ pid: 7101, pipeLive: false }); + const reconnect = makeSession({ pid: 7102, pipeLive: true }); + await injected.session.load(); + await reconnect.session.load(); - it('records load and connection failures with truthful settled state', async () => { - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - try { - const injector = { - inject: vi.fn(() => { throw new Error('fixture inject failure'); }), - unload: vi.fn(), - }; - const failedLoad = new HookSession(7103, { - injector, - makeClient: () => new FakeClient() as unknown as QqHookClient, - pipeWatcher: { isPipeLive: () => false }, - }); - await failedLoad.load(); + const messages = sessionTrace(entries).map((entry) => entry.message); + expect(messages).toEqual( + expect.arrayContaining([ + expect.stringContaining('hook_session_start pid=7101 operation=load'), + 'hook_session_branch pid=7101 operation=load branch=inject_begin', + 'hook_session_branch pid=7101 operation=load branch=inject_completed method="loadModuleManual"', + expect.stringMatching( + /^hook_session_terminal pid=7101 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/, + ), + expect.stringContaining('hook_session_start pid=7102 operation=load'), + 'hook_session_branch pid=7102 operation=load branch=existing_pipe method="reconnect"', + expect.stringMatching( + /^hook_session_terminal pid=7102 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/, + ), + ]), + ); - const failedConnect = makeSession({ - pid: 7104, - pipeLive: true, - clientFailsConnect: true, - }); - await failedConnect.session.load(); - failedConnect.session.onPipeUp(); - await flush(); - - const messages = sessionTrace(entries).map((entry) => entry.message); - expect(messages).toEqual(expect.arrayContaining([ - expect.stringMatching(/^hook_session_terminal pid=7103 operation=load outcome=failed reason=load_failed error="fixture inject failure" state=.*elapsedMs=\d+$/), - expect.stringContaining('hook_session_connect_start pid=7104'), - expect.stringMatching(/^hook_session_connect_terminal pid=7104 outcome=failed reason=connect_failed error="connect failed" state=.*elapsedMs=\d+$/), - ])); - expect(messages.filter( - (message) => message.startsWith('hook_session_connect_terminal pid=7104 '), - )).toHaveLength(1); - } finally { - unsubscribe(); - } - }); - - it('connects when load fails but the pipe is already up', async () => { - let pipeLive = false; - const clients: FakeClient[] = []; - const session = new HookSession(7108, { - injector: { - inject: () => { - pipeLive = true; - throw new Error('component loading failed [COMPONENT_LOAD_FAILED]'); - }, - unload: () => undefined, - }, - makeClient: () => { - const client = new FakeClient(); - client.fireLogin('10001'); - clients.push(client); - return client as unknown as QqHookClient; - }, - pipeWatcher: { - isPipeLive: () => pipeLive, - tickNow: async () => undefined, - }, + for (const pid of [7101, 7102]) { + expect( + messages.filter((message) => + message.startsWith(`hook_session_terminal pid=${pid} operation=load `), + ), + ).toHaveLength(1); + } + } finally { + unsubscribe(); + } }); - const info = await session.load(); - expect(info.status).toBe('online'); - expect(info.uin).toBe('10001'); - expect(info.connected).toBe(true); - expect(clients).toHaveLength(1); - }); - it('records login, disconnect, and process-gone only when state changes', async () => { - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const ctx = makeSession({ pid: 7105, pipeLive: true }); - try { - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); - ctx.currentClient().fireLogin('10001'); - ctx.session.onPipeDown(); - await flush(); - ctx.session.onPipeDown(); - await flush(); - ctx.session.notifyProcessGone(); - await flush(); + it('records load and connection failures with truthful settled state', async () => { + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const messages = sessionTrace(entries).map((entry) => entry.message); - expect(messages.filter( - (message) => message.startsWith('hook_session_login_terminal pid=7105 '), - )).toHaveLength(1); - expect(messages.filter( - (message) => message.startsWith('hook_session_disconnect_terminal pid=7105 '), - )).toHaveLength(1); - expect(messages.filter( - (message) => message.startsWith('hook_session_process_terminal pid=7105 '), - )).toHaveLength(1); - expect(messages).toEqual(expect.arrayContaining([ - expect.stringMatching(/^hook_session_login_terminal pid=7105 outcome=completed reason=login_detected previousUin="0" uin="10001" state=.*elapsedMs=\d+$/), - expect.stringMatching(/^hook_session_disconnect_terminal pid=7105 outcome=completed reason=pipe_down wasLoggedIn=true state=.*elapsedMs=\d+$/), - expect.stringMatching(/^hook_session_process_terminal pid=7105 outcome=completed reason=process_gone wasLoggedIn=false state=.*elapsedMs=\d+$/), - ])); - } finally { - unsubscribe(); - ctx.session.dispose(); - } - }); + try { + const injector = { + inject: vi.fn(() => { + throw new Error('fixture inject failure'); + }), + unload: vi.fn(), + }; + const failedLoad = new HookSession(7103, { + injector, + makeClient: () => new FakeClient() as unknown as QqHookClient, + pipeWatcher: { isPipeLive: () => false }, + }); + await failedLoad.load(); - it('records failed terminals when lifecycle listeners throw', async () => { - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const login = makeSession({ pid: 7107, pipeLive: true }); - const disconnect = makeSession({ pid: 7108, pipeLive: true }); - const processGone = makeSession({ pid: 7109, pipeLive: true }); - try { - await login.session.load(); - login.session.onPipeUp(); - await flush(); - login.session.on('login', () => { throw new Error('login listener boom'); }); - expect(() => login.currentClient().fireLogin('10001')).toThrow('login listener boom'); + const failedConnect = makeSession({ + pid: 7104, + pipeLive: true, + clientFailsConnect: true, + }); + await failedConnect.session.load(); + failedConnect.session.onPipeUp(); + await flush(); - await disconnect.session.load(); - disconnect.session.onPipeUp(); - await flush(); - disconnect.currentClient().fireLogin('10002'); - disconnect.session.on('disconnected', () => { throw new Error('disconnect listener boom'); }); - disconnect.session.onPipeDown(); - await flush(); + const messages = sessionTrace(entries).map((entry) => entry.message); + expect(messages).toEqual( + expect.arrayContaining([ + expect.stringMatching( + /^hook_session_terminal pid=7103 operation=load outcome=failed reason=load_failed error="fixture inject failure" state=.*elapsedMs=\d+$/, + ), + expect.stringContaining('hook_session_connect_start pid=7104'), + expect.stringMatching( + /^hook_session_connect_terminal pid=7104 outcome=failed reason=connect_failed error="connect failed" state=.*elapsedMs=\d+$/, + ), + ]), + ); + expect( + messages.filter((message) => + message.startsWith('hook_session_connect_terminal pid=7104 '), + ), + ).toHaveLength(1); + } finally { + unsubscribe(); + } + }); - processGone.session.on('disposed', () => { throw new Error('dispose listener boom'); }); - processGone.session.notifyProcessGone(); - await flush(); + it('connects when load fails but the pipe is already up', async () => { + let pipeLive = false; + const clients: FakeClient[] = []; + const session = new HookSession(7108, { + injector: { + inject: () => { + pipeLive = true; + throw new Error('component loading failed [COMPONENT_LOAD_FAILED]'); + }, + unload: () => undefined, + }, + makeClient: () => { + const client = new FakeClient(); + client.fireLogin('10001'); + clients.push(client); + return client as unknown as QqHookClient; + }, + pipeWatcher: { + isPipeLive: () => pipeLive, + tickNow: async () => undefined, + }, + }); + const info = await session.load(); + expect(info.status).toBe('online'); + expect(info.uin).toBe('10001'); + expect(info.connected).toBe(true); + expect(clients).toHaveLength(1); + }); - const messages = sessionTrace(entries).map((entry) => entry.message); - expect(messages.filter((message) => - message.startsWith('hook_session_login_terminal pid=7107 '))).toEqual([ - expect.stringMatching(/^hook_session_login_terminal pid=7107 outcome=failed reason=listener_failed error="login listener boom" state=.*elapsedMs=\d+$/), - ]); - expect(messages.filter((message) => - message.startsWith('hook_session_disconnect_terminal pid=7108 '))).toEqual([ - expect.stringMatching(/^hook_session_disconnect_terminal pid=7108 outcome=failed reason=listener_failed error="disconnect listener boom" state=.*elapsedMs=\d+$/), - ]); - expect(messages.filter((message) => - message.startsWith('hook_session_process_terminal pid=7109 '))).toEqual([ - expect.stringMatching(/^hook_session_process_terminal pid=7109 outcome=failed reason=listener_failed error="dispose listener boom" state=.*elapsedMs=\d+$/), - ]); - } finally { - unsubscribe(); - login.session.dispose(); - disconnect.session.dispose(); - processGone.session.dispose(); - } - }); + it('records login, disconnect, and process-gone only when state changes', async () => { + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const ctx = makeSession({ pid: 7105, pipeLive: true }); - it('records unload verification failure as a failed terminal', async () => { - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const ctx = makeSession({ pid: 7106, pipeLive: false }); - try { - await ctx.session.load(); - ctx.setPipeLive(true); - await ctx.session.unload(); + try { + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); + ctx.currentClient().fireLogin('10001'); + ctx.session.onPipeDown(); + await flush(); + ctx.session.onPipeDown(); + await flush(); + ctx.session.notifyProcessGone(); + await flush(); - const terminals = sessionTrace(entries).filter( - (entry) => entry.message.startsWith('hook_session_terminal pid=7106 operation=unload '), - ); - expect(terminals).toHaveLength(1); - expect(terminals[0]!.message).toMatch( - /^hook_session_terminal pid=7106 operation=unload outcome=failed reason=unload_verification_failed error=.*state=.*elapsedMs=\d+$/, - ); - } finally { - unsubscribe(); - } - }); + const messages = sessionTrace(entries).map((entry) => entry.message); + expect( + messages.filter((message) => + message.startsWith('hook_session_login_terminal pid=7105 '), + ), + ).toHaveLength(1); + expect( + messages.filter((message) => + message.startsWith('hook_session_disconnect_terminal pid=7105 '), + ), + ).toHaveLength(1); + expect( + messages.filter((message) => + message.startsWith('hook_session_process_terminal pid=7105 '), + ), + ).toHaveLength(1); + expect(messages).toEqual( + expect.arrayContaining([ + expect.stringMatching( + /^hook_session_login_terminal pid=7105 outcome=completed reason=login_detected previousUin="0" uin="10001" state=.*elapsedMs=\d+$/, + ), + expect.stringMatching( + /^hook_session_disconnect_terminal pid=7105 outcome=completed reason=pipe_down wasLoggedIn=true state=.*elapsedMs=\d+$/, + ), + expect.stringMatching( + /^hook_session_process_terminal pid=7105 outcome=completed reason=process_gone wasLoggedIn=false state=.*elapsedMs=\d+$/, + ), + ]), + ); + } finally { + unsubscribe(); + ctx.session.dispose(); + } + }); + + it('records failed terminals when lifecycle listeners throw', async () => { + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const login = makeSession({ pid: 7107, pipeLive: true }); + const disconnect = makeSession({ pid: 7108, pipeLive: true }); + const processGone = makeSession({ pid: 7109, pipeLive: true }); + + try { + await login.session.load(); + login.session.onPipeUp(); + await flush(); + login.session.on('login', () => { + throw new Error('login listener boom'); + }); + expect(() => login.currentClient().fireLogin('10001')).toThrow('login listener boom'); + + await disconnect.session.load(); + disconnect.session.onPipeUp(); + await flush(); + disconnect.currentClient().fireLogin('10002'); + disconnect.session.on('disconnected', () => { + throw new Error('disconnect listener boom'); + }); + disconnect.session.onPipeDown(); + await flush(); + + processGone.session.on('disposed', () => { + throw new Error('dispose listener boom'); + }); + processGone.session.notifyProcessGone(); + await flush(); + + const messages = sessionTrace(entries).map((entry) => entry.message); + expect( + messages.filter((message) => + message.startsWith('hook_session_login_terminal pid=7107 '), + ), + ).toEqual([ + expect.stringMatching( + /^hook_session_login_terminal pid=7107 outcome=failed reason=listener_failed error="login listener boom" state=.*elapsedMs=\d+$/, + ), + ]); + expect( + messages.filter((message) => + message.startsWith('hook_session_disconnect_terminal pid=7108 '), + ), + ).toEqual([ + expect.stringMatching( + /^hook_session_disconnect_terminal pid=7108 outcome=failed reason=listener_failed error="disconnect listener boom" state=.*elapsedMs=\d+$/, + ), + ]); + expect( + messages.filter((message) => + message.startsWith('hook_session_process_terminal pid=7109 '), + ), + ).toEqual([ + expect.stringMatching( + /^hook_session_process_terminal pid=7109 outcome=failed reason=listener_failed error="dispose listener boom" state=.*elapsedMs=\d+$/, + ), + ]); + } finally { + unsubscribe(); + login.session.dispose(); + disconnect.session.dispose(); + processGone.session.dispose(); + } + }); + + it('records unload verification failure as a failed terminal', async () => { + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const ctx = makeSession({ pid: 7106, pipeLive: false }); + + try { + await ctx.session.load(); + ctx.setPipeLive(true); + await ctx.session.unload(); + + const terminals = sessionTrace(entries).filter((entry) => + entry.message.startsWith('hook_session_terminal pid=7106 operation=unload '), + ); + expect(terminals).toHaveLength(1); + expect(terminals[0]!.message).toMatch( + /^hook_session_terminal pid=7106 operation=unload outcome=failed reason=unload_verification_failed error=.*state=.*elapsedMs=\d+$/, + ); + } finally { + unsubscribe(); + } + }); }); describe('HookSession — load', () => { - it('with no live pipe: injects, status → connecting, method from inject result', async () => { - const { session, injector } = makeSession({ pipeLive: false }); - const info = await session.load(); + it('with no live pipe: injects, status → connecting, method from inject result', async () => { + const { session, injector } = makeSession({ pipeLive: false }); + const info = await session.load(); - expect(injector.inject).toHaveBeenCalledOnce(); - expect(info.status).toBe('connecting'); - expect(info.method).toBe('loadModuleManual'); - expect(info.injected).toBe(true); - }); - - it('fast-path: pipe already live → skip inject, method → "reconnect"', async () => { - const { session, injector } = makeSession({ pipeLive: true }); - const info = await session.load(); - - expect(injector.inject).not.toHaveBeenCalled(); - expect(info.method).toBe('reconnect'); - expect(info.injected).toBe(true); - expect(info.status).toBe('connecting'); - }); - - it('keeps loading pending until asynchronous component loading completes', async () => { - let finishLoading!: (result: { method: 'loadModuleManual'; handle: ManualMapHandle }) => void; - const loading = new Promise<{ method: 'loadModuleManual'; handle: ManualMapHandle }>(resolve => { - finishLoading = resolve; - }); - const injector = { - inject: vi.fn(() => loading), - unload: vi.fn(), - }; - const session = new HookSession(1234, { - injector, - makeClient: () => new FakeClient() as unknown as QqHookClient, - pipeWatcher: { isPipeLive: () => false }, + expect(injector.inject).toHaveBeenCalledOnce(); + expect(info.status).toBe('connecting'); + expect(info.method).toBe('loadModuleManual'); + expect(info.injected).toBe(true); }); - const load = session.load(); - await flush(); + it('fast-path: pipe already live → skip inject, method → "reconnect"', async () => { + const { session, injector } = makeSession({ pipeLive: true }); + const info = await session.load(); - expect(session.status).toBe('loading'); - finishLoading({ method: 'loadModuleManual', handle: DUMMY_HANDLE }); - await expect(load).resolves.toMatchObject({ - status: 'connecting', - method: 'loadModuleManual', - injected: true, - }); - }); - - it('inject failure → status error, error message captured', async () => { - const injector = { - inject: vi.fn(() => { throw new Error('inject boom'); }), - unload: vi.fn(), - }; - const session = new HookSession(1234, { - injector, - makeClient: () => new FakeClient() as unknown as QqHookClient, - pipeWatcher: { isPipeLive: () => false }, - }); - const info = await session.load(); - expect(info.status).toBe('error'); - expect(info.error).toBe('inject boom'); - }); - - it('can retry after asynchronous component loading fails', async () => { - const injector = { - inject: vi - .fn() - .mockRejectedValueOnce(new Error('component loading timed out')) - .mockResolvedValueOnce({ - method: 'loadModuleManual' as const, - handle: DUMMY_HANDLE, - }), - unload: vi.fn(), - }; - const session = new HookSession(1234, { - injector, - makeClient: () => new FakeClient() as unknown as QqHookClient, - pipeWatcher: { isPipeLive: () => false }, + expect(injector.inject).not.toHaveBeenCalled(); + expect(info.method).toBe('reconnect'); + expect(info.injected).toBe(true); + expect(info.status).toBe('connecting'); }); - await expect(session.load()).resolves.toMatchObject({ - status: 'error', - error: 'component loading timed out', - injected: false, + it('keeps loading pending until asynchronous component loading completes', async () => { + let finishLoading!: (result: { + method: 'loadModuleManual'; + handle: ManualMapHandle; + }) => void; + const loading = new Promise<{ method: 'loadModuleManual'; handle: ManualMapHandle }>( + (resolve) => { + finishLoading = resolve; + }, + ); + const injector = { + inject: vi.fn(() => loading), + unload: vi.fn(), + }; + const session = new HookSession(1234, { + injector, + makeClient: () => new FakeClient() as unknown as QqHookClient, + pipeWatcher: { isPipeLive: () => false }, + }); + + const load = session.load(); + await flush(); + + expect(session.status).toBe('loading'); + finishLoading({ method: 'loadModuleManual', handle: DUMMY_HANDLE }); + await expect(load).resolves.toMatchObject({ + status: 'connecting', + method: 'loadModuleManual', + injected: true, + }); }); - await expect(session.load()).resolves.toMatchObject({ - status: 'connecting', - method: 'loadModuleManual', - injected: true, - error: '', + + it('inject failure → status error, error message captured', async () => { + const injector = { + inject: vi.fn(() => { + throw new Error('inject boom'); + }), + unload: vi.fn(), + }; + const session = new HookSession(1234, { + injector, + makeClient: () => new FakeClient() as unknown as QqHookClient, + pipeWatcher: { isPipeLive: () => false }, + }); + const info = await session.load(); + expect(info.status).toBe('error'); + expect(info.error).toBe('inject boom'); + }); + + it('can retry after asynchronous component loading fails', async () => { + const injector = { + inject: vi + .fn() + .mockRejectedValueOnce(new Error('component loading timed out')) + .mockResolvedValueOnce({ + method: 'loadModuleManual' as const, + handle: DUMMY_HANDLE, + }), + unload: vi.fn(), + }; + const session = new HookSession(1234, { + injector, + makeClient: () => new FakeClient() as unknown as QqHookClient, + pipeWatcher: { isPipeLive: () => false }, + }); + + await expect(session.load()).resolves.toMatchObject({ + status: 'error', + error: 'component loading timed out', + injected: false, + }); + await expect(session.load()).resolves.toMatchObject({ + status: 'connecting', + method: 'loadModuleManual', + injected: true, + error: '', + }); + expect(injector.inject).toHaveBeenCalledTimes(2); }); - expect(injector.inject).toHaveBeenCalledTimes(2); - }); }); describe('HookSession — pipe up/down → connect lifecycle', () => { - it('onPipeUp after load: client connects → status loaded', async () => { - const ctx = makeSession({ pipeLive: true }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); + it('onPipeUp after load: client connects → status loaded', async () => { + const ctx = makeSession({ pipeLive: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); - expect(ctx.session.status).toBe('loaded'); - expect(ctx.clients).toHaveLength(1); - }); + expect(ctx.session.status).toBe('loaded'); + expect(ctx.clients).toHaveLength(1); + }); - it('emits "login" with (uin, sender) after client signals loggedIn', async () => { - const ctx = makeSession({ pipeLive: true }); - const loginSpy = vi.fn(); - ctx.session.on('login', loginSpy); + it('emits "login" with (uin, sender) after client signals loggedIn', async () => { + const ctx = makeSession({ pipeLive: true }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); - expect(loginSpy).toHaveBeenCalledOnce(); - const [uin, sender] = loginSpy.mock.calls[0]!; - expect(uin).toBe('10001'); - expect(typeof (sender as { sendPacket: unknown }).sendPacket).toBe('function'); - expect(ctx.session.status).toBe('online'); - expect(ctx.session.uin).toBe('10001'); - }); + expect(loginSpy).toHaveBeenCalledOnce(); + const [uin, sender] = loginSpy.mock.calls[0]!; + expect(uin).toBe('10001'); + expect(typeof (sender as { sendPacket: unknown }).sendPacket).toBe('function'); + expect(ctx.session.status).toBe('online'); + expect(ctx.session.uin).toBe('10001'); + }); - it('does not re-emit "login" on duplicate loginState with same uin', async () => { - const ctx = makeSession({ pipeLive: true }); - const loginSpy = vi.fn(); - ctx.session.on('login', loginSpy); + it('does not re-emit "login" on duplicate loginState with same uin', async () => { + const ctx = makeSession({ pipeLive: true }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); - ctx.currentClient().fireLogin('10001'); - ctx.currentClient().fireLogin('10001'); + ctx.currentClient().fireLogin('10001'); + ctx.currentClient().fireLogin('10001'); - expect(loginSpy).toHaveBeenCalledOnce(); - }); + expect(loginSpy).toHaveBeenCalledOnce(); + }); - it('connect failure: stays in connecting, error message captured (will retry on next tick)', async () => { - const ctx = makeSession({ pipeLive: true, clientFailsConnect: true }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); + it('connect failure: stays in connecting, error message captured (will retry on next tick)', async () => { + const ctx = makeSession({ pipeLive: true, clientFailsConnect: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); - expect(ctx.session.status).toBe('connecting'); - expect(ctx.session.error).toBe('connect failed'); - }); + expect(ctx.session.status).toBe('connecting'); + expect(ctx.session.error).toBe('connect failed'); + }); - it('onPipeDown while logged in: emits disconnected(true), status disconnected', async () => { - const ctx = makeSession({ pipeLive: true }); - const discSpy = vi.fn(); - ctx.session.on('disconnected', discSpy); + it('onPipeDown while logged in: emits disconnected(true), status disconnected', async () => { + const ctx = makeSession({ pipeLive: true }); + const discSpy = vi.fn(); + ctx.session.on('disconnected', discSpy); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); - ctx.session.onPipeDown(); - await flush(); + ctx.session.onPipeDown(); + await flush(); - expect(discSpy).toHaveBeenCalledWith(true); - expect(ctx.session.status).toBe('disconnected'); - }); + expect(discSpy).toHaveBeenCalledWith(true); + expect(ctx.session.status).toBe('disconnected'); + }); - it('onPipeDown while connected-but-not-logged-in: emits disconnected(false), status connecting', async () => { - const ctx = makeSession({ pipeLive: true }); - const discSpy = vi.fn(); - ctx.session.on('disconnected', discSpy); + it('onPipeDown while connected-but-not-logged-in: emits disconnected(false), status connecting', async () => { + const ctx = makeSession({ pipeLive: true }); + const discSpy = vi.fn(); + ctx.session.on('disconnected', discSpy); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - // No login fired — we're connected but not logged in. + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + // No login fired — we're connected but not logged in. - ctx.session.onPipeDown(); - await flush(); + ctx.session.onPipeDown(); + await flush(); - // disconnected(false) is currently NOT emitted — disconnect events are - // reserved for "we owe BridgeManager a disconnect notification". This - // preserves the original behaviour. - expect(discSpy).not.toHaveBeenCalled(); - expect(ctx.session.status).toBe('connecting'); - }); + // disconnected(false) is currently NOT emitted — disconnect events are + // reserved for "we owe BridgeManager a disconnect notification". This + // preserves the original behaviour. + expect(discSpy).not.toHaveBeenCalled(); + expect(ctx.session.status).toBe('connecting'); + }); - it('repeated pipe down → up cycles reach consistent state', async () => { - const ctx = makeSession({ pipeLive: true }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); - expect(ctx.session.status).toBe('online'); + it('repeated pipe down → up cycles reach consistent state', async () => { + const ctx = makeSession({ pipeLive: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); + expect(ctx.session.status).toBe('online'); - ctx.session.onPipeDown(); - await flush(); - expect(ctx.session.status).toBe('disconnected'); + ctx.session.onPipeDown(); + await flush(); + expect(ctx.session.status).toBe('disconnected'); - // Pipe returns — session builds a fresh client. - ctx.session.onPipeUp(); - await flush(); - expect(ctx.clients.length).toBeGreaterThan(1); - expect(ctx.session.status).toBe('loaded'); - }); + // Pipe returns — session builds a fresh client. + ctx.session.onPipeUp(); + await flush(); + expect(ctx.clients.length).toBeGreaterThan(1); + expect(ctx.session.status).toBe('loaded'); + }); }); describe('HookSession — unload', () => { - it('while logged in: emits disconnected(true), calls unload, status available', async () => { - const ctx = makeSession({ pipeLive: false }); - await ctx.session.load(); - ctx.setPipeLive(true); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); + it('while logged in: emits disconnected(true), calls unload, status available', async () => { + const ctx = makeSession({ pipeLive: false }); + await ctx.session.load(); + ctx.setPipeLive(true); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); - const discSpy = vi.fn(); - ctx.session.on('disconnected', discSpy); - ctx.setPipeLive(false); // unload verification will see the pipe gone + const discSpy = vi.fn(); + ctx.session.on('disconnected', discSpy); + ctx.setPipeLive(false); // unload verification will see the pipe gone - await ctx.session.unload(); + await ctx.session.unload(); - expect(discSpy).toHaveBeenCalledWith(true); - expect(ctx.injector.unload).toHaveBeenCalledOnce(); - expect(ctx.session.status).toBe('available'); - }); - - it('when pipe stays live after unload: status connecting with retry message', async () => { - const ctx = makeSession({ pipeLive: false }); - await ctx.session.load(); - // Simulate the unload-failed scenario: pipe is still up after unload. - ctx.setPipeLive(true); - - const info = await ctx.session.unload(); - - expect(info.status).toBe('connecting'); - expect(info.error).toContain('命名管道仍然存在'); - }); - - it('forces a fresh tick before verifying so a stale snapshot does not false-flag a successful unload', async () => { - // Reproduces the Windows-WebUI bug: PipeWatcher's cached snapshot is - // up to 1500ms stale, so right after a successful native unload the - // pre-fix code would read isPipeLive() == true and report failure - // even though the DLL is gone. With the fix, tickNow() refreshes - // the snapshot first and verification correctly sees the pipe down. - const pid = 5555; - let pipeLive = true; // initial cached state: pipe is live - const tickNow = vi.fn(async () => { pipeLive = false; }); // OS poll says: gone now - - const session = new HookSession(pid, { - injector: { - inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), - unload: vi.fn(), - }, - makeClient: () => new FakeClient() as unknown as QqHookClient, - pipeWatcher: { isPipeLive: () => pipeLive, tickNow }, + expect(discSpy).toHaveBeenCalledWith(true); + expect(ctx.injector.unload).toHaveBeenCalledOnce(); + expect(ctx.session.status).toBe('available'); }); - await session.load(); - pipeLive = true; // ensure the pre-check snapshot says "live" - const info = await session.unload(); + it('when pipe stays live after unload: status connecting with retry message', async () => { + const ctx = makeSession({ pipeLive: false }); + await ctx.session.load(); + // Simulate the unload-failed scenario: pipe is still up after unload. + ctx.setPipeLive(true); - expect(tickNow).toHaveBeenCalledOnce(); - expect(info.status).toBe('available'); - expect(info.error).toBe(''); - }); + const info = await ctx.session.unload(); + + expect(info.status).toBe('connecting'); + expect(info.error).toContain('命名管道仍然存在'); + }); + + it('forces a fresh tick before verifying so a stale snapshot does not false-flag a successful unload', async () => { + // Reproduces the Windows-WebUI bug: PipeWatcher's cached snapshot is + // up to 1500ms stale, so right after a successful native unload the + // pre-fix code would read isPipeLive() == true and report failure + // even though the DLL is gone. With the fix, tickNow() refreshes + // the snapshot first and verification correctly sees the pipe down. + const pid = 5555; + let pipeLive = true; // initial cached state: pipe is live + const tickNow = vi.fn(async () => { + pipeLive = false; + }); // OS poll says: gone now + + const session = new HookSession(pid, { + injector: { + inject: vi.fn(() => ({ + method: 'loadModuleManual' as const, + handle: DUMMY_HANDLE, + })), + unload: vi.fn(), + }, + makeClient: () => new FakeClient() as unknown as QqHookClient, + pipeWatcher: { isPipeLive: () => pipeLive, tickNow }, + }); + await session.load(); + pipeLive = true; // ensure the pre-check snapshot says "live" + + const info = await session.unload(); + + expect(tickNow).toHaveBeenCalledOnce(); + expect(info.status).toBe('available'); + expect(info.error).toBe(''); + }); }); describe('HookSession — serialization', () => { - it('user mashing load → unload → load runs in order, end state consistent', async () => { - const ctx = makeSession({ pipeLive: false }); + it('user mashing load → unload → load runs in order, end state consistent', async () => { + const ctx = makeSession({ pipeLive: false }); - const p1 = ctx.session.load(); - const p2 = ctx.session.unload(); - const p3 = ctx.session.load(); - await Promise.all([p1, p2, p3]); + const p1 = ctx.session.load(); + const p2 = ctx.session.unload(); + const p3 = ctx.session.load(); + await Promise.all([p1, p2, p3]); - expect(ctx.injector.inject).toHaveBeenCalledTimes(2); - expect(ctx.injector.unload).toHaveBeenCalledTimes(1); - expect(ctx.session.status).toBe('connecting'); - }); + expect(ctx.injector.inject).toHaveBeenCalledTimes(2); + expect(ctx.injector.unload).toHaveBeenCalledTimes(1); + expect(ctx.session.status).toBe('connecting'); + }); - it('onPipeUp queued behind in-flight load resolves correctly', async () => { - const ctx = makeSession({ pipeLive: true }); + it('onPipeUp queued behind in-flight load resolves correctly', async () => { + const ctx = makeSession({ pipeLive: true }); - const loadPromise = ctx.session.load(); - ctx.session.onPipeUp(); // queued behind load + const loadPromise = ctx.session.load(); + ctx.session.onPipeUp(); // queued behind load - await loadPromise; - await flush(); + await loadPromise; + await flush(); - expect(ctx.session.status).toBe('loaded'); - }); + expect(ctx.session.status).toBe('loaded'); + }); }); describe('HookSession — process gone', () => { - it('emits disconnected(true) then disposed when killed while logged in', async () => { - const ctx = makeSession({ pipeLive: true }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); + it('emits disconnected(true) then disposed when killed while logged in', async () => { + const ctx = makeSession({ pipeLive: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); - const events: string[] = []; - ctx.session.on('disconnected', () => events.push('disconnected')); - ctx.session.on('disposed', () => events.push('disposed')); + const events: string[] = []; + ctx.session.on('disconnected', () => events.push('disconnected')); + ctx.session.on('disposed', () => events.push('disposed')); - ctx.session.notifyProcessGone(); - await flush(); + ctx.session.notifyProcessGone(); + await flush(); - expect(events).toEqual(['disconnected', 'disposed']); - expect(ctx.session.isDisposed).toBe(true); - }); + expect(events).toEqual(['disconnected', 'disposed']); + expect(ctx.session.isDisposed).toBe(true); + }); - it('emits only disposed when killed before login', async () => { - const ctx = makeSession({ pipeLive: true }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); + it('emits only disposed when killed before login', async () => { + const ctx = makeSession({ pipeLive: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); - const events: string[] = []; - ctx.session.on('disconnected', () => events.push('disconnected')); - ctx.session.on('disposed', () => events.push('disposed')); + const events: string[] = []; + ctx.session.on('disconnected', () => events.push('disconnected')); + ctx.session.on('disposed', () => events.push('disposed')); - ctx.session.notifyProcessGone(); - await flush(); + ctx.session.notifyProcessGone(); + await flush(); - expect(events).toEqual(['disposed']); - }); + expect(events).toEqual(['disposed']); + }); }); describe('HookSession — dispose', () => { - it('emits disconnected(true) while logged in so BridgeManager can detach the PID', async () => { - const ctx = makeSession({ pipeLive: true }); - const discSpy = vi.fn(); - ctx.session.on('disconnected', discSpy); + it('emits disconnected(true) while logged in so BridgeManager can detach the PID', async () => { + const ctx = makeSession({ pipeLive: true }); + const discSpy = vi.fn(); + ctx.session.on('disconnected', discSpy); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); - ctx.session.dispose(); + ctx.session.dispose(); - expect(discSpy).toHaveBeenCalledOnce(); - expect(discSpy).toHaveBeenCalledWith(true); - expect(ctx.session.isDisposed).toBe(true); - }); + expect(discSpy).toHaveBeenCalledOnce(); + expect(discSpy).toHaveBeenCalledWith(true); + expect(ctx.session.isDisposed).toBe(true); + }); - it('does not emit disconnected when disposed before login', async () => { - const ctx = makeSession({ pipeLive: true }); - const discSpy = vi.fn(); - ctx.session.on('disconnected', discSpy); + it('does not emit disconnected when disposed before login', async () => { + const ctx = makeSession({ pipeLive: true }); + const discSpy = vi.fn(); + ctx.session.on('disconnected', discSpy); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); - ctx.session.dispose(); + ctx.session.dispose(); - expect(discSpy).not.toHaveBeenCalled(); - expect(ctx.session.isDisposed).toBe(true); - }); + expect(discSpy).not.toHaveBeenCalled(); + expect(ctx.session.isDisposed).toBe(true); + }); }); describe('HookSession — refresh drift fix', () => { - // refresh while the pipe is down on a connected-but-never-logged-in - // session now reports 'connecting' (matching what onPipeDown gives for the - // same state), not the old spurious 'disconnected'. Pre-refactor, refresh's - // down branch ignored wasLoggedIn and always reported 'disconnected'. + // refresh while the pipe is down on a connected-but-never-logged-in + // session now reports 'connecting' (matching what onPipeDown gives for the + // same state), not the old spurious 'disconnected'. Pre-refactor, refresh's + // down branch ignored wasLoggedIn and always reported 'disconnected'. - it('refresh-while-down + never logged in → connecting (not disconnected), no disconnect emit', async () => { - const ctx = makeSession({ pipeLive: true }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - expect(ctx.session.status).toBe('loaded'); // connected, never logged in + it('refresh-while-down + never logged in → connecting (not disconnected), no disconnect emit', async () => { + const ctx = makeSession({ pipeLive: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + expect(ctx.session.status).toBe('loaded'); // connected, never logged in - const discSpy = vi.fn(); - ctx.session.on('disconnected', discSpy); - ctx.setPipeLive(false); + const discSpy = vi.fn(); + ctx.session.on('disconnected', discSpy); + ctx.setPipeLive(false); - const info = await ctx.session.refresh(); + const info = await ctx.session.refresh(); - expect(info.status).toBe('connecting'); // drift fix: was 'disconnected' - expect(discSpy).not.toHaveBeenCalled(); // never logged in ⇒ nothing owed - }); + expect(info.status).toBe('connecting'); // drift fix: was 'disconnected' + expect(discSpy).not.toHaveBeenCalled(); // never logged in ⇒ nothing owed + }); - it('refresh-while-down after login still → disconnected + emits disconnected(true)', async () => { - // The flip is scoped to the never-logged-in case; a real session that - // had reached login must still settle to 'disconnected' and notify. - const ctx = makeSession({ pipeLive: true }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); - expect(ctx.session.status).toBe('online'); + it('refresh-while-down after login still → disconnected + emits disconnected(true)', async () => { + // The flip is scoped to the never-logged-in case; a real session that + // had reached login must still settle to 'disconnected' and notify. + const ctx = makeSession({ pipeLive: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); + expect(ctx.session.status).toBe('online'); - const discSpy = vi.fn(); - ctx.session.on('disconnected', discSpy); - ctx.setPipeLive(false); + const discSpy = vi.fn(); + ctx.session.on('disconnected', discSpy); + ctx.setPipeLive(false); - const info = await ctx.session.refresh(); + const info = await ctx.session.refresh(); - expect(info.status).toBe('disconnected'); - expect(discSpy).toHaveBeenCalledWith(true); - }); + expect(info.status).toBe('disconnected'); + expect(discSpy).toHaveBeenCalledWith(true); + }); }); describe('HookSession — pipe-down must not clobber a settled error', () => { - // Regression net for the phase-2 reconcilePipeDown !connected short-circuit: - // a pipe-down tick on a session that never reached a live connection must - // not wipe a diagnostic error or emit a spurious status-changed. + // Regression net for the phase-2 reconcilePipeDown !connected short-circuit: + // a pipe-down tick on a session that never reached a live connection must + // not wipe a diagnostic error or emit a spurious status-changed. - it('onPipeDown after a failed connect keeps the error and does not re-emit', async () => { - const ctx = makeSession({ pipeLive: true, clientFailsConnect: true }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - expect(ctx.session.status).toBe('connecting'); - expect(ctx.session.error).toBe('connect failed'); + it('onPipeDown after a failed connect keeps the error and does not re-emit', async () => { + const ctx = makeSession({ pipeLive: true, clientFailsConnect: true }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + expect(ctx.session.status).toBe('connecting'); + expect(ctx.session.error).toBe('connect failed'); - const statusSpy = vi.fn(); - ctx.session.on('status-changed', statusSpy); - ctx.session.onPipeDown(); - await flush(); + const statusSpy = vi.fn(); + ctx.session.on('status-changed', statusSpy); + ctx.session.onPipeDown(); + await flush(); - expect(ctx.session.status).toBe('connecting'); - expect(ctx.session.error).toBe('connect failed'); // not wiped to '' - expect(statusSpy).not.toHaveBeenCalled(); // no spurious emit - }); - - it('onPipeDown after a failed load leaves the error status intact', async () => { - const injector = { - inject: vi.fn(() => { throw new Error('inject boom'); }), - unload: vi.fn(), - }; - const session = new HookSession(1234, { - injector, - makeClient: () => new FakeClient() as unknown as QqHookClient, - pipeWatcher: { isPipeLive: () => false }, + expect(ctx.session.status).toBe('connecting'); + expect(ctx.session.error).toBe('connect failed'); // not wiped to '' + expect(statusSpy).not.toHaveBeenCalled(); // no spurious emit }); - await session.load(); - expect(session.status).toBe('error'); - expect(session.error).toBe('inject boom'); - session.onPipeDown(); - await flush(); + it('onPipeDown after a failed load leaves the error status intact', async () => { + const injector = { + inject: vi.fn(() => { + throw new Error('inject boom'); + }), + unload: vi.fn(), + }; + const session = new HookSession(1234, { + injector, + makeClient: () => new FakeClient() as unknown as QqHookClient, + pipeWatcher: { isPipeLive: () => false }, + }); + await session.load(); + expect(session.status).toBe('error'); + expect(session.error).toBe('inject boom'); - expect(session.status).toBe('error'); // not flipped to 'available' - expect(session.error).toBe('inject boom'); // not wiped - }); + session.onPipeDown(); + await flush(); + + expect(session.status).toBe('error'); // not flipped to 'available' + expect(session.error).toBe('inject boom'); // not wiped + }); }); describe('HookSession — packet forwarding', () => { - // These tests cover the field-rename + filter logic that used to live - // inside the deleted NtqqHandler.onHookPacket. Inlining it here means - // we can exercise the transformation with a plain vi.fn() sink, no - // event-emitter machinery required. + // These tests cover the field-rename + filter logic that used to live + // inside the deleted NtqqHandler.onHookPacket. Inlining it here means + // we can exercise the transformation with a plain vi.fn() sink, no + // event-emitter machinery required. - it('forwards parsed packets to onPacket sink with PacketInfo shape', async () => { - const onPacket = vi.fn(); - const ctx = makeSession({ pipeLive: true, onPacket }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); + it('forwards parsed packets to onPacket sink with PacketInfo shape', async () => { + const onPacket = vi.fn(); + const ctx = makeSession({ pipeLive: true, onPacket }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); - ctx.currentClient().firePacket({ - seq: 42, - error: 0, - cmd: 'trpc.msg.olpush.OlPushService.MsgPush', - uin: '10001', - body: Buffer.from([0x01, 0x02, 0x03]), + ctx.currentClient().firePacket({ + seq: 42, + error: 0, + cmd: 'trpc.msg.olpush.OlPushService.MsgPush', + uin: '10001', + body: Buffer.from([0x01, 0x02, 0x03]), + }); + + expect(onPacket).toHaveBeenCalledOnce(); + const pkt = onPacket.mock.calls[0]![0]; + expect(pkt).toMatchObject({ + pid: 1234, + uin: '10001', + serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush', + seqId: 42, + retCode: 0, + fromClient: false, + }); + expect(Buffer.isBuffer(pkt.body)).toBe(true); + expect([...pkt.body]).toEqual([1, 2, 3]); }); - expect(onPacket).toHaveBeenCalledOnce(); - const pkt = onPacket.mock.calls[0]![0]; - expect(pkt).toMatchObject({ - pid: 1234, - uin: '10001', - serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush', - seqId: 42, - retCode: 0, - fromClient: false, - }); - expect(Buffer.isBuffer(pkt.body)).toBe(true); - expect([...pkt.body]).toEqual([1, 2, 3]); - }); + it('falls back to session uin when packet.uin is empty', async () => { + const onPacket = vi.fn(); + const ctx = makeSession({ pipeLive: true, onPacket }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); - it('falls back to session uin when packet.uin is empty', async () => { - const onPacket = vi.fn(); - const ctx = makeSession({ pipeLive: true, onPacket }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); + ctx.currentClient().firePacket({ + seq: 1, + error: 0, + cmd: 'foo', + uin: '', + body: Buffer.alloc(0), + }); - ctx.currentClient().firePacket({ - seq: 1, error: 0, cmd: 'foo', uin: '', body: Buffer.alloc(0), + expect(onPacket.mock.calls[0]![0].uin).toBe('10001'); }); - expect(onPacket.mock.calls[0]![0].uin).toBe('10001'); - }); + it('drops packets received before login', async () => { + const onPacket = vi.fn(); + const ctx = makeSession({ pipeLive: true, onPacket }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + // No login fired yet. - it('drops packets received before login', async () => { - const onPacket = vi.fn(); - const ctx = makeSession({ pipeLive: true, onPacket }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - // No login fired yet. + ctx.currentClient().firePacket({ + seq: 1, + error: 0, + cmd: 'foo', + uin: '10001', + body: Buffer.alloc(0), + }); - ctx.currentClient().firePacket({ - seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.alloc(0), + expect(onPacket).not.toHaveBeenCalled(); }); - expect(onPacket).not.toHaveBeenCalled(); - }); + it('drops packets whose uin is non-real ("0" / too short / non-numeric)', async () => { + const onPacket = vi.fn(); + const ctx = makeSession({ pipeLive: true, onPacket }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); - it('drops packets whose uin is non-real ("0" / too short / non-numeric)', async () => { - const onPacket = vi.fn(); - const ctx = makeSession({ pipeLive: true, onPacket }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); + // Packet uin '0' falls back to session uin '10001' — that one passes. + // Force a bad uin via the packet AND null out session uin by simulating + // a logout? Simpler: send a packet with uin '42' (numeric but <5 chars). + ctx.currentClient().firePacket({ + seq: 1, + error: 0, + cmd: 'foo', + uin: '42', + body: Buffer.alloc(0), + }); - // Packet uin '0' falls back to session uin '10001' — that one passes. - // Force a bad uin via the packet AND null out session uin by simulating - // a logout? Simpler: send a packet with uin '42' (numeric but <5 chars). - ctx.currentClient().firePacket({ - seq: 1, error: 0, cmd: 'foo', uin: '42', body: Buffer.alloc(0), + expect(onPacket).not.toHaveBeenCalled(); }); - expect(onPacket).not.toHaveBeenCalled(); - }); + it('is a no-op when no onPacket sink is provided', async () => { + const ctx = makeSession({ pipeLive: true }); // no onPacket + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); - it('is a no-op when no onPacket sink is provided', async () => { - const ctx = makeSession({ pipeLive: true }); // no onPacket - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); - - // Should not throw / crash. - ctx.currentClient().firePacket({ - seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.from([7]), + // Should not throw / crash. + ctx.currentClient().firePacket({ + seq: 1, + error: 0, + cmd: 'foo', + uin: '10001', + body: Buffer.from([7]), + }); }); - }); }); describe('HookSession — login reconcile (Docker auto-login safety net)', () => { - it('keeps the packet sender usable only after native readiness confirms the identity hint', async () => { - const ctx = makeSession({ - pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), - nativeReadyOnIdentityHint: true, - }); - let sender: PacketSender | undefined; - ctx.session.on('login', (_uin: string, nextSender: PacketSender) => { - sender = nextSender; + it('keeps the packet sender usable only after native readiness confirms the identity hint', async () => { + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), + nativeReadyOnIdentityHint: true, + }); + let sender: PacketSender | undefined; + ctx.session.on('login', (_uin: string, nextSender: PacketSender) => { + sender = nextSender; + }); + + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + await flush(); + + expect(sender).toBeDefined(); + const result = await sender!.sendPacket('Test.LoginReady', Buffer.from('request')); + + expect(result).toMatchObject({ + success: true, + gotResponse: true, + errorCode: 0, + responseData: Buffer.from('reply'), + }); + expect(ctx.currentClient().sentPackets).toEqual([ + { serviceCmd: 'Test.LoginReady', body: Buffer.from('request') }, + ]); }); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - await flush(); + it('treats a port-probed account as an identity hint, not native login proof', async () => { + // Account identity does not prove request readiness. The bridge must wait + // for a login-state confirmation instead of synthesizing one. + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), + }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); - expect(sender).toBeDefined(); - const result = await sender!.sendPacket('Test.LoginReady', Buffer.from('request')); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); // connect (not logged in via frame) → starts reconcile + await flush(); // immediate probe resolves → forwards identity hint - expect(result).toMatchObject({ - success: true, - gotResponse: true, - errorCode: 0, - responseData: Buffer.from('reply'), + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); + expect(loginSpy).not.toHaveBeenCalled(); + expect(ctx.session.status).toBe('loaded'); + expect(ctx.session.uin).toBe('0'); }); - expect(ctx.currentClient().sentPackets).toEqual([ - { serviceCmd: 'Test.LoginReady', body: Buffer.from('request') }, - ]); - }); - it('treats a port-probed account as an identity hint, not native login proof', async () => { - // Account identity does not prove request readiness. The bridge must wait - // for a login-state confirmation instead of synthesizing one. - const ctx = makeSession({ - pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), + it('forwards the same identity at most once per pipe connection', async () => { + vi.useFakeTimers(); + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), + }); + + try { + await ctx.session.load(); + ctx.session.onPipeUp(); + await vi.advanceTimersByTimeAsync(0); + await vi.advanceTimersByTimeAsync(9000); + + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } }); - const loginSpy = vi.fn(); - ctx.session.on('login', loginSpy); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); // connect (not logged in via frame) → starts reconcile - await flush(); // immediate probe resolves → forwards identity hint + it('keeps observing identity after acknowledgement and forwards an account change', async () => { + vi.useFakeTimers(); + let uin = '10001'; + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin, identityKnown: true }), + }); - expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); - expect(loginSpy).not.toHaveBeenCalled(); - expect(ctx.session.status).toBe('loaded'); - expect(ctx.session.uin).toBe('0'); - }); + try { + await ctx.session.load(); + ctx.session.onPipeUp(); + await vi.advanceTimersByTimeAsync(0); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); - it('forwards the same identity at most once per pipe connection', async () => { - vi.useFakeTimers(); - const ctx = makeSession({ - pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), + uin = '20002'; + await vi.advanceTimersByTimeAsync(29_999); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); + + await vi.advanceTimersByTimeAsync(1); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '20002']); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } }); - try { - await ctx.session.load(); - ctx.session.onPipeUp(); - await vi.advanceTimersByTimeAsync(0); - await vi.advanceTimersByTimeAsync(9000); - expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); - } finally { - ctx.session.dispose(); - vi.useRealTimers(); - } - }); + it('retries identity forwarding failures with a strict bound', async () => { + vi.useFakeTimers(); + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), + identityHintFailures: 3, + }); - it('keeps observing identity after acknowledgement and forwards an account change', async () => { - vi.useFakeTimers(); - let uin = '10001'; - const ctx = makeSession({ - pipeLive: true, - probeLogin: async () => ({ port: 4301, uin, identityKnown: true }), + try { + await ctx.session.load(); + ctx.session.onPipeUp(); + await vi.advanceTimersByTimeAsync(0); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); + + await vi.advanceTimersByTimeAsync(3000); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']); + + await vi.advanceTimersByTimeAsync(9000); + expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001', '10001']); + + await vi.advanceTimersByTimeAsync(30_000); + expect(ctx.currentClient().loginIdentityHints).toHaveLength(3); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } }); - try { - await ctx.session.load(); - ctx.session.onPipeUp(); - await vi.advanceTimersByTimeAsync(0); - expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); - uin = '20002'; - await vi.advanceTimersByTimeAsync(29_999); - expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); + it('does not log in when the probe reports not-logged-in', async () => { + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 0, uin: '', identityKnown: false }), + }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + await flush(); - await vi.advanceTimersByTimeAsync(1); - expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '20002']); - } finally { - ctx.session.dispose(); - vi.useRealTimers(); - } - }); - - it('retries identity forwarding failures with a strict bound', async () => { - vi.useFakeTimers(); - const ctx = makeSession({ - pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }), - identityHintFailures: 3, + expect(loginSpy).not.toHaveBeenCalled(); + expect(ctx.session.status).toBe('loaded'); }); - try { - await ctx.session.load(); - ctx.session.onPipeUp(); - await vi.advanceTimersByTimeAsync(0); - expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']); - await vi.advanceTimersByTimeAsync(3000); - expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']); + it('ignores a probe with a non-real uin (0)', async () => { + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin: '0', identityKnown: true }), + }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + await flush(); - await vi.advanceTimersByTimeAsync(9000); - expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001', '10001']); - - await vi.advanceTimersByTimeAsync(30_000); - expect(ctx.currentClient().loginIdentityHints).toHaveLength(3); - } finally { - ctx.session.dispose(); - vi.useRealTimers(); - } - }); - - it('does not log in when the probe reports not-logged-in', async () => { - const ctx = makeSession({ - pipeLive: true, - probeLogin: async () => ({ port: 0, uin: '', identityKnown: false }), + expect(loginSpy).not.toHaveBeenCalled(); }); - const loginSpy = vi.fn(); - ctx.session.on('login', loginSpy); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); await flush(); - expect(loginSpy).not.toHaveBeenCalled(); - expect(ctx.session.status).toBe('loaded'); - }); + it('tolerates a throwing probe (best-effort, no crash/login)', async () => { + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => { + throw new Error('port scan failed'); + }, + }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + await flush(); - it('ignores a probe with a non-real uin (0)', async () => { - const ctx = makeSession({ - pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '0', identityKnown: true }), + expect(loginSpy).not.toHaveBeenCalled(); + expect(ctx.session.status).toBe('loaded'); }); - const loginSpy = vi.fn(); - ctx.session.on('login', loginSpy); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); await flush(); - expect(loginSpy).not.toHaveBeenCalled(); - }); + it('detects a login that lands on a LATER interval probe', async () => { + vi.useFakeTimers(); - it('tolerates a throwing probe (best-effort, no crash/login)', async () => { - const ctx = makeSession({ - pipeLive: true, - probeLogin: async () => { throw new Error('port scan failed'); }, + try { + let identityKnown = false; + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown }), + nativeReadyOnIdentityHint: true, + }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + + await ctx.session.load(); + ctx.session.onPipeUp(); + await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet) + expect(loginSpy).not.toHaveBeenCalled(); + + identityKnown = true; // QQ exposes the restored identity + await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up + + expect(loginSpy).toHaveBeenCalledOnce(); + expect(ctx.session.status).toBe('online'); + } finally { + vi.useRealTimers(); + } }); - const loginSpy = vi.fn(); - ctx.session.on('login', loginSpy); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); await flush(); - expect(loginSpy).not.toHaveBeenCalled(); - expect(ctx.session.status).toBe('loaded'); - }); + it('does not double-emit when the pushed frame logs in first', async () => { + // Pushed-frame login wins; a subsequent probe with the same uin must not + // re-emit (handleLoginState dedups), and the reconcile timer is stopped. + const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', identityKnown: true })); + const ctx = makeSession({ pipeLive: true, probeLogin }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); - it('detects a login that lands on a LATER interval probe', async () => { - vi.useFakeTimers(); - try { - let identityKnown = false; - const ctx = makeSession({ - pipeLive: true, - probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown }), - nativeReadyOnIdentityHint: true, - }); - const loginSpy = vi.fn(); - ctx.session.on('login', loginSpy); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); // pushed-frame login first + await flush(); - await ctx.session.load(); - ctx.session.onPipeUp(); - await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet) - expect(loginSpy).not.toHaveBeenCalled(); - - identityKnown = true; // QQ exposes the restored identity - await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up - - expect(loginSpy).toHaveBeenCalledOnce(); - expect(ctx.session.status).toBe('online'); - } finally { - vi.useRealTimers(); - } - }); - - it('does not double-emit when the pushed frame logs in first', async () => { - // Pushed-frame login wins; a subsequent probe with the same uin must not - // re-emit (handleLoginState dedups), and the reconcile timer is stopped. - const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', identityKnown: true })); - const ctx = makeSession({ pipeLive: true, probeLogin }); - const loginSpy = vi.fn(); - ctx.session.on('login', loginSpy); - - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); // pushed-frame login first - await flush(); - - expect(loginSpy).toHaveBeenCalledOnce(); - expect(ctx.session.status).toBe('online'); - }); + expect(loginSpy).toHaveBeenCalledOnce(); + expect(ctx.session.status).toBe('online'); + }); }); describe('HookSession — end-to-end receive health (#233)', () => { - const HEARTBEAT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat'; - const MESSAGE_CMD = 'trpc.msg.olpush.OlPushService.MsgPush'; + const HEARTBEAT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat'; + const MESSAGE_CMD = 'trpc.msg.olpush.OlPushService.MsgPush'; - async function startReceiveSession(onPacket?: PacketSink) { - const ctx = makeSession({ pipeLive: true, onPacket }); - const healthChanges: boolean[] = []; - ctx.session.on('receive-health-changed', (healthy: boolean) => healthChanges.push(healthy)); - await ctx.session.load(); - ctx.session.onPipeUp(); - await flush(); - ctx.currentClient().fireLogin('10001'); - return { ctx, healthChanges }; - } + async function startReceiveSession(onPacket?: PacketSink) { + const ctx = makeSession({ pipeLive: true, onPacket }); + const healthChanges: boolean[] = []; + ctx.session.on('receive-health-changed', (healthy: boolean) => healthChanges.push(healthy)); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); + return { ctx, healthChanges }; + } - function firePacket( - ctx: ReturnType, - cmd: string, - uin = '10001', - seq = 1, - ): void { - ctx.currentClient().firePacket({ seq, error: 0, cmd, uin, body: Buffer.alloc(0) }); - } + function firePacket( + ctx: ReturnType, + cmd: string, + uin = '10001', + seq = 1, + ): void { + ctx.currentClient().firePacket({ seq, error: 0, cmd, uin, body: Buffer.alloc(0) }); + } - it('reports native outbound loss as unhealthy and recovers on the next successful request', async () => { - const { ctx, healthChanges } = await startReceiveSession(); - let sender: PacketSender | undefined; - ctx.session.on('login', (_uin: string, nextSender: PacketSender) => { - sender = nextSender; + it('reports native outbound loss as unhealthy and recovers on the next successful request', async () => { + const { ctx, healthChanges } = await startReceiveSession(); + let sender: PacketSender | undefined; + ctx.session.on('login', (_uin: string, nextSender: PacketSender) => { + sender = nextSender; + }); + + try { + // Re-emit on a new account epoch so the test captures the session sender. + ctx.currentClient().fireLogin('20002'); + ctx.currentClient().sendError = new HookPipeRequestError( + 'The QQ connection changed. Please restart QQ and try again.', + PIPE_STATUS_CONNECTION_UNAVAILABLE, + 1, + ); + + await sender!.sendPacket('Test.Command', Buffer.alloc(0)); + expect(ctx.session.receiveHealthy).toBe(false); + expect(healthChanges).toEqual([false]); + + // Incoming traffic alone must not conceal a still-broken send path. + firePacket(ctx, HEARTBEAT_CMD, '20002'); + expect(ctx.session.receiveHealthy).toBe(false); + + ctx.currentClient().sendError = null; + await sender!.sendPacket('Test.Command', Buffer.alloc(0)); + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([false, true]); + } finally { + ctx.session.dispose(); + } }); - try { - // Re-emit on a new account epoch so the test captures the session sender. - ctx.currentClient().fireLogin('20002'); - ctx.currentClient().sendError = new HookPipeRequestError( - 'The QQ connection changed. Please restart QQ and try again.', - PIPE_STATUS_CONNECTION_UNAVAILABLE, - 1, - ); + it('becomes unhealthy only after an observed QQ heartbeat stays silent, then recovers on the next packet', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); + const { ctx, healthChanges } = await startReceiveSession(); - await sender!.sendPacket('Test.Command', Buffer.alloc(0)); - expect(ctx.session.receiveHealthy).toBe(false); - expect(healthChanges).toEqual([false]); + try { + firePacket(ctx, HEARTBEAT_CMD); - // Incoming traffic alone must not conceal a still-broken send path. - firePacket(ctx, HEARTBEAT_CMD, '20002'); - expect(ctx.session.receiveHealthy).toBe(false); + vi.advanceTimersByTime(90_000); + expect(ctx.session.receiveHealthy).toBe(true); - ctx.currentClient().sendError = null; - await sender!.sendPacket('Test.Command', Buffer.alloc(0)); - expect(ctx.session.receiveHealthy).toBe(true); - expect(healthChanges).toEqual([false, true]); - } finally { - ctx.session.dispose(); - } - }); + vi.advanceTimersByTime(15_000); + expect(ctx.session.receiveHealthy).toBe(false); + expect(healthChanges).toEqual([false]); - it('becomes unhealthy only after an observed QQ heartbeat stays silent, then recovers on the next packet', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); - const { ctx, healthChanges } = await startReceiveSession(); + firePacket(ctx, MESSAGE_CMD, '10001', 2); - try { - firePacket(ctx, HEARTBEAT_CMD); + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([false, true]); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } + }); - vi.advanceTimersByTime(90_000); - expect(ctx.session.receiveHealthy).toBe(true); + it('does not arm the watchdog when this QQ session has never exposed its heartbeat', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); + const { ctx, healthChanges } = await startReceiveSession(); - vi.advanceTimersByTime(15_000); - expect(ctx.session.receiveHealthy).toBe(false); - expect(healthChanges).toEqual([false]); + try { + firePacket(ctx, MESSAGE_CMD); - firePacket(ctx, MESSAGE_CMD, '10001', 2); + vi.advanceTimersByTime(10 * 60_000); - expect(ctx.session.receiveHealthy).toBe(true); - expect(healthChanges).toEqual([false, true]); - } finally { - ctx.session.dispose(); - vi.useRealTimers(); - } - }); + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([]); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } + }); - it('does not arm the watchdog when this QQ session has never exposed its heartbeat', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); - const { ctx, healthChanges } = await startReceiveSession(); + it('uses the confirmation window to avoid a sleep-resume false alarm', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); + const { ctx, healthChanges } = await startReceiveSession(); - try { - firePacket(ctx, MESSAGE_CMD); + try { + firePacket(ctx, HEARTBEAT_CMD); - vi.advanceTimersByTime(10 * 60_000); + vi.advanceTimersByTime(90_000); + vi.advanceTimersByTime(14_999); + firePacket(ctx, HEARTBEAT_CMD, '10001', 2); + vi.advanceTimersByTime(1); - expect(ctx.session.receiveHealthy).toBe(true); - expect(healthChanges).toEqual([]); - } finally { - ctx.session.dispose(); - vi.useRealTimers(); - } - }); + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([]); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } + }); - it('uses the confirmation window to avoid a sleep-resume false alarm', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); - const { ctx, healthChanges } = await startReceiveSession(); + it('does not carry an armed watchdog across a direct account switch', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); + const { ctx, healthChanges } = await startReceiveSession(); - try { - firePacket(ctx, HEARTBEAT_CMD); + try { + firePacket(ctx, HEARTBEAT_CMD); - vi.advanceTimersByTime(90_000); - vi.advanceTimersByTime(14_999); - firePacket(ctx, HEARTBEAT_CMD, '10001', 2); - vi.advanceTimersByTime(1); + ctx.currentClient().fireLogin('20002'); + vi.advanceTimersByTime(10 * 60_000); - expect(ctx.session.receiveHealthy).toBe(true); - expect(healthChanges).toEqual([]); - } finally { - ctx.session.dispose(); - vi.useRealTimers(); - } - }); + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([]); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } + }); - it('does not carry an armed watchdog across a direct account switch', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); - const { ctx, healthChanges } = await startReceiveSession(); + it('requires the new account heartbeat after packet-driven PID migration', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); + const { ctx, healthChanges } = await startReceiveSession(); - try { - firePacket(ctx, HEARTBEAT_CMD); + try { + firePacket(ctx, HEARTBEAT_CMD); + firePacket(ctx, MESSAGE_CMD, '20002', 2); + vi.advanceTimersByTime(10 * 60_000); - ctx.currentClient().fireLogin('20002'); - vi.advanceTimersByTime(10 * 60_000); + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([]); - expect(ctx.session.receiveHealthy).toBe(true); - expect(healthChanges).toEqual([]); - } finally { - ctx.session.dispose(); - vi.useRealTimers(); - } - }); + firePacket(ctx, HEARTBEAT_CMD, '20002', 3); + vi.advanceTimersByTime(105_000); - it('requires the new account heartbeat after packet-driven PID migration', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); - const { ctx, healthChanges } = await startReceiveSession(); + expect(ctx.session.receiveHealthy).toBe(false); + expect(healthChanges).toEqual([false]); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } + }); - try { - firePacket(ctx, HEARTBEAT_CMD); - firePacket(ctx, MESSAGE_CMD, '20002', 2); - vi.advanceTimersByTime(10 * 60_000); + it('counts an invalid-UIN frame as receive activity without routing it', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); + const onPacket = vi.fn(); + const { ctx, healthChanges } = await startReceiveSession(onPacket); - expect(ctx.session.receiveHealthy).toBe(true); - expect(healthChanges).toEqual([]); + try { + firePacket(ctx, HEARTBEAT_CMD); + onPacket.mockClear(); - firePacket(ctx, HEARTBEAT_CMD, '20002', 3); - vi.advanceTimersByTime(105_000); + vi.advanceTimersByTime(80_000); + firePacket(ctx, 'trpc.status.invalid-uin-probe', '0', 2); + vi.advanceTimersByTime(104_999); - expect(ctx.session.receiveHealthy).toBe(false); - expect(healthChanges).toEqual([false]); - } finally { - ctx.session.dispose(); - vi.useRealTimers(); - } - }); + expect(ctx.session.receiveHealthy).toBe(true); + expect(onPacket).not.toHaveBeenCalled(); - it('counts an invalid-UIN frame as receive activity without routing it', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); - const onPacket = vi.fn(); - const { ctx, healthChanges } = await startReceiveSession(onPacket); + vi.advanceTimersByTime(1); + expect(ctx.session.receiveHealthy).toBe(false); - try { - firePacket(ctx, HEARTBEAT_CMD); - onPacket.mockClear(); + firePacket(ctx, 'trpc.status.invalid-uin-probe', '0', 3); - vi.advanceTimersByTime(80_000); - firePacket(ctx, 'trpc.status.invalid-uin-probe', '0', 2); - vi.advanceTimersByTime(104_999); - - expect(ctx.session.receiveHealthy).toBe(true); - expect(onPacket).not.toHaveBeenCalled(); - - vi.advanceTimersByTime(1); - expect(ctx.session.receiveHealthy).toBe(false); - - firePacket(ctx, 'trpc.status.invalid-uin-probe', '0', 3); - - expect(ctx.session.receiveHealthy).toBe(true); - expect(healthChanges).toEqual([false, true]); - expect(onPacket).not.toHaveBeenCalled(); - } finally { - ctx.session.dispose(); - vi.useRealTimers(); - } - }); + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([false, true]); + expect(onPacket).not.toHaveBeenCalled(); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } + }); }); describe('HookSession — login reconcile does not stack concurrent probes', () => { - it('skips overlapping ticks while a slow probe is in flight', async () => { - vi.useFakeTimers(); - try { - // A probe that never resolves — simulates a slow port scan spanning - // multiple intervals. The in-flight guard must call it only once. - const probeLogin = vi.fn(() => new Promise(() => { /* pending */ })); - const ctx = makeSession({ pipeLive: true, probeLogin }); + it('skips overlapping ticks while a slow probe is in flight', async () => { + vi.useFakeTimers(); - await ctx.session.load(); - ctx.session.onPipeUp(); - await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (starts, stays pending) - await vi.advanceTimersByTimeAsync(9000); // 3 more interval ticks + try { + // A probe that never resolves — simulates a slow port scan spanning + // multiple intervals. The in-flight guard must call it only once. + const probeLogin = vi.fn( + () => + new Promise(() => { + /* pending */ + }), + ); + const ctx = makeSession({ pipeLive: true, probeLogin }); - expect(probeLogin).toHaveBeenCalledTimes(1); // not stacked - } finally { - vi.useRealTimers(); - } - }); + await ctx.session.load(); + ctx.session.onPipeUp(); + await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (starts, stays pending) + await vi.advanceTimersByTimeAsync(9000); // 3 more interval ticks + + expect(probeLogin).toHaveBeenCalledTimes(1); // not stacked + } finally { + vi.useRealTimers(); + } + }); }); diff --git a/packages/bridge/tests/hook-status.test.ts b/packages/bridge/tests/hook-status.test.ts index 2d1e21f8..925bf29d 100644 --- a/packages/bridge/tests/hook-status.test.ts +++ b/packages/bridge/tests/hook-status.test.ts @@ -3,54 +3,66 @@ import { statusFor, type HookFlags } from '../src/hook-status'; import type { HookProcessStatus } from '../src/types'; const F = (o: Partial): HookFlags => ({ - injected: false, connected: false, loggedIn: false, wasLoggedIn: false, ...o, + injected: false, + connected: false, + loggedIn: false, + wasLoggedIn: false, + ...o, }); describe('statusFor — settled HookProcessStatus derivation', () => { - it('not injected → available (regardless of other flags)', () => { - expect(statusFor(F({ injected: false }))).toBe('available'); - // !injected dominates: stale connected/loggedIn bits must not leak through. - expect(statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true }))).toBe('available'); - }); + it('not injected → available (regardless of other flags)', () => { + expect(statusFor(F({ injected: false }))).toBe('available'); + // !injected dominates: stale connected/loggedIn bits must not leak through. + expect( + statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true })), + ).toBe('available'); + }); - it('injected, connected, loggedIn → online', () => { - expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online'); - }); + it('injected, connected, loggedIn → online', () => { + expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online'); + }); - it('injected, connected, not loggedIn → loaded', () => { - expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded'); - }); + it('injected, connected, not loggedIn → loaded', () => { + expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded'); + }); - it('injected, not connected, had logged in → disconnected', () => { - expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe('disconnected'); - }); + it('injected, not connected, had logged in → disconnected', () => { + expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe( + 'disconnected', + ); + }); - it('injected, not connected, never logged in → connecting', () => { - expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe('connecting'); - }); + it('injected, not connected, never logged in → connecting', () => { + expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe( + 'connecting', + ); + }); - it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => { - const base = { injected: true, connected: false, loggedIn: false }; - expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected'); - expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting'); - }); + it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => { + const base = { injected: true, connected: false, loggedIn: false }; + expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected'); + expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting'); + }); - it('covers exactly the five settled states across the flag space', () => { - const seen = new Set(); - for (const injected of [false, true]) { - for (const connected of [false, true]) { - for (const loggedIn of [false, true]) { - for (const wasLoggedIn of [false, true]) { - seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn })); - } + it('covers exactly the five settled states across the flag space', () => { + const seen = new Set(); + + for (const injected of [false, true]) { + for (const connected of [false, true]) { + for (const loggedIn of [false, true]) { + for (const wasLoggedIn of [false, true]) { + seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn })); + } + } + } } - } - } - expect([...seen].sort()).toEqual( - ['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(), - ); - // The two out-of-band states are never produced by the pure derivation. - expect(seen.has('loading')).toBe(false); - expect(seen.has('error')).toBe(false); - }); + + expect([...seen].sort()).toEqual( + ['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(), + ); + // The two out-of-band states are never produced by the pure derivation. + expect(seen.has('loading')).toBe(false); + expect(seen.has('error')).toBe(false); + }); }); diff --git a/packages/bridge/tests/injector.test.ts b/packages/bridge/tests/injector.test.ts index 8ae58215..de0c38ce 100644 --- a/packages/bridge/tests/injector.test.ts +++ b/packages/bridge/tests/injector.test.ts @@ -3,21 +3,21 @@ import { fileURLToPath } from 'url'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const { existsSyncMock, listPidsMock } = vi.hoisted(() => ({ - existsSyncMock: vi.fn<(target: string) => boolean>(() => false), - listPidsMock: vi.fn(() => new Set()), + existsSyncMock: vi.fn<(target: string) => boolean>(() => false), + listPidsMock: vi.fn(() => new Set()), })); vi.mock('fs', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - existsSync: (target: Parameters[0]) => - existsSyncMock(String(target)), - }; + const actual = await importOriginal(); + return { + ...actual, + existsSync: (target: Parameters[0]) => + existsSyncMock(String(target)), + }; }); vi.mock('../src/qq-hook-client', () => ({ - listSnowlumaPipePidsSync: listPidsMock, + listSnowlumaPipePidsSync: listPidsMock, })); const INJECTOR_DIR = path.dirname(fileURLToPath(new URL('../src/injector.ts', import.meta.url))); @@ -25,378 +25,391 @@ const ORIGINAL_PLATFORM = process.platform; const ORIGINAL_ARCH = process.arch; const HANDLE = { - base: 0x7fff0000n, - entry: 0x7fff1234n, - exceptionTable: 0x7fff5678n, - size: 8192, + base: 0x7fff0000n, + entry: 0x7fff1234n, + exceptionTable: 0x7fff5678n, + size: 8192, }; function setPlatform(platform: NodeJS.Platform, arch: string): void { - Object.defineProperty(process, 'platform', { value: platform, configurable: true }); - Object.defineProperty(process, 'arch', { value: arch, configurable: true }); + Object.defineProperty(process, 'platform', { value: platform, configurable: true }); + Object.defineProperty(process, 'arch', { value: arch, configurable: true }); } function restorePlatform(): void { - Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true }); - Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true }); + Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true }); + Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true }); } function nativeSearchDirs(cwd = process.cwd()): string[] { - return [ - path.resolve(INJECTOR_DIR, 'native'), - path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'), - path.resolve(cwd, 'dist', 'native'), - path.resolve(cwd, 'packages', 'runtime', 'native'), - ]; + return [ + path.resolve(INJECTOR_DIR, 'native'), + path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'), + path.resolve(cwd, 'dist', 'native'), + path.resolve(cwd, 'packages', 'runtime', 'native'), + ]; } function nativeCandidate(fileName: string, dirIndex: number, cwd = process.cwd()): string { - return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName); + return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName); } function allowExisting(paths: readonly string[]): void { - const allowed = new Set(paths); - existsSyncMock.mockImplementation((target) => allowed.has(target)); + const allowed = new Set(paths); + existsSyncMock.mockImplementation((target) => allowed.has(target)); } -function fakeAddon(overrides: { - getAllMainProcess?: number[]; - loadModuleManual?: (pid: number, dylibPath: string) => unknown; - unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void; -} = {}) { - return { - getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []), - loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)), - unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)), - }; +function fakeAddon( + overrides: { + getAllMainProcess?: number[]; + loadModuleManual?: (pid: number, dylibPath: string) => unknown; + unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void; + } = {}, +) { + return { + getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []), + loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)), + unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)), + }; } function installDlopen(addon: object) { - return vi.spyOn(process, 'dlopen').mockImplementation((mod) => { - (mod as { exports: object }).exports = addon; - }); + return vi.spyOn(process, 'dlopen').mockImplementation((mod) => { + (mod as { exports: object }).exports = addon; + }); } async function loadInjector() { - return import('../src/injector'); + return import('../src/injector'); } beforeEach(() => { - existsSyncMock.mockReset(); - existsSyncMock.mockReturnValue(false); - listPidsMock.mockReset(); - listPidsMock.mockReturnValue(new Set()); - vi.resetModules(); + existsSyncMock.mockReset(); + existsSyncMock.mockReturnValue(false); + listPidsMock.mockReset(); + listPidsMock.mockReturnValue(new Set()); + vi.resetModules(); }); afterEach(() => { - restorePlatform(); - vi.restoreAllMocks(); + restorePlatform(); + vi.restoreAllMocks(); }); describe('resolveHookNativePath', () => { - it('returns null after probing every search directory', async () => { - setPlatform('linux', 'x64'); - const probed: string[] = []; - existsSyncMock.mockImplementation((target) => { - probed.push(target); - return false; + it('returns null after probing every search directory', async () => { + setPlatform('linux', 'x64'); + const probed: string[] = []; + existsSyncMock.mockImplementation((target) => { + probed.push(target); + return false; + }); + + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('node')).toBeNull(); + expect(probed).toEqual([ + nativeCandidate('snowluma-linux-x64.node', 0), + nativeCandidate('snowluma-linux-x64.node', 1), + nativeCandidate('snowluma-linux-x64.node', 2), + nativeCandidate('snowluma-linux-x64.node', 3), + ]); }); - const { resolveHookNativePath } = await loadInjector(); - expect(resolveHookNativePath('node')).toBeNull(); - expect(probed).toEqual([ - nativeCandidate('snowluma-linux-x64.node', 0), - nativeCandidate('snowluma-linux-x64.node', 1), - nativeCandidate('snowluma-linux-x64.node', 2), - nativeCandidate('snowluma-linux-x64.node', 3), - ]); - }); + it('returns the first existing candidate and stops scanning', async () => { + setPlatform('linux', 'x64'); + const winner = nativeCandidate('snowluma-linux-x64.node', 0); + const later = nativeCandidate('snowluma-linux-x64.node', 1); + const probed: string[] = []; + existsSyncMock.mockImplementation((target) => { + probed.push(target); + return target === winner || target === later; + }); - it('returns the first existing candidate and stops scanning', async () => { - setPlatform('linux', 'x64'); - const winner = nativeCandidate('snowluma-linux-x64.node', 0); - const later = nativeCandidate('snowluma-linux-x64.node', 1); - const probed: string[] = []; - existsSyncMock.mockImplementation((target) => { - probed.push(target); - return target === winner || target === later; + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('node')).toBe(winner); + expect(probed).toEqual([winner]); }); - const { resolveHookNativePath } = await loadInjector(); - expect(resolveHookNativePath('node')).toBe(winner); - expect(probed).toEqual([winner]); - }); + it('skips missing earlier directories for the injectable .so', async () => { + setPlatform('linux', 'arm64'); + const winner = nativeCandidate('snowluma-linux-arm64.so', 2); + allowExisting([winner]); - it('skips missing earlier directories for the injectable .so', async () => { - setPlatform('linux', 'arm64'); - const winner = nativeCandidate('snowluma-linux-arm64.so', 2); - allowExisting([winner]); + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('so')).toBe(winner); + }); - const { resolveHookNativePath } = await loadInjector(); - expect(resolveHookNativePath('so')).toBe(winner); - }); + it('resolves snowluma-win32-x64.dll on win32 x64', async () => { + setPlatform('win32', 'x64'); + const winner = nativeCandidate('snowluma-win32-x64.dll', 3); + allowExisting([winner]); - it('resolves snowluma-win32-x64.dll on win32 x64', async () => { - setPlatform('win32', 'x64'); - const winner = nativeCandidate('snowluma-win32-x64.dll', 3); - allowExisting([winner]); + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('dll')).toBe(winner); + }); - const { resolveHookNativePath } = await loadInjector(); - expect(resolveHookNativePath('dll')).toBe(winner); - }); + it('uses the generic platform-arch name on win32 arm64', async () => { + setPlatform('win32', 'arm64'); + const winner = nativeCandidate('snowluma-win32-arm64.node', 1); + allowExisting([winner]); - it('uses the generic platform-arch name on win32 arm64', async () => { - setPlatform('win32', 'arm64'); - const winner = nativeCandidate('snowluma-win32-arm64.node', 1); - allowExisting([winner]); + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('node')).toBe(winner); + }); - const { resolveHookNativePath } = await loadInjector(); - expect(resolveHookNativePath('node')).toBe(winner); - }); + it('re-reads process.cwd() for the dist/native fallback', async () => { + setPlatform('darwin', 'arm64'); + vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd'); + const winner = path.join( + '/tmp/sl-injector-cwd', + 'dist', + 'native', + 'snowluma-darwin-arm64.node', + ); + allowExisting([winner]); - it('re-reads process.cwd() for the dist/native fallback', async () => { - setPlatform('darwin', 'arm64'); - vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd'); - const winner = path.join('/tmp/sl-injector-cwd', 'dist', 'native', 'snowluma-darwin-arm64.node'); - allowExisting([winner]); - - const { resolveHookNativePath } = await loadInjector(); - expect(resolveHookNativePath('node')).toBe(winner); - }); + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('node')).toBe(winner); + }); }); describe('getNativeHookAddon / getNativeHookLoadError', () => { - it('starts with a null load error before any probe', async () => { - const { getNativeHookLoadError } = await loadInjector(); - expect(getNativeHookLoadError()).toBeNull(); - }); - - it('returns null and records a missing-binary error', async () => { - setPlatform('linux', 'x64'); - const dlopen = vi.spyOn(process, 'dlopen'); - const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); - - expect(getNativeHookAddon()).toBeNull(); - expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64'); - expect(dlopen).not.toHaveBeenCalled(); - }); - - it('dlopens the resolved .node once and caches the addon', async () => { - setPlatform('linux', 'x64'); - const nodePath = nativeCandidate('snowluma-linux-x64.node', 0); - allowExisting([nodePath]); - const addon = fakeAddon(); - const dlopen = installDlopen(addon); - - const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); - const first = getNativeHookAddon(); - const second = getNativeHookAddon(); - - expect(first).toBe(addon); - expect(second).toBe(addon); - expect(getNativeHookLoadError()).toBeNull(); - expect(dlopen).toHaveBeenCalledTimes(1); - expect(dlopen.mock.calls[0]![1]).toBe(nodePath); - }); - - it('stores Error.message when process.dlopen throws', async () => { - setPlatform('darwin', 'arm64'); - allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]); - vi.spyOn(process, 'dlopen').mockImplementation(() => { - throw new Error('not a valid Node addon'); + it('starts with a null load error before any probe', async () => { + const { getNativeHookLoadError } = await loadInjector(); + expect(getNativeHookLoadError()).toBeNull(); }); - const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); - expect(getNativeHookAddon()).toBeNull(); - expect(getNativeHookLoadError()).toBe('not a valid Node addon'); - }); + it('returns null and records a missing-binary error', async () => { + setPlatform('linux', 'x64'); + const dlopen = vi.spyOn(process, 'dlopen'); + const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); - it('stringifies a non-Error dlopen failure', async () => { - setPlatform('linux', 'x64'); - allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]); - vi.spyOn(process, 'dlopen').mockImplementation(() => { - throw 42; + expect(getNativeHookAddon()).toBeNull(); + expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64'); + expect(dlopen).not.toHaveBeenCalled(); }); - const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); - expect(getNativeHookAddon()).toBeNull(); - expect(getNativeHookLoadError()).toBe('42'); - }); + it('dlopens the resolved .node once and caches the addon', async () => { + setPlatform('linux', 'x64'); + const nodePath = nativeCandidate('snowluma-linux-x64.node', 0); + allowExisting([nodePath]); + const addon = fakeAddon(); + const dlopen = installDlopen(addon); - it('retries after a failed load when a binary later appears', async () => { - setPlatform('linux', 'x64'); - const nodePath = nativeCandidate('snowluma-linux-x64.node', 1); - const addon = fakeAddon(); - installDlopen(addon); + const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); + const first = getNativeHookAddon(); + const second = getNativeHookAddon(); - const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); - expect(getNativeHookAddon()).toBeNull(); - expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64'); + expect(first).toBe(addon); + expect(second).toBe(addon); + expect(getNativeHookLoadError()).toBeNull(); + expect(dlopen).toHaveBeenCalledTimes(1); + expect(dlopen.mock.calls[0]![1]).toBe(nodePath); + }); - allowExisting([nodePath]); - expect(getNativeHookAddon()).toBe(addon); - expect(getNativeHookLoadError()).toBeNull(); - }); + it('stores Error.message when process.dlopen throws', async () => { + setPlatform('darwin', 'arm64'); + allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]); + vi.spyOn(process, 'dlopen').mockImplementation(() => { + throw new Error('not a valid Node addon'); + }); + + const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); + expect(getNativeHookAddon()).toBeNull(); + expect(getNativeHookLoadError()).toBe('not a valid Node addon'); + }); + + it('stringifies a non-Error dlopen failure', async () => { + setPlatform('linux', 'x64'); + allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]); + vi.spyOn(process, 'dlopen').mockImplementation(() => { + throw 42; + }); + + const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); + expect(getNativeHookAddon()).toBeNull(); + expect(getNativeHookLoadError()).toBe('42'); + }); + + it('retries after a failed load when a binary later appears', async () => { + setPlatform('linux', 'x64'); + const nodePath = nativeCandidate('snowluma-linux-x64.node', 1); + const addon = fakeAddon(); + installDlopen(addon); + + const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); + expect(getNativeHookAddon()).toBeNull(); + expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64'); + + allowExisting([nodePath]); + expect(getNativeHookAddon()).toBe(addon); + expect(getNativeHookLoadError()).toBeNull(); + }); }); describe('listHookProcesses', () => { - it('on darwin maps sorted pipe pids without opening the native addon', async () => { - setPlatform('darwin', 'arm64'); - listPidsMock.mockReturnValue(new Set([42, 7, 15])); - allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]); - const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] })); + it('on darwin maps sorted pipe pids without opening the native addon', async () => { + setPlatform('darwin', 'arm64'); + listPidsMock.mockReturnValue(new Set([42, 7, 15])); + allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]); + const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] })); - const { listHookProcesses } = await loadInjector(); - expect(listHookProcesses()).toEqual([ - { pid: 7, name: 'qq', path: '' }, - { pid: 15, name: 'qq', path: '' }, - { pid: 42, name: 'qq', path: '' }, - ]); - expect(listPidsMock).toHaveBeenCalledTimes(1); - expect(dlopen).not.toHaveBeenCalled(); - }); + const { listHookProcesses } = await loadInjector(); + expect(listHookProcesses()).toEqual([ + { pid: 7, name: 'qq', path: '' }, + { pid: 15, name: 'qq', path: '' }, + { pid: 42, name: 'qq', path: '' }, + ]); + expect(listPidsMock).toHaveBeenCalledTimes(1); + expect(dlopen).not.toHaveBeenCalled(); + }); - it('on darwin returns an empty list when no control sockets exist', async () => { - setPlatform('darwin', 'arm64'); - listPidsMock.mockReturnValue(new Set()); + it('on darwin returns an empty list when no control sockets exist', async () => { + setPlatform('darwin', 'arm64'); + listPidsMock.mockReturnValue(new Set()); - const { listHookProcesses } = await loadInjector(); - expect(listHookProcesses()).toEqual([]); - }); + const { listHookProcesses } = await loadInjector(); + expect(listHookProcesses()).toEqual([]); + }); - it('on non-darwin returns [] when the addon cannot be loaded', async () => { - setPlatform('linux', 'x64'); + it('on non-darwin returns [] when the addon cannot be loaded', async () => { + setPlatform('linux', 'x64'); - const { listHookProcesses } = await loadInjector(); - expect(listHookProcesses()).toEqual([]); - }); + const { listHookProcesses } = await loadInjector(); + expect(listHookProcesses()).toEqual([]); + }); - it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => { - setPlatform('linux', 'x64'); - const nodePath = nativeCandidate('snowluma-linux-x64.node', 0); - allowExisting([nodePath]); - installDlopen(fakeAddon({ - getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2], - })); + it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => { + setPlatform('linux', 'x64'); + const nodePath = nativeCandidate('snowluma-linux-x64.node', 0); + allowExisting([nodePath]); + installDlopen( + fakeAddon({ + getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2], + }), + ); - const { listHookProcesses } = await loadInjector(); - expect(listHookProcesses()).toEqual([ - { pid: 2, name: 'qq', path: '' }, - { pid: 8, name: 'qq', path: '' }, - ]); - }); + const { listHookProcesses } = await loadInjector(); + expect(listHookProcesses()).toEqual([ + { pid: 2, name: 'qq', path: '' }, + { pid: 8, name: 'qq', path: '' }, + ]); + }); - it('on win32 names processes QQ.exe', async () => { - setPlatform('win32', 'x64'); - allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]); - installDlopen(fakeAddon({ getAllMainProcess: [9] })); + it('on win32 names processes QQ.exe', async () => { + setPlatform('win32', 'x64'); + allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]); + installDlopen(fakeAddon({ getAllMainProcess: [9] })); - const { listHookProcesses } = await loadInjector(); - expect(listHookProcesses()).toEqual([ - { pid: 9, name: 'QQ.exe', path: '' }, - ]); - }); + const { listHookProcesses } = await loadInjector(); + expect(listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]); + }); }); describe('injectHookProcess', () => { - it('throws the missing-addon load error', async () => { - setPlatform('linux', 'x64'); - const { injectHookProcess } = await loadInjector(); - await expect(injectHookProcess(4242)).rejects.toThrow('No hook native addon found for linux-x64'); - }); - - it('throws when the addon exists but the injectable is missing', async () => { - setPlatform('linux', 'x64'); - allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]); - installDlopen(fakeAddon()); - - const { injectHookProcess } = await loadInjector(); - await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64'); - }); - - it('awaits a thenable loadModuleManual handle', async () => { - setPlatform('linux', 'x64'); - const nodePath = nativeCandidate('snowluma-linux-x64.node', 0); - const soPath = nativeCandidate('snowluma-linux-x64.so', 0); - allowExisting([nodePath, soPath]); - const addon = fakeAddon({ - loadModuleManual: () => Promise.resolve(HANDLE), + it('throws the missing-addon load error', async () => { + setPlatform('linux', 'x64'); + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(4242)).rejects.toThrow( + 'No hook native addon found for linux-x64', + ); }); - installDlopen(addon); - const { injectHookProcess } = await loadInjector(); - await expect(injectHookProcess(4242)).resolves.toEqual({ - method: 'loadModuleManual', - handle: HANDLE, + it('throws when the addon exists but the injectable is missing', async () => { + setPlatform('linux', 'x64'); + allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]); + installDlopen(fakeAddon()); + + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64'); }); - expect(addon.loadModuleManual).toHaveBeenCalledTimes(1); - expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath); - }); - it('accepts a synchronous loadModuleManual return value', async () => { - setPlatform('darwin', 'arm64'); - const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2); - const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3); - allowExisting([nodePath, soPath]); - const addon = fakeAddon({ loadModuleManual: () => HANDLE }); - installDlopen(addon); + it('awaits a thenable loadModuleManual handle', async () => { + setPlatform('linux', 'x64'); + const nodePath = nativeCandidate('snowluma-linux-x64.node', 0); + const soPath = nativeCandidate('snowluma-linux-x64.so', 0); + allowExisting([nodePath, soPath]); + const addon = fakeAddon({ + loadModuleManual: () => Promise.resolve(HANDLE), + }); + installDlopen(addon); - const { injectHookProcess } = await loadInjector(); - await expect(injectHookProcess(77)).resolves.toEqual({ - method: 'loadModuleManual', - handle: HANDLE, + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(4242)).resolves.toEqual({ + method: 'loadModuleManual', + handle: HANDLE, + }); + expect(addon.loadModuleManual).toHaveBeenCalledTimes(1); + expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath); }); - expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath); - }); - it('injects snowluma-win32-x64.dll on win32 x64', async () => { - setPlatform('win32', 'x64'); - const nodePath = nativeCandidate('snowluma-win32-x64.node', 0); - const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0); - allowExisting([nodePath, dllPath]); - const addon = fakeAddon({ loadModuleManual: () => HANDLE }); - installDlopen(addon); + it('accepts a synchronous loadModuleManual return value', async () => { + setPlatform('darwin', 'arm64'); + const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2); + const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3); + allowExisting([nodePath, soPath]); + const addon = fakeAddon({ loadModuleManual: () => HANDLE }); + installDlopen(addon); - const { injectHookProcess } = await loadInjector(); - await expect(injectHookProcess(5150)).resolves.toEqual({ - method: 'loadModuleManual', - handle: HANDLE, + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(77)).resolves.toEqual({ + method: 'loadModuleManual', + handle: HANDLE, + }); + expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath); }); - expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath); - }); - it('propagates a rejected loadModuleManual', async () => { - setPlatform('linux', 'x64'); - allowExisting([ - nativeCandidate('snowluma-linux-x64.node', 0), - nativeCandidate('snowluma-linux-x64.so', 0), - ]); - installDlopen(fakeAddon({ - loadModuleManual: () => Promise.reject(new Error('map failed')), - })); + it('injects snowluma-win32-x64.dll on win32 x64', async () => { + setPlatform('win32', 'x64'); + const nodePath = nativeCandidate('snowluma-win32-x64.node', 0); + const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0); + allowExisting([nodePath, dllPath]); + const addon = fakeAddon({ loadModuleManual: () => HANDLE }); + installDlopen(addon); - const { injectHookProcess } = await loadInjector(); - await expect(injectHookProcess(7)).rejects.toThrow('map failed'); - }); + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(5150)).resolves.toEqual({ + method: 'loadModuleManual', + handle: HANDLE, + }); + expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath); + }); + + it('propagates a rejected loadModuleManual', async () => { + setPlatform('linux', 'x64'); + allowExisting([ + nativeCandidate('snowluma-linux-x64.node', 0), + nativeCandidate('snowluma-linux-x64.so', 0), + ]); + installDlopen( + fakeAddon({ + loadModuleManual: () => Promise.reject(new Error('map failed')), + }), + ); + + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(7)).rejects.toThrow('map failed'); + }); }); describe('unloadHookProcess', () => { - it('throws the missing-addon load error', async () => { - setPlatform('linux', 'x64'); - const { unloadHookProcess } = await loadInjector(); - expect(() => unloadHookProcess(4242, HANDLE)).toThrow('No hook native addon found for linux-x64'); - }); + it('throws the missing-addon load error', async () => { + setPlatform('linux', 'x64'); + const { unloadHookProcess } = await loadInjector(); + expect(() => unloadHookProcess(4242, HANDLE)).toThrow( + 'No hook native addon found for linux-x64', + ); + }); - it('forwards pid and handle to unloadModuleManual', async () => { - setPlatform('linux', 'x64'); - allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]); - const addon = fakeAddon(); - installDlopen(addon); + it('forwards pid and handle to unloadModuleManual', async () => { + setPlatform('linux', 'x64'); + allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]); + const addon = fakeAddon(); + installDlopen(addon); - const { unloadHookProcess } = await loadInjector(); - expect(unloadHookProcess(4242, HANDLE)).toBeUndefined(); - expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1); - expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE); - }); + const { unloadHookProcess } = await loadInjector(); + expect(unloadHookProcess(4242, HANDLE)).toBeUndefined(); + expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1); + expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE); + }); }); diff --git a/packages/bridge/tests/packet-timeout.test.ts b/packages/bridge/tests/packet-timeout.test.ts index 587dc4b0..00395d11 100644 --- a/packages/bridge/tests/packet-timeout.test.ts +++ b/packages/bridge/tests/packet-timeout.test.ts @@ -6,25 +6,25 @@ const PACKET = 'SNOWLUMA_PACKET_TIMEOUT_MS'; const ACK = 'SNOWLUMA_HOOK_ACK_TIMEOUT_MS'; afterEach(() => { - delete process.env[PACKET]; - delete process.env[ACK]; + delete process.env[PACKET]; + delete process.env[ACK]; }); describe('packet and hook ack timeouts', () => { - it('keeps the 15 second packet default', () => { - expect(packetTimeoutMs({})).toBe(15_000); - }); + it('keeps the 15 second packet default', () => { + expect(packetTimeoutMs({})).toBe(15_000); + }); - it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => { - expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000); - expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000); - }); + it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => { + expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000); + expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000); + }); - it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => { - process.env[ACK] = '1200'; - const client = new QqHookClient(1, { runtimeDir: '/tmp' }); - expect(client.defaultAckTimeoutMs).toBe(1200); - const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 }); - expect(explicit.defaultAckTimeoutMs).toBe(50); - }); -}); \ No newline at end of file + it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => { + process.env[ACK] = '1200'; + const client = new QqHookClient(1, { runtimeDir: '/tmp' }); + expect(client.defaultAckTimeoutMs).toBe(1200); + const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 }); + expect(explicit.defaultAckTimeoutMs).toBe(50); + }); +}); diff --git a/packages/bridge/tests/pipe-watcher.test.ts b/packages/bridge/tests/pipe-watcher.test.ts index 26214c56..f5704b94 100644 --- a/packages/bridge/tests/pipe-watcher.test.ts +++ b/packages/bridge/tests/pipe-watcher.test.ts @@ -3,282 +3,312 @@ import { PipeWatcher } from '../src/pipe-watcher'; import type { HookProcessBaseInfo } from '../src/injector'; function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set }) { - let processes = initial.processes; - let live = initial.live; - const watcher = new PipeWatcher({ - listProcesses: () => processes, - // Defensively copy so the watcher can't mutate the test's reference. - listLivePipes: async () => new Set(live), - intervalMs: 60_000, // disable the internal timer; tests drive ticks manually - }); - return { - watcher, - setProcesses: (p: HookProcessBaseInfo[]) => { processes = p; }, - setLive: (s: Set) => { live = s; }, - }; + let processes = initial.processes; + let live = initial.live; + const watcher = new PipeWatcher({ + listProcesses: () => processes, + // Defensively copy so the watcher can't mutate the test's reference. + listLivePipes: async () => new Set(live), + intervalMs: 60_000, // disable the internal timer; tests drive ticks manually + }); + return { + watcher, + setProcesses: (p: HookProcessBaseInfo[]) => { + processes = p; + }, + setLive: (s: Set) => { + live = s; + }, + }; } type EventRow = [string, unknown]; function captureEvents(watcher: PipeWatcher): EventRow[] { - const events: EventRow[] = []; - watcher.on('process-discovered', info => events.push(['discovered', (info as HookProcessBaseInfo).pid])); - watcher.on('process-gone', pid => events.push(['gone', pid])); - watcher.on('pipe-up', pid => events.push(['up', pid])); - watcher.on('pipe-down', pid => events.push(['down', pid])); - return events; + const events: EventRow[] = []; + watcher.on('process-discovered', (info) => + events.push(['discovered', (info as HookProcessBaseInfo).pid]), + ); + watcher.on('process-gone', (pid) => events.push(['gone', pid])); + watcher.on('pipe-up', (pid) => events.push(['up', pid])); + watcher.on('pipe-down', (pid) => events.push(['down', pid])); + return events; } describe('PipeWatcher', () => { - it('passes the current process snapshot to pipe discovery', async () => { - const processes = [ - { pid: 1234, name: 'qq', path: '/opt/QQ/qq' }, - { pid: 5678, name: 'qq', path: '/opt/QQ/qq' }, - ]; - let observed: readonly HookProcessBaseInfo[] | undefined; - const watcher = new PipeWatcher({ - listProcesses: () => processes, - listLivePipes: async current => { - observed = current; - return new Set(); - }, - intervalMs: 60_000, + it('passes the current process snapshot to pipe discovery', async () => { + const processes = [ + { pid: 1234, name: 'qq', path: '/opt/QQ/qq' }, + { pid: 5678, name: 'qq', path: '/opt/QQ/qq' }, + ]; + let observed: readonly HookProcessBaseInfo[] | undefined; + const watcher = new PipeWatcher({ + listProcesses: () => processes, + listLivePipes: async (current) => { + observed = current; + return new Set(); + }, + intervalMs: 60_000, + }); + + await watcher.start(); + + expect(observed).toEqual(processes); + watcher.stop(); }); - await watcher.start(); + it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set([1234]), + }); + const events = captureEvents(ctx.watcher); + await ctx.watcher.start(); - expect(observed).toEqual(processes); - watcher.stop(); - }); + expect(events).toEqual([ + ['discovered', 1234], + ['up', 1234], + ]); + expect(ctx.watcher.isPipeLive(1234)).toBe(true); + expect(ctx.watcher.isProcessAlive(1234)).toBe(true); - it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => { - const ctx = setupWatcher({ - processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], - live: new Set([1234]), - }); - const events = captureEvents(ctx.watcher); - await ctx.watcher.start(); - - expect(events).toEqual([ - ['discovered', 1234], - ['up', 1234], - ]); - expect(ctx.watcher.isPipeLive(1234)).toBe(true); - expect(ctx.watcher.isProcessAlive(1234)).toBe(true); - - ctx.watcher.stop(); - }); - - it('pipe-down emitted when a previously-live pipe disappears', async () => { - const ctx = setupWatcher({ - processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], - live: new Set([1234]), - }); - await ctx.watcher.start(); - const events = captureEvents(ctx.watcher); - - ctx.setLive(new Set()); - await ctx.watcher.tickNow(); - - expect(events).toEqual([['down', 1234]]); - expect(ctx.watcher.isPipeLive(1234)).toBe(false); - ctx.watcher.stop(); - }); - - it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => { - const ctx = setupWatcher({ - processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], - live: new Set([1234]), - }); - await ctx.watcher.start(); - const events = captureEvents(ctx.watcher); - - ctx.setProcesses([]); - ctx.setLive(new Set()); - await ctx.watcher.tickNow(); - - expect(events).toEqual([ - ['down', 1234], - ['gone', 1234], - ]); - ctx.watcher.stop(); - }); - - it('ignores live pipes whose process is not running', async () => { - const ctx = setupWatcher({ - processes: [], - live: new Set([9999]), - }); - const events = captureEvents(ctx.watcher); - await ctx.watcher.start(); - - expect(events).toEqual([]); - expect(ctx.watcher.isPipeLive(9999)).toBe(false); - ctx.watcher.stop(); - }); - - it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => { - const ctx = setupWatcher({ - processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], - live: new Set(), - }); - await ctx.watcher.start(); - const events = captureEvents(ctx.watcher); - - ctx.setLive(new Set([1234])); - await ctx.watcher.tickNow(); - expect(events).toEqual([['up', 1234]]); - - ctx.setLive(new Set()); - await ctx.watcher.tickNow(); - expect(events).toEqual([['up', 1234], ['down', 1234]]); - - ctx.setLive(new Set([1234])); - await ctx.watcher.tickNow(); - expect(events).toEqual([['up', 1234], ['down', 1234], ['up', 1234]]); - - ctx.watcher.stop(); - }); - - it('does not double-emit on idempotent ticks (no state change)', async () => { - const ctx = setupWatcher({ - processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], - live: new Set([1234]), - }); - await ctx.watcher.start(); - const events = captureEvents(ctx.watcher); - - await ctx.watcher.tickNow(); - await ctx.watcher.tickNow(); - - expect(events).toEqual([]); - ctx.watcher.stop(); - }); - - it('emits "tick" after every poll', async () => { - const ctx = setupWatcher({ processes: [], live: new Set() }); - let ticks = 0; - ctx.watcher.on('tick', () => { ticks++; }); - - await ctx.watcher.start(); - expect(ticks).toBe(1); - - await ctx.watcher.tickNow(); - expect(ticks).toBe(2); - - ctx.watcher.stop(); - }); - - it('wake() pulls the next tick forward', async () => { - const ctx = setupWatcher({ - processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], - live: new Set(), - }); - await ctx.watcher.start(); - const events = captureEvents(ctx.watcher); - - // Wait on 'tick' rather than guessing how many event-loop turns - // setTimeout(0) needs (it's clamped to ~1ms and races setImmediate). - const nextTick = new Promise(resolve => ctx.watcher.once('tick', () => resolve())); - ctx.setLive(new Set([1234])); - ctx.watcher.wake(); - await nextTick; - - expect(events).toEqual([['up', 1234]]); - ctx.watcher.stop(); - }); - - it('survives a throwing listProcesses without crashing the watcher', async () => { - let processes: HookProcessBaseInfo[] = []; - let live = new Set(); - let shouldThrow = true; - const watcher = new PipeWatcher({ - listProcesses: () => { - if (shouldThrow) throw new Error('boom'); - return processes; - }, - listLivePipes: async () => new Set(live), - intervalMs: 60_000, + ctx.watcher.stop(); }); - await watcher.start(); - expect(watcher.isProcessAlive(1234)).toBe(false); + it('pipe-down emitted when a previously-live pipe disappears', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set([1234]), + }); + await ctx.watcher.start(); + const events = captureEvents(ctx.watcher); - shouldThrow = false; - processes = [{ pid: 1234, name: 'QQ.exe', path: '' }]; - live = new Set([1234]); - const events = captureEvents(watcher); - await watcher.tickNow(); + ctx.setLive(new Set()); + await ctx.watcher.tickNow(); - expect(events).toEqual([['discovered', 1234], ['up', 1234]]); - watcher.stop(); - }); - - it('preserves live sessions when pipe discovery temporarily fails', async () => { - let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }]; - let failPipeDiscovery = false; - const watcher = new PipeWatcher({ - listProcesses: () => processes, - listLivePipes: async () => { - if (failPipeDiscovery) throw new Error('permission denied'); - return new Set([1234]); - }, - intervalMs: 60_000, + expect(events).toEqual([['down', 1234]]); + expect(ctx.watcher.isPipeLive(1234)).toBe(false); + ctx.watcher.stop(); }); - await watcher.start(); - expect(watcher.isPipeLive(1234)).toBe(true); - const events = captureEvents(watcher); + it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set([1234]), + }); + await ctx.watcher.start(); + const events = captureEvents(ctx.watcher); - failPipeDiscovery = true; - await watcher.tickNow(); + ctx.setProcesses([]); + ctx.setLive(new Set()); + await ctx.watcher.tickNow(); - expect(events).toEqual([]); - expect(watcher.isProcessAlive(1234)).toBe(true); - expect(watcher.isPipeLive(1234)).toBe(true); - - processes = []; - await watcher.tickNow(); - - expect(events).toEqual([['down', 1234], ['gone', 1234]]); - expect(watcher.isProcessAlive(1234)).toBe(false); - expect(watcher.isPipeLive(1234)).toBe(false); - watcher.stop(); - }); - - it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => { - let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }]; - let live = new Set([1234]); - const watcher = new PipeWatcher({ - listProcesses: () => result, - listLivePipes: async () => new Set(live), - intervalMs: 60_000, + expect(events).toEqual([ + ['down', 1234], + ['gone', 1234], + ]); + ctx.watcher.stop(); }); - await watcher.start(); - expect(watcher.isProcessAlive(1234)).toBe(true); - expect(watcher.isPipeLive(1234)).toBe(true); + it('ignores live pipes whose process is not running', async () => { + const ctx = setupWatcher({ + processes: [], + live: new Set([9999]), + }); + const events = captureEvents(ctx.watcher); + await ctx.watcher.start(); - const events = captureEvents(watcher); + expect(events).toEqual([]); + expect(ctx.watcher.isPipeLive(9999)).toBe(false); + ctx.watcher.stop(); + }); - // Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ - // hot-update). Prior process + pipe state MUST be preserved — no teardown. - result = null; - await watcher.tickNow(); - expect(events).toEqual([]); - expect(watcher.isProcessAlive(1234)).toBe(true); - expect(watcher.isPipeLive(1234)).toBe(true); + it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set(), + }); + await ctx.watcher.start(); + const events = captureEvents(ctx.watcher); - // Enumeration recovers with the same set → still no churn. - result = [{ pid: 1234, name: 'qq', path: '' }]; - await watcher.tickNow(); - expect(events).toEqual([]); + ctx.setLive(new Set([1234])); + await ctx.watcher.tickNow(); + expect(events).toEqual([['up', 1234]]); - // A REAL disappearance (empty list, not null) still fires the teardown. - result = []; - live = new Set(); - await watcher.tickNow(); - expect(events).toEqual([['down', 1234], ['gone', 1234]]); - watcher.stop(); - }); + ctx.setLive(new Set()); + await ctx.watcher.tickNow(); + expect(events).toEqual([ + ['up', 1234], + ['down', 1234], + ]); + + ctx.setLive(new Set([1234])); + await ctx.watcher.tickNow(); + expect(events).toEqual([ + ['up', 1234], + ['down', 1234], + ['up', 1234], + ]); + + ctx.watcher.stop(); + }); + + it('does not double-emit on idempotent ticks (no state change)', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set([1234]), + }); + await ctx.watcher.start(); + const events = captureEvents(ctx.watcher); + + await ctx.watcher.tickNow(); + await ctx.watcher.tickNow(); + + expect(events).toEqual([]); + ctx.watcher.stop(); + }); + + it('emits "tick" after every poll', async () => { + const ctx = setupWatcher({ processes: [], live: new Set() }); + let ticks = 0; + ctx.watcher.on('tick', () => { + ticks++; + }); + + await ctx.watcher.start(); + expect(ticks).toBe(1); + + await ctx.watcher.tickNow(); + expect(ticks).toBe(2); + + ctx.watcher.stop(); + }); + + it('wake() pulls the next tick forward', async () => { + const ctx = setupWatcher({ + processes: [{ pid: 1234, name: 'QQ.exe', path: '' }], + live: new Set(), + }); + await ctx.watcher.start(); + const events = captureEvents(ctx.watcher); + + // Wait on 'tick' rather than guessing how many event-loop turns + // setTimeout(0) needs (it's clamped to ~1ms and races setImmediate). + const nextTick = new Promise((resolve) => ctx.watcher.once('tick', () => resolve())); + ctx.setLive(new Set([1234])); + ctx.watcher.wake(); + await nextTick; + + expect(events).toEqual([['up', 1234]]); + ctx.watcher.stop(); + }); + + it('survives a throwing listProcesses without crashing the watcher', async () => { + let processes: HookProcessBaseInfo[] = []; + let live = new Set(); + let shouldThrow = true; + const watcher = new PipeWatcher({ + listProcesses: () => { + if (shouldThrow) { + throw new Error('boom'); + } + + return processes; + }, + listLivePipes: async () => new Set(live), + intervalMs: 60_000, + }); + + await watcher.start(); + expect(watcher.isProcessAlive(1234)).toBe(false); + + shouldThrow = false; + processes = [{ pid: 1234, name: 'QQ.exe', path: '' }]; + live = new Set([1234]); + const events = captureEvents(watcher); + await watcher.tickNow(); + + expect(events).toEqual([ + ['discovered', 1234], + ['up', 1234], + ]); + watcher.stop(); + }); + + it('preserves live sessions when pipe discovery temporarily fails', async () => { + let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }]; + let failPipeDiscovery = false; + const watcher = new PipeWatcher({ + listProcesses: () => processes, + listLivePipes: async () => { + if (failPipeDiscovery) { + throw new Error('permission denied'); + } + + return new Set([1234]); + }, + intervalMs: 60_000, + }); + + await watcher.start(); + expect(watcher.isPipeLive(1234)).toBe(true); + const events = captureEvents(watcher); + + failPipeDiscovery = true; + await watcher.tickNow(); + + expect(events).toEqual([]); + expect(watcher.isProcessAlive(1234)).toBe(true); + expect(watcher.isPipeLive(1234)).toBe(true); + + processes = []; + await watcher.tickNow(); + + expect(events).toEqual([ + ['down', 1234], + ['gone', 1234], + ]); + expect(watcher.isProcessAlive(1234)).toBe(false); + expect(watcher.isPipeLive(1234)).toBe(false); + watcher.stop(); + }); + + it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => { + let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }]; + let live = new Set([1234]); + const watcher = new PipeWatcher({ + listProcesses: () => result, + listLivePipes: async () => new Set(live), + intervalMs: 60_000, + }); + + await watcher.start(); + expect(watcher.isProcessAlive(1234)).toBe(true); + expect(watcher.isPipeLive(1234)).toBe(true); + + const events = captureEvents(watcher); + + // Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ + // hot-update). Prior process + pipe state MUST be preserved — no teardown. + result = null; + await watcher.tickNow(); + expect(events).toEqual([]); + expect(watcher.isProcessAlive(1234)).toBe(true); + expect(watcher.isPipeLive(1234)).toBe(true); + + // Enumeration recovers with the same set → still no churn. + result = [{ pid: 1234, name: 'qq', path: '' }]; + await watcher.tickNow(); + expect(events).toEqual([]); + + // A REAL disappearance (empty list, not null) still fires the teardown. + result = []; + live = new Set(); + await watcher.tickNow(); + expect(events).toEqual([ + ['down', 1234], + ['gone', 1234], + ]); + watcher.stop(); + }); }); diff --git a/packages/bridge/tests/process-enumerator.test.ts b/packages/bridge/tests/process-enumerator.test.ts index 6d45d1de..51233e46 100644 --- a/packages/bridge/tests/process-enumerator.test.ts +++ b/packages/bridge/tests/process-enumerator.test.ts @@ -5,51 +5,53 @@ import type { HookProcessBaseInfo } from '../src/injector'; const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' }); describe('createNativeProcessEnumerator', () => { - describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => { - it('returns the sync lister result', async () => { - const en = createNativeProcessEnumerator({ - addonPath: null, - fallbackSync: () => [QQ(10), QQ(20)], - processName: 'qq', - }); - expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]); - en.dispose(); + describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => { + it('returns the sync lister result', async () => { + const en = createNativeProcessEnumerator({ + addonPath: null, + fallbackSync: () => [QQ(10), QQ(20)], + processName: 'qq', + }); + expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]); + en.dispose(); + }); + + it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => { + const en = createNativeProcessEnumerator({ + addonPath: null, + fallbackSync: () => { + throw new Error('boom'); + }, + processName: 'qq', + }); + expect(await en.enumerate()).toBeNull(); + en.dispose(); + }); }); - it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => { - const en = createNativeProcessEnumerator({ - addonPath: null, - fallbackSync: () => { throw new Error('boom'); }, - processName: 'qq', - }); - expect(await en.enumerate()).toBeNull(); - en.dispose(); + describe('worker isolation that cannot load the addon → permanent fallback', () => { + it('falls back to the sync lister after the worker reports a fatal load error', async () => { + const fallback = vi.fn(() => [QQ(7)]); + const en = createNativeProcessEnumerator({ + // A path that exists nowhere → process.dlopen throws in the worker → + // the worker posts 'fatal' → isolation is abandoned for good. + addonPath: '/nonexistent/snowluma-test.node', + fallbackSync: fallback, + processName: 'qq', + timeoutMs: 200, + }); + + // First call spawns the worker; the fatal message drains it to UNKNOWN. + const first = await en.enumerate(); + expect(first).toBeNull(); + + // Give the 'fatal' message a moment to flip isolationBroken if it hadn't + // already, then subsequent calls take the synchronous fallback. + await new Promise((r) => setTimeout(r, 50)); + const second = await en.enumerate(); + expect(second).toEqual([QQ(7)]); + expect(fallback).toHaveBeenCalled(); + en.dispose(); + }); }); - }); - - describe('worker isolation that cannot load the addon → permanent fallback', () => { - it('falls back to the sync lister after the worker reports a fatal load error', async () => { - const fallback = vi.fn(() => [QQ(7)]); - const en = createNativeProcessEnumerator({ - // A path that exists nowhere → process.dlopen throws in the worker → - // the worker posts 'fatal' → isolation is abandoned for good. - addonPath: '/nonexistent/snowluma-test.node', - fallbackSync: fallback, - processName: 'qq', - timeoutMs: 200, - }); - - // First call spawns the worker; the fatal message drains it to UNKNOWN. - const first = await en.enumerate(); - expect(first).toBeNull(); - - // Give the 'fatal' message a moment to flip isolationBroken if it hadn't - // already, then subsequent calls take the synchronous fallback. - await new Promise((r) => setTimeout(r, 50)); - const second = await en.enumerate(); - expect(second).toEqual([QQ(7)]); - expect(fallback).toHaveBeenCalled(); - en.dispose(); - }); - }); }); diff --git a/packages/bridge/tests/qq-hook-client.test.ts b/packages/bridge/tests/qq-hook-client.test.ts index 4411f57e..f3f59d78 100644 --- a/packages/bridge/tests/qq-hook-client.test.ts +++ b/packages/bridge/tests/qq-hook-client.test.ts @@ -4,858 +4,1008 @@ import os from 'os'; import path from 'path'; import { Duplex } from 'stream'; import { - currentRequestId, - getLogLevel, - runWithRequestId, - setLogLevel, - subscribeLogs, - type LogEntry, + currentRequestId, + getLogLevel, + runWithRequestId, + setLogLevel, + subscribeLogs, + type LogEntry, } from '@snowluma/common/logger'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { - HEADER_SIZE, - listLiveLinuxPipePids, - MAX_PIPE_BODY_BYTES, - MAX_PIPE_CMD_BYTES, - MAX_PIPE_MSG_BYTES, - PIPE_MAGIC, - PIPE_VERSION, - PipeOp, - QqHookClient, + HEADER_SIZE, + listLiveLinuxPipePids, + MAX_PIPE_BODY_BYTES, + MAX_PIPE_CMD_BYTES, + MAX_PIPE_MSG_BYTES, + PIPE_MAGIC, + PIPE_VERSION, + PipeOp, + QqHookClient, } from '../src/qq-hook-client'; let tmpDir: string | null = null; const previousLogLevel = getLogLevel(); async function makeRuntimeDir(): Promise { - tmpDir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-hook-')); - return tmpDir; + tmpDir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-hook-')); + return tmpDir; } function pipeFrame({ - op, - requestId = 0, - status = 0, - value0 = 0n, - cmd = '', - message = '', - body = Buffer.alloc(0), + op, + requestId = 0, + status = 0, + value0 = 0n, + cmd = '', + message = '', + body = Buffer.alloc(0), }: { - op: PipeOp; - requestId?: number; - status?: number; - value0?: bigint; - cmd?: string; - message?: string; - body?: Buffer; + op: PipeOp; + requestId?: number; + status?: number; + value0?: bigint; + cmd?: string; + message?: string; + body?: Buffer; }): Buffer { - const cmdBytes = Buffer.from(cmd); - const messageBytes = Buffer.from(message); - const header = Buffer.alloc(HEADER_SIZE); - header.writeUInt32LE(PIPE_MAGIC, 0); - header.writeUInt16LE(PIPE_VERSION, 4); - header.writeUInt16LE(op, 6); - header.writeUInt32LE(requestId, 8); - header.writeInt32LE(status, 12); - header.writeUInt32LE(cmdBytes.length, 20); - header.writeUInt32LE(messageBytes.length, 24); - header.writeUInt32LE(body.length, 28); - header.writeBigUInt64LE(value0, 32); - return Buffer.concat([header, cmdBytes, messageBytes, body]); + const cmdBytes = Buffer.from(cmd); + const messageBytes = Buffer.from(message); + const header = Buffer.alloc(HEADER_SIZE); + header.writeUInt32LE(PIPE_MAGIC, 0); + header.writeUInt16LE(PIPE_VERSION, 4); + header.writeUInt16LE(op, 6); + header.writeUInt32LE(requestId, 8); + header.writeInt32LE(status, 12); + header.writeUInt32LE(cmdBytes.length, 20); + header.writeUInt32LE(messageBytes.length, 24); + header.writeUInt32LE(body.length, 28); + header.writeBigUInt64LE(value0, 32); + return Buffer.concat([header, cmdBytes, messageBytes, body]); } function readSendFrame(payload: Buffer): { - requestId: number; - cmd: string; - body: Buffer; + requestId: number; + cmd: string; + body: Buffer; } { - const cmdLength = payload.readUInt32LE(20); - const messageLength = payload.readUInt32LE(24); - const bodyLength = payload.readUInt32LE(28); - const cmdStart = HEADER_SIZE; - const bodyStart = cmdStart + cmdLength + messageLength; - return { - requestId: payload.readUInt32LE(8), - cmd: payload.subarray(cmdStart, cmdStart + cmdLength).toString(), - body: Buffer.from(payload.subarray(bodyStart, bodyStart + bodyLength)), - }; + const cmdLength = payload.readUInt32LE(20); + const messageLength = payload.readUInt32LE(24); + const bodyLength = payload.readUInt32LE(28); + const cmdStart = HEADER_SIZE; + const bodyStart = cmdStart + cmdLength + messageLength; + return { + requestId: payload.readUInt32LE(8), + cmd: payload.subarray(cmdStart, cmdStart + cmdLength).toString(), + body: Buffer.from(payload.subarray(bodyStart, bodyStart + bodyLength)), + }; } function mockControlPipe( - pid: number, - onWrite: (socket: net.Socket, payload: Buffer) => void, + pid: number, + onWrite: (socket: net.Socket, payload: Buffer) => void, ): ReturnType { - return vi.spyOn(net, 'createConnection').mockImplementation((() => { - const socket = new Duplex({ - read() { /* peer data is injected with emit('data') */ }, - write(chunk, _encoding, callback) { - onWrite(socket, Buffer.from(chunk)); - callback(); - }, - }) as net.Socket; - queueMicrotask(() => { - socket.emit('connect'); - queueMicrotask(() => socket.emit('data', pipeFrame({ - op: PipeOp.hello, - value0: BigInt(pid), - }))); - }); - return socket; - }) as typeof net.createConnection); + return vi.spyOn(net, 'createConnection').mockImplementation((() => { + const socket = new Duplex({ + read() { + /* peer data is injected with emit('data') */ + }, + write(chunk, _encoding, callback) { + onWrite(socket, Buffer.from(chunk)); + callback(); + }, + }) as net.Socket; + queueMicrotask(() => { + socket.emit('connect'); + queueMicrotask(() => + socket.emit( + 'data', + pipeFrame({ + op: PipeOp.hello, + value0: BigInt(pid), + }), + ), + ); + }); + return socket; + }) as typeof net.createConnection); } function traceMessages(entries: LogEntry[]): string[] { - return entries - .filter((entry) => entry.level === 'trace' && entry.scope === 'QQHook.Packet') - .map((entry) => entry.message); + return entries + .filter((entry) => entry.level === 'trace' && entry.scope === 'QQHook.Packet') + .map((entry) => entry.message); } function runtimeTrace(entries: LogEntry[]): LogEntry[] { - return entries.filter( - (entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime', - ); + return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime'); } afterEach(async () => { - setLogLevel(previousLogLevel); - vi.restoreAllMocks(); - if (!tmpDir) return; - await rm(tmpDir, { recursive: true, force: true }); - tmpDir = null; + setLogLevel(previousLogLevel); + vi.restoreAllMocks(); + + if (!tmpDir) { + return; + } + + await rm(tmpDir, { recursive: true, force: true }); + tmpDir = null; }); describe('listLiveLinuxPipePids', () => { - it('ignores stale-looking control socket names when the probe rejects them', async () => { - const runtimeDir = await makeRuntimeDir(); - await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), ''); - await writeFile(path.join(runtimeDir, 'mojo.55.recv.sock'), ''); + it('ignores stale-looking control socket names when the probe rejects them', async () => { + const runtimeDir = await makeRuntimeDir(); + await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), ''); + await writeFile(path.join(runtimeDir, 'mojo.55.recv.sock'), ''); - const pids = await listLiveLinuxPipePids(runtimeDir, async () => false); + const pids = await listLiveLinuxPipePids(runtimeDir, async () => false); - expect([...pids]).toEqual([]); - }); + expect([...pids]).toEqual([]); + }); - it('returns only connectable control sockets', async () => { - const runtimeDir = await makeRuntimeDir(); - await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), ''); - await writeFile(path.join(runtimeDir, 'mojo.56.control.sock'), ''); - await writeFile(path.join(runtimeDir, 'mojo.56.recv.sock'), ''); - await writeFile(path.join(runtimeDir, 'mojo.not-a-pid.control.sock'), ''); + it('returns only connectable control sockets', async () => { + const runtimeDir = await makeRuntimeDir(); + await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), ''); + await writeFile(path.join(runtimeDir, 'mojo.56.control.sock'), ''); + await writeFile(path.join(runtimeDir, 'mojo.56.recv.sock'), ''); + await writeFile(path.join(runtimeDir, 'mojo.not-a-pid.control.sock'), ''); - const probe = vi.fn(async (socketPath: string) => socketPath.endsWith('mojo.56.control.sock')); - const pids = await listLiveLinuxPipePids(runtimeDir, probe); + const probe = vi.fn(async (socketPath: string) => + socketPath.endsWith('mojo.56.control.sock'), + ); + const pids = await listLiveLinuxPipePids(runtimeDir, probe); - expect([...pids]).toEqual([56]); - expect(probe).toHaveBeenCalledTimes(2); - }); + expect([...pids]).toEqual([56]); + expect(probe).toHaveBeenCalledTimes(2); + }); }); describe('QqHookClient — pipe frame limits', () => { - it('forwards a probed account as a native identity hint without changing login state', async () => { - const pid = 778819; - const writes: Buffer[] = []; - const connection = mockControlPipe(pid, (socket, payload) => { - writes.push(Buffer.from(payload)); - const requestId = payload.readUInt32LE(8); - queueMicrotask(() => socket.emit('data', pipeFrame({ - op: PipeOp.sendAck, - requestId, - }))); - }); - const client = new QqHookClient(pid); - try { - await client.reconcileLoginIdentity('10001'); - - expect(writes).toHaveLength(1); - expect(writes[0]!.readUInt16LE(6)).toBe(PipeOp.loginIdentityHint); - expect(writes[0]!.readBigUInt64LE(32)).toBe(10001n); - expect(client.getLoginState()).toEqual({ - loggedIn: false, - uin: '0', - uinNumber: 0n, - }); - } finally { - client.close(); - connection.mockRestore(); - } - }); - - it.each([ - ['command', 20, MAX_PIPE_CMD_BYTES], - ['message', 24, MAX_PIPE_MSG_BYTES], - ['body', 28, MAX_PIPE_BODY_BYTES], - ] as const)( - 'rejects an oversized inbound %s before waiting for its payload', - async (name, lengthOffset, limit) => { - const pid = 778830; - let socket: net.Socket | null = null; - const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { - socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket; - queueMicrotask(() => { - socket!.emit('connect'); - const header = Buffer.alloc(HEADER_SIZE); - header.writeUInt32LE(PIPE_MAGIC, 0); - header.writeUInt16LE(PIPE_VERSION, 4); - header.writeUInt16LE(PipeOp.hello, 6); - header.writeUInt32LE(limit + 1, lengthOffset); - socket!.emit('data', header); - }); - return socket; - }) as typeof net.createConnection); - const client = new QqHookClient(pid); - const connecting = client.connect().catch(() => undefined); - try { - const error = await new Promise((resolve, reject) => { - const timer = setTimeout( - () => reject(new Error('oversized frame was not rejected')), - 100, - ); - client.once('error', (reason: unknown) => { - clearTimeout(timer); - resolve(reason instanceof Error ? reason : new Error(String(reason))); - }); + it('forwards a probed account as a native identity hint without changing login state', async () => { + const pid = 778819; + const writes: Buffer[] = []; + const connection = mockControlPipe(pid, (socket, payload) => { + writes.push(Buffer.from(payload)); + const requestId = payload.readUInt32LE(8); + queueMicrotask(() => + socket.emit( + 'data', + pipeFrame({ + op: PipeOp.sendAck, + requestId, + }), + ), + ); }); + const client = new QqHookClient(pid); - expect(error.message).toBe( - `pipe frame ${name} length ${limit + 1} exceeds limit ${limit}`, - ); - expect(socket?.destroyed).toBe(true); - } finally { - client.close(); - await connecting; - createConnection.mockRestore(); - } + try { + await client.reconcileLoginIdentity('10001'); + + expect(writes).toHaveLength(1); + expect(writes[0]!.readUInt16LE(6)).toBe(PipeOp.loginIdentityHint); + expect(writes[0]!.readBigUInt64LE(32)).toBe(10001n); + expect(client.getLoginState()).toEqual({ + loggedIn: false, + uin: '0', + uinNumber: 0n, + }); + } finally { + client.close(); + connection.mockRestore(); + } }); - it('rejects an oversized outbound command before writing to the pipe', async () => { - const pid = 778831; - const onWrite = vi.fn(); - const connection = mockControlPipe(pid, onWrite); - const client = new QqHookClient(pid); - try { - await client.connect(); + it.each([ + ['command', 20, MAX_PIPE_CMD_BYTES], + ['message', 24, MAX_PIPE_MSG_BYTES], + ['body', 28, MAX_PIPE_BODY_BYTES], + ] as const)( + 'rejects an oversized inbound %s before waiting for its payload', + async (name, lengthOffset, limit) => { + const pid = 778830; + let socket: net.Socket | null = null; + const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { + socket = new Duplex({ + read() { + /* peer data is injected with emit('data') */ + }, + }) as net.Socket; + queueMicrotask(() => { + socket!.emit('connect'); + const header = Buffer.alloc(HEADER_SIZE); + header.writeUInt32LE(PIPE_MAGIC, 0); + header.writeUInt16LE(PIPE_VERSION, 4); + header.writeUInt16LE(PipeOp.hello, 6); + header.writeUInt32LE(limit + 1, lengthOffset); + socket!.emit('data', header); + }); + return socket; + }) as typeof net.createConnection); + const client = new QqHookClient(pid); + const connecting = client.connect().catch(() => undefined); - await expect(client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES + 1), Buffer.alloc(0), { - ackTimeoutMs: 25, - })).rejects.toThrow( - `pipe frame command length ${MAX_PIPE_CMD_BYTES + 1} exceeds limit ${MAX_PIPE_CMD_BYTES}`, - ); - expect(onWrite).not.toHaveBeenCalled(); - } finally { - client.close(); - connection.mockRestore(); - } - }); + try { + const error = await new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error('oversized frame was not rejected')), + 100, + ); + client.once('error', (reason: unknown) => { + clearTimeout(timer); + resolve(reason instanceof Error ? reason : new Error(String(reason))); + }); + }); - it('rejects an oversized outbound body before writing to the pipe', async () => { - const pid = 778832; - const onWrite = vi.fn(); - const connection = mockControlPipe(pid, onWrite); - const client = new QqHookClient(pid); - try { - await client.connect(); + expect(error.message).toBe( + `pipe frame ${name} length ${limit + 1} exceeds limit ${limit}`, + ); + expect(socket?.destroyed).toBe(true); + } finally { + client.close(); + await connecting; + createConnection.mockRestore(); + } + }, + ); - await expect(client.sendNoReply( - 'test.command', - Buffer.alloc(MAX_PIPE_BODY_BYTES + 1), - )).rejects.toThrow( - `pipe frame body length ${MAX_PIPE_BODY_BYTES + 1} exceeds limit ${MAX_PIPE_BODY_BYTES}`, - ); - expect(onWrite).not.toHaveBeenCalled(); - } finally { - client.close(); - connection.mockRestore(); - } - }); + it('rejects an oversized outbound command before writing to the pipe', async () => { + const pid = 778831; + const onWrite = vi.fn(); + const connection = mockControlPipe(pid, onWrite); + const client = new QqHookClient(pid); - it('accepts values exactly at the command limit', async () => { - const pid = 778833; - const connection = mockControlPipe(pid, (socket, payload) => { - const requestId = payload.readUInt32LE(8); - queueMicrotask(() => socket.emit('data', pipeFrame({ - op: PipeOp.sendAck, - requestId, - }))); + try { + await client.connect(); + + await expect( + client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES + 1), Buffer.alloc(0), { + ackTimeoutMs: 25, + }), + ).rejects.toThrow( + `pipe frame command length ${MAX_PIPE_CMD_BYTES + 1} exceeds limit ${MAX_PIPE_CMD_BYTES}`, + ); + expect(onWrite).not.toHaveBeenCalled(); + } finally { + client.close(); + connection.mockRestore(); + } }); - const client = new QqHookClient(pid); - try { - await expect(client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES), Buffer.alloc(0))) - .resolves.toMatchObject({ requestId: 1 }); - } finally { - client.close(); - connection.mockRestore(); - } - }); - it('parses fragmented and coalesced frames without losing boundaries', async () => { - const pid = 778834; - const states: string[] = []; - const wire = Buffer.concat([ - pipeFrame({ op: PipeOp.hello, value0: BigInt(pid), message: 'control' }), - pipeFrame({ op: PipeOp.loginState, status: 1, value0: 10001n, message: '10001' }), - pipeFrame({ op: PipeOp.loginState, status: 1, value0: 10002n, message: '10002' }), - ]); - const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { - const socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket; - queueMicrotask(() => { - socket.emit('connect'); - queueMicrotask(() => { - const cuts = [1, 7, 39, 40, 44, 83, wire.length - 1, wire.length]; - let offset = 0; - for (const end of cuts) { - if (end > offset) socket.emit('data', wire.subarray(offset, end)); - offset = end; - } + it('rejects an oversized outbound body before writing to the pipe', async () => { + const pid = 778832; + const onWrite = vi.fn(); + const connection = mockControlPipe(pid, onWrite); + const client = new QqHookClient(pid); + + try { + await client.connect(); + + await expect( + client.sendNoReply('test.command', Buffer.alloc(MAX_PIPE_BODY_BYTES + 1)), + ).rejects.toThrow( + `pipe frame body length ${MAX_PIPE_BODY_BYTES + 1} exceeds limit ${MAX_PIPE_BODY_BYTES}`, + ); + expect(onWrite).not.toHaveBeenCalled(); + } finally { + client.close(); + connection.mockRestore(); + } + }); + + it('accepts values exactly at the command limit', async () => { + const pid = 778833; + const connection = mockControlPipe(pid, (socket, payload) => { + const requestId = payload.readUInt32LE(8); + queueMicrotask(() => + socket.emit( + 'data', + pipeFrame({ + op: PipeOp.sendAck, + requestId, + }), + ), + ); }); - }); - return socket; - }) as typeof net.createConnection); - const client = new QqHookClient(pid); - client.on('loginState', state => states.push(state.uin)); - try { - const hello = await client.connect(); + const client = new QqHookClient(pid); - expect(hello).toMatchObject({ pipeName: 'control', pid }); - expect(states).toEqual(['10001', '10002']); - } finally { - client.close(); - createConnection.mockRestore(); - } - }); + try { + await expect( + client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES), Buffer.alloc(0)), + ).resolves.toMatchObject({ requestId: 1 }); + } finally { + client.close(); + connection.mockRestore(); + } + }); - it('accepts an inbound message exactly at the native limit', async () => { - const pid = 778835; - const message = 'x'.repeat(MAX_PIPE_MSG_BYTES); - const frame = pipeFrame({ op: PipeOp.hello, value0: BigInt(pid), message }); - const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { - const socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket; - queueMicrotask(() => { - socket.emit('connect'); - queueMicrotask(() => { - for (let offset = 0; offset < frame.length; offset += 1024) { - socket.emit('data', frame.subarray(offset, offset + 1024)); - } - }); - }); - return socket; - }) as typeof net.createConnection); - const client = new QqHookClient(pid); - try { - await expect(client.connect()).resolves.toMatchObject({ pipeName: message, pid }); - } finally { - client.close(); - createConnection.mockRestore(); - } - }); + it('parses fragmented and coalesced frames without losing boundaries', async () => { + const pid = 778834; + const states: string[] = []; + const wire = Buffer.concat([ + pipeFrame({ op: PipeOp.hello, value0: BigInt(pid), message: 'control' }), + pipeFrame({ op: PipeOp.loginState, status: 1, value0: 10001n, message: '10001' }), + pipeFrame({ op: PipeOp.loginState, status: 1, value0: 10002n, message: '10002' }), + ]); + const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { + const socket = new Duplex({ + read() { + /* peer data is injected with emit('data') */ + }, + }) as net.Socket; + queueMicrotask(() => { + socket.emit('connect'); + queueMicrotask(() => { + const cuts = [1, 7, 39, 40, 44, 83, wire.length - 1, wire.length]; + let offset = 0; + + for (const end of cuts) { + if (end > offset) { + socket.emit('data', wire.subarray(offset, end)); + } + + offset = end; + } + }); + }); + return socket; + }) as typeof net.createConnection); + const client = new QqHookClient(pid); + client.on('loginState', (state) => states.push(state.uin)); + + try { + const hello = await client.connect(); + + expect(hello).toMatchObject({ pipeName: 'control', pid }); + expect(states).toEqual(['10001', '10002']); + } finally { + client.close(); + createConnection.mockRestore(); + } + }); + + it('accepts an inbound message exactly at the native limit', async () => { + const pid = 778835; + const message = 'x'.repeat(MAX_PIPE_MSG_BYTES); + const frame = pipeFrame({ op: PipeOp.hello, value0: BigInt(pid), message }); + const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { + const socket = new Duplex({ + read() { + /* peer data is injected with emit('data') */ + }, + }) as net.Socket; + queueMicrotask(() => { + socket.emit('connect'); + queueMicrotask(() => { + for (let offset = 0; offset < frame.length; offset += 1024) { + socket.emit('data', frame.subarray(offset, offset + 1024)); + } + }); + }); + return socket; + }) as typeof net.createConnection); + const client = new QqHookClient(pid); + + try { + await expect(client.connect()).resolves.toMatchObject({ pipeName: message, pid }); + } finally { + client.close(); + createConnection.mockRestore(); + } + }); }); describe('QqHookClient — runtime TRACE', () => { - it('records control and receive pipe hello lifecycles under the parent request', async () => { - const pid = 778820; - const entries: LogEntry[] = []; - let connectionIndex = 0; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { - const kind = connectionIndex === 0 ? 'control' : 'recv'; - connectionIndex += 1; - const socket = new Duplex({ - read() { /* peer data is injected with emit('data') */ }, - }) as net.Socket; - queueMicrotask(() => { - socket.emit('connect'); - queueMicrotask(() => socket.emit('data', pipeFrame({ - op: PipeOp.hello, - value0: BigInt(pid), - message: `${kind}-fixture`, - }))); - }); - return socket; - }) as typeof net.createConnection); - const client = new QqHookClient(pid); - try { - await runWithRequestId(4201, () => client.connectAll()); + it('records control and receive pipe hello lifecycles under the parent request', async () => { + const pid = 778820; + const entries: LogEntry[] = []; + let connectionIndex = 0; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { + const kind = connectionIndex === 0 ? 'control' : 'recv'; + connectionIndex += 1; + const socket = new Duplex({ + read() { + /* peer data is injected with emit('data') */ + }, + }) as net.Socket; + queueMicrotask(() => { + socket.emit('connect'); + queueMicrotask(() => + socket.emit( + 'data', + pipeFrame({ + op: PipeOp.hello, + value0: BigInt(pid), + message: `${kind}-fixture`, + }), + ), + ); + }); + return socket; + }) as typeof net.createConnection); + const client = new QqHookClient(pid); - const trace = runtimeTrace(entries); - expect(trace).toHaveLength(6); - expect(trace.every((entry) => entry.req === 4201)).toBe(true); - expect(trace.map((entry) => entry.message)).toEqual([ - expect.stringMatching(/^hook_pipe_start pid=778820 kind=control pipeName=.*$/), - expect.stringMatching(/^hook_pipe_branch pid=778820 kind=control branch=socket_connected$/), - expect.stringMatching(/^hook_pipe_terminal pid=778820 kind=control outcome=completed reason=hello_received hello=\{pipeName:"control-fixture",pid:778820,recvPipe:false\} elapsedMs=\d+$/), - expect.stringMatching(/^hook_pipe_start pid=778820 kind=recv pipeName=.*$/), - expect.stringMatching(/^hook_pipe_branch pid=778820 kind=recv branch=socket_connected$/), - expect.stringMatching(/^hook_pipe_terminal pid=778820 kind=recv outcome=completed reason=hello_received hello=\{pipeName:"recv-fixture",pid:778820,recvPipe:true\} elapsedMs=\d+$/), - ]); - } finally { - unsubscribe(); - client.close(); - createConnection.mockRestore(); - } - }); + try { + await runWithRequestId(4201, () => client.connectAll()); - it('records a pre-request connection failure without a pipe request id', async () => { - const pid = 778821; - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { - const socket = new Duplex({ read() { /* no peer */ } }) as net.Socket; - queueMicrotask(() => socket.emit('error', new Error('fixture connect failure'))); - return socket; - }) as typeof net.createConnection); - const client = new QqHookClient(pid); - try { - await expect(client.connect()).rejects.toThrow('fixture connect failure'); - - const trace = runtimeTrace(entries); - expect(trace).toHaveLength(2); - expect(trace.every((entry) => entry.req !== undefined)).toBe(true); - expect(trace[0]!.req).toBe(trace[1]!.req); - expect(trace.map((entry) => entry.message)).toEqual([ - expect.stringMatching(/^hook_pipe_start pid=778821 kind=control pipeName=.*$/), - expect.stringMatching(/^hook_pipe_terminal pid=778821 kind=control outcome=failed reason=connect_failed error="fixture connect failure" elapsedMs=\d+$/), - ]); - expect(trace.map((entry) => entry.message).join('\n')).not.toContain('requestId='); - } finally { - unsubscribe(); - client.close(); - createConnection.mockRestore(); - } - }); - - it('assigns fresh request contexts to material login and close events only', async () => { - const pid = 778822; - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const connection = mockControlPipe(pid, () => { /* no packet writes */ }); - const client = new QqHookClient(pid); - const eventRequestIds: Array<{ event: 'login' | 'close'; req: number | undefined }> = []; - client.on('loginState', () => { - eventRequestIds.push({ event: 'login', req: currentRequestId() }); + const trace = runtimeTrace(entries); + expect(trace).toHaveLength(6); + expect(trace.every((entry) => entry.req === 4201)).toBe(true); + expect(trace.map((entry) => entry.message)).toEqual([ + expect.stringMatching(/^hook_pipe_start pid=778820 kind=control pipeName=.*$/), + expect.stringMatching( + /^hook_pipe_branch pid=778820 kind=control branch=socket_connected$/, + ), + expect.stringMatching( + /^hook_pipe_terminal pid=778820 kind=control outcome=completed reason=hello_received hello=\{pipeName:"control-fixture",pid:778820,recvPipe:false\} elapsedMs=\d+$/, + ), + expect.stringMatching(/^hook_pipe_start pid=778820 kind=recv pipeName=.*$/), + expect.stringMatching( + /^hook_pipe_branch pid=778820 kind=recv branch=socket_connected$/, + ), + expect.stringMatching( + /^hook_pipe_terminal pid=778820 kind=recv outcome=completed reason=hello_received hello=\{pipeName:"recv-fixture",pid:778820,recvPipe:true\} elapsedMs=\d+$/, + ), + ]); + } finally { + unsubscribe(); + client.close(); + createConnection.mockRestore(); + } }); - client.on('close', () => { - eventRequestIds.push({ event: 'close', req: currentRequestId() }); - }); - try { - await runWithRequestId(4202, () => client.connect()); - const controlSocket = connection.mock.results[0]!.value as net.Socket; - controlSocket.emit('data', pipeFrame({ - op: PipeOp.loginState, - status: 1, - value0: 123456n, - message: '123456', - })); - controlSocket.emit('data', pipeFrame({ - op: PipeOp.loginState, - status: 1, - value0: 123456n, - message: '123456', - })); - controlSocket.destroy(); - await new Promise((resolve) => setImmediate(resolve)); - const facts = runtimeTrace(entries).filter( - (entry) => entry.message.startsWith('hook_runtime_fact pid=778822 '), - ); - expect(facts).toHaveLength(2); - expect(facts.every((entry) => entry.req !== undefined)).toBe(true); - expect(facts[0]!.req).not.toBe(facts[1]!.req); - expect(facts.map((entry) => entry.message)).toEqual([ - 'hook_runtime_fact pid=778822 event=login_state_changed previousLoggedIn=false previousUin="0" loggedIn=true uin="123456"', - 'hook_runtime_fact pid=778822 event=pipe_closed kind=control loggedIn=true uin="123456"', - ]); - expect(eventRequestIds).toEqual([ - { event: 'login', req: facts[0]!.req }, - { event: 'login', req: undefined }, - { event: 'close', req: facts[1]!.req }, - ]); - } finally { - unsubscribe(); - client.close(); - connection.mockRestore(); - } - }); + it('records a pre-request connection failure without a pipe request id', async () => { + const pid = 778821; + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { + const socket = new Duplex({ + read() { + /* no peer */ + }, + }) as net.Socket; + queueMicrotask(() => socket.emit('error', new Error('fixture connect failure'))); + return socket; + }) as typeof net.createConnection); + const client = new QqHookClient(pid); + + try { + await expect(client.connect()).rejects.toThrow('fixture connect failure'); + + const trace = runtimeTrace(entries); + expect(trace).toHaveLength(2); + expect(trace.every((entry) => entry.req !== undefined)).toBe(true); + expect(trace[0]!.req).toBe(trace[1]!.req); + expect(trace.map((entry) => entry.message)).toEqual([ + expect.stringMatching(/^hook_pipe_start pid=778821 kind=control pipeName=.*$/), + expect.stringMatching( + /^hook_pipe_terminal pid=778821 kind=control outcome=failed reason=connect_failed error="fixture connect failure" elapsedMs=\d+$/, + ), + ]); + expect(trace.map((entry) => entry.message).join('\n')).not.toContain('requestId='); + } finally { + unsubscribe(); + client.close(); + createConnection.mockRestore(); + } + }); + + it('assigns fresh request contexts to material login and close events only', async () => { + const pid = 778822; + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const connection = mockControlPipe(pid, () => { + /* no packet writes */ + }); + const client = new QqHookClient(pid); + const eventRequestIds: Array<{ event: 'login' | 'close'; req: number | undefined }> = []; + client.on('loginState', () => { + eventRequestIds.push({ event: 'login', req: currentRequestId() }); + }); + client.on('close', () => { + eventRequestIds.push({ event: 'close', req: currentRequestId() }); + }); + + try { + await runWithRequestId(4202, () => client.connect()); + const controlSocket = connection.mock.results[0]!.value as net.Socket; + controlSocket.emit( + 'data', + pipeFrame({ + op: PipeOp.loginState, + status: 1, + value0: 123456n, + message: '123456', + }), + ); + controlSocket.emit( + 'data', + pipeFrame({ + op: PipeOp.loginState, + status: 1, + value0: 123456n, + message: '123456', + }), + ); + controlSocket.destroy(); + await new Promise((resolve) => setImmediate(resolve)); + + const facts = runtimeTrace(entries).filter((entry) => + entry.message.startsWith('hook_runtime_fact pid=778822 '), + ); + expect(facts).toHaveLength(2); + expect(facts.every((entry) => entry.req !== undefined)).toBe(true); + expect(facts[0]!.req).not.toBe(facts[1]!.req); + expect(facts.map((entry) => entry.message)).toEqual([ + 'hook_runtime_fact pid=778822 event=login_state_changed previousLoggedIn=false previousUin="0" loggedIn=true uin="123456"', + 'hook_runtime_fact pid=778822 event=pipe_closed kind=control loggedIn=true uin="123456"', + ]); + expect(eventRequestIds).toEqual([ + { event: 'login', req: facts[0]!.req }, + { event: 'login', req: undefined }, + { event: 'close', req: facts[1]!.req }, + ]); + } finally { + unsubscribe(); + client.close(); + connection.mockRestore(); + } + }); }); describe('QqHookClient — packet TRACE', () => { - it('records complete request and reply bodies with the real pipe request id', async () => { - const pid = 778810; - const requestBody = Buffer.from([ - 0x00, 0xff, ...Array.from({ length: 160 }, (_, index) => index & 0xff), - ]); - const replyBody = Buffer.from([0xff, 0x00, 0x7f]); - const entries: LogEntry[] = []; - const writes: Buffer[] = []; - let traceCountAtWrite = 0; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const connection = mockControlPipe(pid, (socket, payload) => { - const frame = readSendFrame(payload); - writes.push(payload); - traceCountAtWrite = traceMessages(entries).length; - queueMicrotask(() => { - socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId: frame.requestId })); - socket.emit('data', pipeFrame({ - op: PipeOp.sendReply, - requestId: frame.requestId, - status: 27, - message: 'fixture reply', - body: replyBody, - })); - }); - }); - const client = new QqHookClient(pid); - try { - const reply = await runWithRequestId( - 4101, - () => client.sendAndWait('OidbSvcTrpcTcp.0x1234_1', requestBody), - ); - - const sent = readSendFrame(writes[0]); - expect(sent).toMatchObject({ - requestId: 1, - cmd: 'OidbSvcTrpcTcp.0x1234_1', - body: requestBody, - }); - expect(reply).toMatchObject({ - requestId: 1, - error: 27, - message: 'fixture reply', - body: replyBody, - }); - expect(traceCountAtWrite).toBe(1); - expect(entries.filter((entry) => entry.scope === 'QQHook.Packet')) - .toEqual(expect.arrayContaining([ - expect.objectContaining({ - req: 4101, - message: `packet_send serviceCmd="OidbSvcTrpcTcp.0x1234_1" requestId=1 length=${requestBody.length} body=${requestBody.toString('hex')}`, - }), - expect.objectContaining({ - req: 4101, - message: `packet_recv serviceCmd="OidbSvcTrpcTcp.0x1234_1" requestId=1 error=27 message="fixture reply" length=${replyBody.length} body=${replyBody.toString('hex')}`, - }), - expect.objectContaining({ - req: 4101, - message: expect.stringMatching(/^packet_terminal serviceCmd="OidbSvcTrpcTcp\.0x1234_1" requestId=1 outcome=failed reason=reply_error error=27 elapsedMs=\d+$/), - }), - ])); - for (const message of traceMessages(entries)) expect(message).not.toContain('...'); - } finally { - unsubscribe(); - client.close(); - connection.mockRestore(); - } - }); - - it('records empty request and reply bodies exactly', async () => { - const pid = 778811; - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const connection = mockControlPipe(pid, (socket, payload) => { - const { requestId } = readSendFrame(payload); - queueMicrotask(() => { - socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId })); - socket.emit('data', pipeFrame({ op: PipeOp.sendReply, requestId })); - }); - }); - const client = new QqHookClient(pid); - try { - await client.sendAndWait('Empty.Command', Buffer.alloc(0)); - - expect(traceMessages(entries)).toEqual([ - 'packet_send serviceCmd="Empty.Command" requestId=1 length=0 body=', - 'packet_recv serviceCmd="Empty.Command" requestId=1 error=0 message="" length=0 body=', - expect.stringMatching(/^packet_terminal serviceCmd="Empty\.Command" requestId=1 outcome=ok reason=reply_received error=0 elapsedMs=\d+$/), - ]); - } finally { - unsubscribe(); - client.close(); - connection.mockRestore(); - } - }); - - it('records no-reply acknowledgement as the terminal outcome', async () => { - const pid = 778812; - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const connection = mockControlPipe(pid, (socket, payload) => { - const { requestId } = readSendFrame(payload); - queueMicrotask(() => { - socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId })); - }); - }); - const client = new QqHookClient(pid); - try { - await client.sendNoReply('NoReply.Command', Buffer.from([0x00, 0xff])); - - expect(traceMessages(entries)).toEqual([ - 'packet_send serviceCmd="NoReply.Command" requestId=1 length=2 body=00ff', - expect.stringMatching(/^packet_terminal serviceCmd="NoReply\.Command" requestId=1 outcome=ok reason=ack_received elapsedMs=\d+$/), - ]); - } finally { - unsubscribe(); - client.close(); - connection.mockRestore(); - } - }); - - it('records reply timeout and transport failure with their real request ids', async () => { - vi.useFakeTimers(); - const pid = 778813; - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - let writeCount = 0; - const connection = mockControlPipe(pid, (socket, payload) => { - const { requestId } = readSendFrame(payload); - writeCount += 1; - if (writeCount === 1) { - queueMicrotask(() => { - socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId })); + it('records complete request and reply bodies with the real pipe request id', async () => { + const pid = 778810; + const requestBody = Buffer.from([ + 0x00, + 0xff, + ...Array.from({ length: 160 }, (_, index) => index & 0xff), + ]); + const replyBody = Buffer.from([0xff, 0x00, 0x7f]); + const entries: LogEntry[] = []; + const writes: Buffer[] = []; + let traceCountAtWrite = 0; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const connection = mockControlPipe(pid, (socket, payload) => { + const frame = readSendFrame(payload); + writes.push(payload); + traceCountAtWrite = traceMessages(entries).length; + queueMicrotask(() => { + socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId: frame.requestId })); + socket.emit( + 'data', + pipeFrame({ + op: PipeOp.sendReply, + requestId: frame.requestId, + status: 27, + message: 'fixture reply', + body: replyBody, + }), + ); + }); }); - return; - } - queueMicrotask(() => socket.destroy()); - }); - const client = new QqHookClient(pid); - client.on('error', () => { /* expected transport failure */ }); - try { - const timedOut = client.sendAndWait('Timeout.Command', Buffer.from([0xff]), { - ackTimeoutMs: 50, - replyTimeoutMs: 50, - }); - const timedOutOutcome = timedOut.then( - () => null, - (error: unknown) => error, - ); - await vi.advanceTimersByTimeAsync(50); - const timeoutError = await timedOutOutcome; - expect(timeoutError).toBeInstanceOf(Error); - expect((timeoutError as Error).message).toBe('send reply 1 timed out after 50 ms'); + const client = new QqHookClient(pid); - const failed = client.sendAndWait('Closed.Command', Buffer.from([0x00]), { - ackTimeoutMs: 50, - replyTimeoutMs: 50, - }); - await expect(failed).rejects.toThrow('control pipe closed'); + try { + const reply = await runWithRequestId(4101, () => + client.sendAndWait('OidbSvcTrpcTcp.0x1234_1', requestBody), + ); - expect(traceMessages(entries)).toEqual(expect.arrayContaining([ - expect.stringMatching(/^packet_terminal serviceCmd="Timeout\.Command" requestId=1 outcome=timeout reason=reply_timeout error="send reply 1 timed out after 50 ms" elapsedMs=\d+$/), - expect.stringMatching(/^packet_terminal serviceCmd="Closed\.Command" requestId=2 outcome=failed reason=transport_failure error="control pipe closed" elapsedMs=\d+$/), - ])); - } finally { - unsubscribe(); - client.close(); - connection.mockRestore(); - vi.useRealTimers(); - } - }); + const sent = readSendFrame(writes[0]); + expect(sent).toMatchObject({ + requestId: 1, + cmd: 'OidbSvcTrpcTcp.0x1234_1', + body: requestBody, + }); + expect(reply).toMatchObject({ + requestId: 1, + error: 27, + message: 'fixture reply', + body: replyBody, + }); + expect(traceCountAtWrite).toBe(1); + expect(entries.filter((entry) => entry.scope === 'QQHook.Packet')).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + req: 4101, + message: `packet_send serviceCmd="OidbSvcTrpcTcp.0x1234_1" requestId=1 length=${requestBody.length} body=${requestBody.toString('hex')}`, + }), + expect.objectContaining({ + req: 4101, + message: `packet_recv serviceCmd="OidbSvcTrpcTcp.0x1234_1" requestId=1 error=27 message="fixture reply" length=${replyBody.length} body=${replyBody.toString('hex')}`, + }), + expect.objectContaining({ + req: 4101, + message: expect.stringMatching( + /^packet_terminal serviceCmd="OidbSvcTrpcTcp\.0x1234_1" requestId=1 outcome=failed reason=reply_error error=27 elapsedMs=\d+$/, + ), + }), + ]), + ); - it('classifies acknowledgement timeout and pipe request failure', async () => { - vi.useFakeTimers(); - const pid = 778815; - const entries: LogEntry[] = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - let writeCount = 0; - const connection = mockControlPipe(pid, (socket, payload) => { - const { requestId } = readSendFrame(payload); - writeCount += 1; - if (writeCount === 2) { - queueMicrotask(() => socket.emit('data', pipeFrame({ - op: PipeOp.error, - requestId, - status: 12, - message: 'send ack 2 timed out after 25 ms', - }))); - } - }); - const client = new QqHookClient(pid); - try { - const timedOut = client.sendNoReply('Ack.Timeout', Buffer.from([0x00]), { - ackTimeoutMs: 25, - }); - const timedOutOutcome = timedOut.then( - () => null, - (error: unknown) => error, - ); - await vi.advanceTimersByTimeAsync(25); - expect(await timedOutOutcome).toMatchObject({ - message: 'send ack 1 timed out after 25 ms', - }); - - const requestError = await client.sendAndWait( - 'Pipe.Error', - Buffer.from([0xff]), - ).then( - () => null, - (error: unknown) => error, - ); - expect(requestError).toMatchObject({ - name: 'HookPipeRequestError', - message: 'send ack 2 timed out after 25 ms', - status: 12, - requestId: 2, - }); - - expect(traceMessages(entries)).toEqual(expect.arrayContaining([ - expect.stringMatching(/^packet_terminal serviceCmd="Ack\.Timeout" requestId=1 outcome=timeout reason=ack_timeout error="send ack 1 timed out after 25 ms" elapsedMs=\d+$/), - expect.stringMatching(/^packet_terminal serviceCmd="Pipe\.Error" requestId=2 outcome=failed reason=request_failed error="send ack 2 timed out after 25 ms" elapsedMs=\d+$/), - ])); - } finally { - unsubscribe(); - client.close(); - connection.mockRestore(); - vi.useRealTimers(); - } - }); - - it('keeps concurrent packet records atomic with distinct real request ids', async () => { - const pid = 778816; - const entries: LogEntry[] = []; - const writes: Array> = []; - setLogLevel('trace'); - const unsubscribe = subscribeLogs((entry) => entries.push(entry)); - const connection = mockControlPipe(pid, (socket, payload) => { - writes.push(readSendFrame(payload)); - if (writes.length !== 2) return; - queueMicrotask(() => { - for (const frame of [...writes].reverse()) { - socket.emit('data', pipeFrame({ - op: PipeOp.sendAck, - requestId: frame.requestId, - })); - socket.emit('data', pipeFrame({ - op: PipeOp.sendReply, - requestId: frame.requestId, - body: Buffer.from(frame.body).reverse(), - })); + for (const message of traceMessages(entries)) { + expect(message).not.toContain('...'); + } + } finally { + unsubscribe(); + client.close(); + connection.mockRestore(); } - }); }); - const client = new QqHookClient(pid); - const firstBody = Buffer.from([0x00, 0xff]); - const secondBody = Buffer.from( - Array.from({ length: 160 }, (_, index) => index & 0xff), - ); - try { - const [first, second] = await Promise.all([ - client.sendAndWait('First\nCommand', firstBody), - client.sendAndWait('Second.Command', secondBody), - ]); - expect([first.requestId, second.requestId]).toEqual([1, 2]); - expect(writes.map((frame) => frame.requestId)).toEqual([1, 2]); - const messages = traceMessages(entries); - expect(messages).toHaveLength(6); - expect(messages.every((message) => !message.includes('\n'))).toBe(true); - expect(messages).toEqual(expect.arrayContaining([ - `packet_send serviceCmd="First\\nCommand" requestId=1 length=2 body=${firstBody.toString('hex')}`, - `packet_recv serviceCmd="First\\nCommand" requestId=1 error=0 message="" length=2 body=${Buffer.from(firstBody).reverse().toString('hex')}`, - `packet_send serviceCmd="Second.Command" requestId=2 length=${secondBody.length} body=${secondBody.toString('hex')}`, - `packet_recv serviceCmd="Second.Command" requestId=2 error=0 message="" length=${secondBody.length} body=${Buffer.from(secondBody).reverse().toString('hex')}`, - ])); - expect(messages.filter((message) => message.startsWith('packet_terminal'))).toHaveLength(2); - } finally { - unsubscribe(); - client.close(); - connection.mockRestore(); - } - }); + it('records empty request and reply bodies exactly', async () => { + const pid = 778811; + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const connection = mockControlPipe(pid, (socket, payload) => { + const { requestId } = readSendFrame(payload); + queueMicrotask(() => { + socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId })); + socket.emit('data', pipeFrame({ op: PipeOp.sendReply, requestId })); + }); + }); + const client = new QqHookClient(pid); - it('does not evaluate packet TRACE producers while TRACE is disabled', async () => { - const pid = 778814; - setLogLevel('debug'); - const byteLength = vi.spyOn(Buffer.prototype, 'toString'); - const connection = mockControlPipe(pid, (socket, payload) => { - const { requestId } = readSendFrame(payload); - queueMicrotask(() => { - socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId })); - socket.emit('data', pipeFrame({ op: PipeOp.sendReply, requestId })); - }); + try { + await client.sendAndWait('Empty.Command', Buffer.alloc(0)); + + expect(traceMessages(entries)).toEqual([ + 'packet_send serviceCmd="Empty.Command" requestId=1 length=0 body=', + 'packet_recv serviceCmd="Empty.Command" requestId=1 error=0 message="" length=0 body=', + expect.stringMatching( + /^packet_terminal serviceCmd="Empty\.Command" requestId=1 outcome=ok reason=reply_received error=0 elapsedMs=\d+$/, + ), + ]); + } finally { + unsubscribe(); + client.close(); + connection.mockRestore(); + } }); - const client = new QqHookClient(pid); - try { - await client.sendAndWait('Disabled.Command', Buffer.from([0x00, 0xff])); - expect(byteLength).not.toHaveBeenCalledWith('hex'); - } finally { - client.close(); - connection.mockRestore(); - byteLength.mockRestore(); - } - }); + it('records no-reply acknowledgement as the terminal outcome', async () => { + const pid = 778812; + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const connection = mockControlPipe(pid, (socket, payload) => { + const { requestId } = readSendFrame(payload); + queueMicrotask(() => { + socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId })); + }); + }); + const client = new QqHookClient(pid); + + try { + await client.sendNoReply('NoReply.Command', Buffer.from([0x00, 0xff])); + + expect(traceMessages(entries)).toEqual([ + 'packet_send serviceCmd="NoReply.Command" requestId=1 length=2 body=00ff', + expect.stringMatching( + /^packet_terminal serviceCmd="NoReply\.Command" requestId=1 outcome=ok reason=ack_received elapsedMs=\d+$/, + ), + ]); + } finally { + unsubscribe(); + client.close(); + connection.mockRestore(); + } + }); + + it('records reply timeout and transport failure with their real request ids', async () => { + vi.useFakeTimers(); + const pid = 778813; + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + let writeCount = 0; + const connection = mockControlPipe(pid, (socket, payload) => { + const { requestId } = readSendFrame(payload); + writeCount += 1; + + if (writeCount === 1) { + queueMicrotask(() => { + socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId })); + }); + return; + } + + queueMicrotask(() => socket.destroy()); + }); + const client = new QqHookClient(pid); + client.on('error', () => { + /* expected transport failure */ + }); + + try { + const timedOut = client.sendAndWait('Timeout.Command', Buffer.from([0xff]), { + ackTimeoutMs: 50, + replyTimeoutMs: 50, + }); + const timedOutOutcome = timedOut.then( + () => null, + (error: unknown) => error, + ); + await vi.advanceTimersByTimeAsync(50); + const timeoutError = await timedOutOutcome; + expect(timeoutError).toBeInstanceOf(Error); + expect((timeoutError as Error).message).toBe('send reply 1 timed out after 50 ms'); + + const failed = client.sendAndWait('Closed.Command', Buffer.from([0x00]), { + ackTimeoutMs: 50, + replyTimeoutMs: 50, + }); + await expect(failed).rejects.toThrow('control pipe closed'); + + expect(traceMessages(entries)).toEqual( + expect.arrayContaining([ + expect.stringMatching( + /^packet_terminal serviceCmd="Timeout\.Command" requestId=1 outcome=timeout reason=reply_timeout error="send reply 1 timed out after 50 ms" elapsedMs=\d+$/, + ), + expect.stringMatching( + /^packet_terminal serviceCmd="Closed\.Command" requestId=2 outcome=failed reason=transport_failure error="control pipe closed" elapsedMs=\d+$/, + ), + ]), + ); + } finally { + unsubscribe(); + client.close(); + connection.mockRestore(); + vi.useRealTimers(); + } + }); + + it('classifies acknowledgement timeout and pipe request failure', async () => { + vi.useFakeTimers(); + const pid = 778815; + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + let writeCount = 0; + const connection = mockControlPipe(pid, (socket, payload) => { + const { requestId } = readSendFrame(payload); + writeCount += 1; + + if (writeCount === 2) { + queueMicrotask(() => + socket.emit( + 'data', + pipeFrame({ + op: PipeOp.error, + requestId, + status: 12, + message: 'send ack 2 timed out after 25 ms', + }), + ), + ); + } + }); + const client = new QqHookClient(pid); + + try { + const timedOut = client.sendNoReply('Ack.Timeout', Buffer.from([0x00]), { + ackTimeoutMs: 25, + }); + const timedOutOutcome = timedOut.then( + () => null, + (error: unknown) => error, + ); + await vi.advanceTimersByTimeAsync(25); + expect(await timedOutOutcome).toMatchObject({ + message: 'send ack 1 timed out after 25 ms', + }); + + const requestError = await client.sendAndWait('Pipe.Error', Buffer.from([0xff])).then( + () => null, + (error: unknown) => error, + ); + expect(requestError).toMatchObject({ + name: 'HookPipeRequestError', + message: 'send ack 2 timed out after 25 ms', + status: 12, + requestId: 2, + }); + + expect(traceMessages(entries)).toEqual( + expect.arrayContaining([ + expect.stringMatching( + /^packet_terminal serviceCmd="Ack\.Timeout" requestId=1 outcome=timeout reason=ack_timeout error="send ack 1 timed out after 25 ms" elapsedMs=\d+$/, + ), + expect.stringMatching( + /^packet_terminal serviceCmd="Pipe\.Error" requestId=2 outcome=failed reason=request_failed error="send ack 2 timed out after 25 ms" elapsedMs=\d+$/, + ), + ]), + ); + } finally { + unsubscribe(); + client.close(); + connection.mockRestore(); + vi.useRealTimers(); + } + }); + + it('keeps concurrent packet records atomic with distinct real request ids', async () => { + const pid = 778816; + const entries: LogEntry[] = []; + const writes: Array> = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + const connection = mockControlPipe(pid, (socket, payload) => { + writes.push(readSendFrame(payload)); + + if (writes.length !== 2) { + return; + } + + queueMicrotask(() => { + for (const frame of [...writes].reverse()) { + socket.emit( + 'data', + pipeFrame({ + op: PipeOp.sendAck, + requestId: frame.requestId, + }), + ); + socket.emit( + 'data', + pipeFrame({ + op: PipeOp.sendReply, + requestId: frame.requestId, + body: Buffer.from(frame.body).reverse(), + }), + ); + } + }); + }); + const client = new QqHookClient(pid); + const firstBody = Buffer.from([0x00, 0xff]); + const secondBody = Buffer.from(Array.from({ length: 160 }, (_, index) => index & 0xff)); + + try { + const [first, second] = await Promise.all([ + client.sendAndWait('First\nCommand', firstBody), + client.sendAndWait('Second.Command', secondBody), + ]); + + expect([first.requestId, second.requestId]).toEqual([1, 2]); + expect(writes.map((frame) => frame.requestId)).toEqual([1, 2]); + const messages = traceMessages(entries); + expect(messages).toHaveLength(6); + expect(messages.every((message) => !message.includes('\n'))).toBe(true); + expect(messages).toEqual( + expect.arrayContaining([ + `packet_send serviceCmd="First\\nCommand" requestId=1 length=2 body=${firstBody.toString('hex')}`, + `packet_recv serviceCmd="First\\nCommand" requestId=1 error=0 message="" length=2 body=${Buffer.from(firstBody).reverse().toString('hex')}`, + `packet_send serviceCmd="Second.Command" requestId=2 length=${secondBody.length} body=${secondBody.toString('hex')}`, + `packet_recv serviceCmd="Second.Command" requestId=2 error=0 message="" length=${secondBody.length} body=${Buffer.from(secondBody).reverse().toString('hex')}`, + ]), + ); + expect( + messages.filter((message) => message.startsWith('packet_terminal')), + ).toHaveLength(2); + } finally { + unsubscribe(); + client.close(); + connection.mockRestore(); + } + }); + + it('does not evaluate packet TRACE producers while TRACE is disabled', async () => { + const pid = 778814; + setLogLevel('debug'); + const byteLength = vi.spyOn(Buffer.prototype, 'toString'); + const connection = mockControlPipe(pid, (socket, payload) => { + const { requestId } = readSendFrame(payload); + queueMicrotask(() => { + socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId })); + socket.emit('data', pipeFrame({ op: PipeOp.sendReply, requestId })); + }); + }); + const client = new QqHookClient(pid); + + try { + await client.sendAndWait('Disabled.Command', Buffer.from([0x00, 0xff])); + + expect(byteLength).not.toHaveBeenCalledWith('hex'); + } finally { + client.close(); + connection.mockRestore(); + byteLength.mockRestore(); + } + }); }); describe('QqHookClient — pipe close mid-send', () => { - // Regression: when the control pipe closes while a send() is awaiting its - // ack, rejectControlPending() rejects BOTH the ack and reply deferreds. The - // reply is only `await`ed after the ack, so if the ack rejects first the - // reply promise is rejected with NO awaiter — an UNHANDLED rejection that - // crashes the Node process (Docker: supervisor restarts it ~1s later; on - // Windows it just dies → "connection pipe closed", bot down). The .catch() - // guard on each deferred prevents it; without the guard this test trips the - // unhandledRejection assertion below. - it('does not raise an unhandled rejection', async () => { - const PID = 778899; - const helloFrame = (): Buffer => { - const h = Buffer.alloc(40); - h.writeUInt32LE(0x31504851, 0); // PIPE_MAGIC - h.writeUInt16LE(1, 4); // PIPE_VERSION - h.writeUInt16LE(1, 6); // PipeOp.hello - h.writeBigUInt64LE(BigInt(PID), 32); // value0 = pid - return h; - }; + // Regression: when the control pipe closes while a send() is awaiting its + // ack, rejectControlPending() rejects BOTH the ack and reply deferreds. The + // reply is only `await`ed after the ack, so if the ack rejects first the + // reply promise is rejected with NO awaiter — an UNHANDLED rejection that + // crashes the Node process (Docker: supervisor restarts it ~1s later; on + // Windows it just dies → "connection pipe closed", bot down). The .catch() + // guard on each deferred prevents it; without the guard this test trips the + // unhandledRejection assertion below. + it('does not raise an unhandled rejection', async () => { + const PID = 778899; - let controlConn: net.Socket | null = null; - let signalControlWrite!: () => void; - const controlWriteStarted = new Promise((resolve) => { signalControlWrite = resolve; }); - const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { - const socket = new Duplex({ - read() { /* peer data is injected with emit('data') */ }, - write(_chunk, _encoding, callback) { - signalControlWrite(); - callback(); - }, - }) as net.Socket; - controlConn = socket; - queueMicrotask(() => { - socket.emit('connect'); - queueMicrotask(() => socket.emit('data', helloFrame())); - }); - return socket; - }) as typeof net.createConnection); + const helloFrame = (): Buffer => { + const h = Buffer.alloc(40); + h.writeUInt32LE(0x31504851, 0); // PIPE_MAGIC + h.writeUInt16LE(1, 4); // PIPE_VERSION + h.writeUInt16LE(1, 6); // PipeOp.hello + h.writeBigUInt64LE(BigInt(PID), 32); // value0 = pid + return h; + }; - const unhandled: unknown[] = []; - const onUnhandled = (reason: unknown): void => { unhandled.push(reason); }; - process.on('unhandledRejection', onUnhandled); + let controlConn: net.Socket | null = null; + let signalControlWrite!: () => void; + const controlWriteStarted = new Promise((resolve) => { + signalControlWrite = resolve; + }); + const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => { + const socket = new Duplex({ + read() { + /* peer data is injected with emit('data') */ + }, + write(_chunk, _encoding, callback) { + signalControlWrite(); + callback(); + }, + }) as net.Socket; + controlConn = socket; + queueMicrotask(() => { + socket.emit('connect'); + queueMicrotask(() => socket.emit('data', helloFrame())); + }); + return socket; + }) as typeof net.createConnection); - const client = new QqHookClient(PID); - client.on('error', () => { /* socket reset on destroy — ignore */ }); - try { - await client.connect(); + const unhandled: unknown[] = []; - // Start a reply-expecting send, let it reach the in-flight (awaiting-ack) - // state, then have the "hook" drop the pipe before it answers. - const sent = client.send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 }) - .then(() => 'resolved' as const, (e: unknown) => e); - await controlWriteStarted; - controlConn?.destroy(); + const onUnhandled = (reason: unknown): void => { + unhandled.push(reason); + }; - const outcome = await sent; - await new Promise((resolve) => setImmediate(resolve)); + process.on('unhandledRejection', onUnhandled); - expect(outcome).toBeInstanceOf(Error); - expect((outcome as Error).message).toBe('control pipe closed'); - expect(unhandled, `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`).toHaveLength(0); - } finally { - process.off('unhandledRejection', onUnhandled); - client.close(); - createConnection.mockRestore(); - } - }); + const client = new QqHookClient(PID); + client.on('error', () => { + /* socket reset on destroy — ignore */ + }); + + try { + await client.connect(); + + // Start a reply-expecting send, let it reach the in-flight (awaiting-ack) + // state, then have the "hook" drop the pipe before it answers. + const sent = client + .send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 }) + .then( + () => 'resolved' as const, + (e: unknown) => e, + ); + await controlWriteStarted; + controlConn?.destroy(); + + const outcome = await sent; + await new Promise((resolve) => setImmediate(resolve)); + + expect(outcome).toBeInstanceOf(Error); + expect((outcome as Error).message).toBe('control pipe closed'); + expect( + unhandled, + `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`, + ).toHaveLength(0); + } finally { + process.off('unhandledRejection', onUnhandled); + client.close(); + createConnection.mockRestore(); + } + }); }); diff --git a/packages/bridge/tests/qq-port-probe-more.test.ts b/packages/bridge/tests/qq-port-probe-more.test.ts index 120f81ba..63562899 100644 --- a/packages/bridge/tests/qq-port-probe-more.test.ts +++ b/packages/bridge/tests/qq-port-probe-more.test.ts @@ -8,12 +8,12 @@ const httpsGetMock = vi.hoisted(() => vi.fn()); vi.mock('child_process', () => ({ exec: execMock })); vi.mock('http', () => ({ - default: { get: httpGetMock }, - get: httpGetMock, + default: { get: httpGetMock }, + get: httpGetMock, })); vi.mock('https', () => ({ - default: { get: httpsGetMock }, - get: httpsGetMock, + default: { get: httpsGetMock }, + get: httpsGetMock, })); import { probeQqLoginInfo } from '../src/qq-port-probe'; @@ -21,676 +21,704 @@ import { probeQqLoginInfo } from '../src/qq-port-probe'; const originalPlatform = process.platform; const EXEC_OPTIONS = { timeout: 1500, killSignal: 'SIGKILL' }; const PTLOGIN_HEADERS = { - Host: 'localhost.ptlogin2.qq.com', - Referer: 'https://xui.ptlogin2.qq.com/', - Cookie: 'pt_local_token=0', + Host: 'localhost.ptlogin2.qq.com', + Referer: 'https://xui.ptlogin2.qq.com/', + Cookie: 'pt_local_token=0', }; type ExecCallback = (error: Error | null, result?: { stdout: string; stderr: string }) => void; type RequestLike = EventEmitter & { destroy: ReturnType }; function setPlatform(platform: string): void { - Object.defineProperty(process, 'platform', { value: platform, configurable: true }); + Object.defineProperty(process, 'platform', { value: platform, configurable: true }); } function mockExec(replies: Record): void { - execMock.mockImplementation((command: string, _options: unknown, callback: ExecCallback) => { - const reply = replies[command]; - if (reply === undefined) { - callback(new Error(`unexpected command ${command}`)); - return; - } - if (reply instanceof Error) { - callback(reply); - return; - } - callback(null, { stdout: reply, stderr: '' }); - }); + execMock.mockImplementation((command: string, _options: unknown, callback: ExecCallback) => { + const reply = replies[command]; + + if (reply === undefined) { + callback(new Error(`unexpected command ${command}`)); + return; + } + + if (reply instanceof Error) { + callback(reply); + return; + } + + callback(null, { stdout: reply, stderr: '' }); + }); } function execCommands(): string[] { - return execMock.mock.calls.map((call) => String(call[0])); + return execMock.mock.calls.map((call) => String(call[0])); } function ssLine(port: number, pid: number, owner: 'comma' | 'paren' = 'comma'): string { - const tag = owner === 'comma' ? `pid=${pid},fd=9` : `pid=${pid}`; - return `LISTEN 0 128 127.0.0.1:${port} 0.0.0.0:* users:(("qq",${tag}))`; + const tag = owner === 'comma' ? `pid=${pid},fd=9` : `pid=${pid}`; + return `LISTEN 0 128 127.0.0.1:${port} 0.0.0.0:* users:(("qq",${tag}))`; } function netstatLine(localAddr: string, pid: number): string { - return ` TCP ${localAddr} 0.0.0.0:0 LISTENING ${pid}`; + return ` TCP ${localAddr} 0.0.0.0:0 LISTENING ${pid}`; } function jsonp(accounts: unknown[]): string { - return `ptui_getuins_CB(${JSON.stringify(accounts)});`; + return `ptui_getuins_CB(${JSON.stringify(accounts)});`; } function requestStub(): RequestLike { - const req = new EventEmitter() as RequestLike; - req.destroy = vi.fn(); - return req; + const req = new EventEmitter() as RequestLike; + req.destroy = vi.fn(); + return req; } function replyBody(body: string | ReadonlyArray) { - return (_url: string, _options: unknown, onResponse: (res: EventEmitter) => void): RequestLike => { - const req = requestStub(); - const res = new EventEmitter(); - onResponse(res); - const chunks = typeof body === 'string' ? [body] : body; - for (const chunk of chunks) res.emit('data', chunk); - res.emit('end'); - return req; - }; + return ( + _url: string, + _options: unknown, + onResponse: (res: EventEmitter) => void, + ): RequestLike => { + const req = requestStub(); + const res = new EventEmitter(); + onResponse(res); + const chunks = typeof body === 'string' ? [body] : body; + + for (const chunk of chunks) { + res.emit('data', chunk); + } + + res.emit('end'); + return req; + }; } function replyError(error: Error) { - return (): RequestLike => { - const req = requestStub(); - queueMicrotask(() => req.emit('error', error)); - return req; - }; + return (): RequestLike => { + const req = requestStub(); + queueMicrotask(() => req.emit('error', error)); + return req; + }; } beforeEach(() => { - execMock.mockReset(); - httpGetMock.mockReset(); - httpsGetMock.mockReset(); - setPlatform('linux'); + execMock.mockReset(); + httpGetMock.mockReset(); + httpsGetMock.mockReset(); + setPlatform('linux'); }); afterEach(() => { - setPlatform(originalPlatform); - vi.useRealTimers(); + setPlatform(originalPlatform); + vi.useRealTimers(); }); describe('probeQqLoginInfo — unix listing', () => { - it('returns null when ss cannot list sockets', async () => { - mockExec({ 'ss -tlnp': new Error('ss: not found') }); + it('returns null when ss cannot list sockets', async () => { + mockExec({ 'ss -tlnp': new Error('ss: not found') }); - await expect(probeQqLoginInfo(3310)).resolves.toBeNull(); - expect(execCommands()).toEqual(['ss -tlnp']); - expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(httpsGetMock).not.toHaveBeenCalled(); - }); - - it('reports a logged-out identity when the PID has no sockets and pgrep is below 6', async () => { - mockExec({ - 'ss -tlnp': 'State Recv-Q Send-Q Local Address:Port Peer Address:Port\n', - 'pgrep -c qq': '5\n', + await expect(probeQqLoginInfo(3310)).resolves.toBeNull(); + expect(execCommands()).toEqual(['ss -tlnp']); + expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(httpsGetMock).not.toHaveBeenCalled(); }); - await expect(probeQqLoginInfo(3311)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); - expect(execCommands()).toEqual(['ss -tlnp', 'pgrep -c qq']); - expect(execMock.mock.calls[1]?.[1]).toEqual(EXEC_OPTIONS); - }); + it('reports a logged-out identity when the PID has no sockets and pgrep is below 6', async () => { + mockExec({ + 'ss -tlnp': 'State Recv-Q Send-Q Local Address:Port Peer Address:Port\n', + 'pgrep -c qq': '5\n', + }); - it('treats a pgrep count of 0 as logged out', async () => { - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': '0\n', + await expect(probeQqLoginInfo(3311)).resolves.toEqual({ + port: 0, + uin: '', + identityKnown: false, + }); + expect(execCommands()).toEqual(['ss -tlnp', 'pgrep -c qq']); + expect(execMock.mock.calls[1]?.[1]).toEqual(EXEC_OPTIONS); }); - await expect(probeQqLoginInfo(3312)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); - }); + it('treats a pgrep count of 0 as logged out', async () => { + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': '0\n', + }); - it('treats a non-numeric pgrep count as 0 and therefore logged out', async () => { - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': 'qq: no process found\n', + await expect(probeQqLoginInfo(3312)).resolves.toEqual({ + port: 0, + uin: '', + identityKnown: false, + }); }); - await expect(probeQqLoginInfo(3313)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); - }); + it('treats a non-numeric pgrep count as 0 and therefore logged out', async () => { + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': 'qq: no process found\n', + }); - it('returns null when there are no sockets and pgrep is 6 or higher', async () => { - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': '6\n', - }); - await expect(probeQqLoginInfo(3314)).resolves.toBeNull(); - - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': '9\n', - }); - await expect(probeQqLoginInfo(3315)).resolves.toBeNull(); - }); - - it('does not treat a failed pgrep as logged out', async () => { - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': new Error('pgrep: exit 1'), + await expect(probeQqLoginInfo(3313)).resolves.toEqual({ + port: 0, + uin: '', + identityKnown: false, + }); }); - await expect(probeQqLoginInfo(3316)).resolves.toBeNull(); - }); + it('returns null when there are no sockets and pgrep is 6 or higher', async () => { + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': '6\n', + }); + await expect(probeQqLoginInfo(3314)).resolves.toBeNull(); - it('uses the first listening port as a logged-out hint when no Ptlogin port is present', async () => { - mockExec({ - 'ss -tlnp': [ - ssLine(9218, 4410), - ssLine(18000, 4410), - ].join('\n'), - 'pgrep -c qq': ' 4 \n', + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': '9\n', + }); + await expect(probeQqLoginInfo(3315)).resolves.toBeNull(); }); - await expect(probeQqLoginInfo(4410)).resolves.toEqual({ - port: 9218, - uin: '', - identityKnown: false, - }); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(httpsGetMock).not.toHaveBeenCalled(); - }); + it('does not treat a failed pgrep as logged out', async () => { + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': new Error('pgrep: exit 1'), + }); - it('returns null for non-Ptlogin ports when the QQ process count is ambiguous', async () => { - mockExec({ - 'ss -tlnp': ssLine(9218, 4411), - 'pgrep -c qq': '7\n', + await expect(probeQqLoginInfo(3316)).resolves.toBeNull(); }); - await expect(probeQqLoginInfo(4411)).resolves.toBeNull(); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(httpsGetMock).not.toHaveBeenCalled(); - }); + it('uses the first listening port as a logged-out hint when no Ptlogin port is present', async () => { + mockExec({ + 'ss -tlnp': [ssLine(9218, 4410), ssLine(18000, 4410)].join('\n'), + 'pgrep -c qq': ' 4 \n', + }); - it('collects unique ports from ss lines that name the PID with either pid=N, or pid=N)', async () => { - mockExec({ - 'ss -tlnp': [ - 'LISTEN 0 128 127.0.0.1:4301users:(("qq",pid=4412,fd=1))', - ssLine(4301, 4412, 'comma'), - ssLine(4301, 4412, 'comma'), - ssLine(4305, 4412, 'paren'), - ssLine(4305, 9999, 'comma'), - 'ESTAB 0 0 127.0.0.1:4307 127.0.0.1:443 users:(("qq",pid=4412,fd=4))', - ].join('\n'), + await expect(probeQqLoginInfo(4410)).resolves.toEqual({ + port: 9218, + uin: '', + identityKnown: false, + }); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(httpsGetMock).not.toHaveBeenCalled(); }); - httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '10001', nickname: 'Ada' }]))); - await expect(probeQqLoginInfo(4412)).resolves.toEqual({ - port: 4301, - uin: '10001', - nickName: 'Ada', - identityKnown: true, + it('returns null for non-Ptlogin ports when the QQ process count is ambiguous', async () => { + mockExec({ + 'ss -tlnp': ssLine(9218, 4411), + 'pgrep -c qq': '7\n', + }); + + await expect(probeQqLoginInfo(4411)).resolves.toBeNull(); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(httpsGetMock).not.toHaveBeenCalled(); + }); + + it('collects unique ports from ss lines that name the PID with either pid=N, or pid=N)', async () => { + mockExec({ + 'ss -tlnp': [ + 'LISTEN 0 128 127.0.0.1:4301users:(("qq",pid=4412,fd=1))', + ssLine(4301, 4412, 'comma'), + ssLine(4301, 4412, 'comma'), + ssLine(4305, 4412, 'paren'), + ssLine(4305, 9999, 'comma'), + 'ESTAB 0 0 127.0.0.1:4307 127.0.0.1:443 users:(("qq",pid=4412,fd=4))', + ].join('\n'), + }); + httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '10001', nickname: 'Ada' }]))); + + await expect(probeQqLoginInfo(4412)).resolves.toEqual({ + port: 4301, + uin: '10001', + nickName: 'Ada', + identityKnown: true, + }); + expect(httpsGetMock).toHaveBeenCalledTimes(2); + expect(httpsGetMock.mock.calls[0]?.[0]).toBe( + 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + ); }); - expect(httpsGetMock).toHaveBeenCalledTimes(2); - expect(httpsGetMock.mock.calls[0]?.[0]).toBe( - 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - ); - }); }); describe('probeQqLoginInfo — Ptlogin identity', () => { - it('reads a single account from an odd Ptlogin port over https', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5501) }); - httpsGetMock.mockImplementation(replyBody(jsonp([{ - uin: 319427101, - account: 1, - nickname: 'Snow', - extra: 'ignored', - }]))); + it('reads a single account from an odd Ptlogin port over https', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5501) }); + httpsGetMock.mockImplementation( + replyBody( + jsonp([ + { + uin: 319427101, + account: 1, + nickname: 'Snow', + extra: 'ignored', + }, + ]), + ), + ); - await expect(probeQqLoginInfo(5501)).resolves.toEqual({ - port: 4301, - uin: '319427101', - nickName: 'Snow', - identityKnown: true, - }); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(httpsGetMock).toHaveBeenCalledTimes(2); - expect(httpsGetMock.mock.calls[0]?.[1]).toEqual({ - headers: PTLOGIN_HEADERS, - timeout: 500, - rejectUnauthorized: false, - }); - }); - - it('reads a single account from an even Ptlogin port over http', async () => { - mockExec({ 'ss -tlnp': ssLine(4302, 5502) }); - httpGetMock.mockImplementation(replyBody(jsonp([{ - account: '2880036470', - }]))); - - await expect(probeQqLoginInfo(5502)).resolves.toEqual({ - port: 4302, - uin: '2880036470', - nickName: '', - identityKnown: true, - }); - expect(httpsGetMock).not.toHaveBeenCalled(); - expect(httpGetMock).toHaveBeenCalledTimes(2); - expect(httpGetMock.mock.calls[0]?.[0]).toBe( - 'http://127.0.0.1:4302/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - ); - expect(httpGetMock.mock.calls[0]?.[1]).toEqual({ - headers: PTLOGIN_HEADERS, - timeout: 500, - }); - }); - - it('probes every documented odd Ptlogin port over https', async () => { - for (const port of [4301, 4303, 4305, 4307, 4309]) { - execMock.mockReset(); - httpsGetMock.mockReset(); - httpGetMock.mockReset(); - mockExec({ 'ss -tlnp': ssLine(port, 5510) }); - httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '70001', nickname: 'Odd' }]))); - - await expect(probeQqLoginInfo(5510)).resolves.toEqual({ - port, - uin: '70001', - nickName: 'Odd', - identityKnown: true, - }); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(String(httpsGetMock.mock.calls[0]?.[0])).toBe( - `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`, - ); - } - }); - - it('probes every documented even Ptlogin port over http when no odd port is listening', async () => { - for (const port of [4302, 4304, 4306, 4308, 4310]) { - execMock.mockReset(); - httpsGetMock.mockReset(); - httpGetMock.mockReset(); - mockExec({ 'ss -tlnp': ssLine(port, 5511) }); - httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '70002', nickname: 'Even' }]))); - - await expect(probeQqLoginInfo(5511)).resolves.toEqual({ - port, - uin: '70002', - nickName: 'Even', - identityKnown: true, - }); - expect(httpsGetMock).not.toHaveBeenCalled(); - expect(String(httpGetMock.mock.calls[0]?.[0])).toBe( - `http://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`, - ); - } - }); - - it('prefers odd Ptlogin ports and never falls through to even ones', async () => { - mockExec({ - 'ss -tlnp': [ssLine(4302, 5520), ssLine(4301, 5520)].join('\n'), - }); - httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED'))); - - await expect(probeQqLoginInfo(5520)).resolves.toBeNull(); - expect(httpsGetMock).toHaveBeenCalled(); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(execCommands()).toEqual(['ss -tlnp']); - }); - - it('tries the next odd Ptlogin port after the first one fails', async () => { - mockExec({ - 'ss -tlnp': [ssLine(4301, 5521), ssLine(4305, 5521)].join('\n'), - }); - httpsGetMock - .mockImplementationOnce(replyBody('nope')) - .mockImplementationOnce(replyBody('nope')) - .mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }]))) - .mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }]))); - - await expect(probeQqLoginInfo(5521)).resolves.toEqual({ - port: 4305, - uin: '188888', - nickName: 'Next', - identityKnown: true, - }); - expect(httpsGetMock.mock.calls.map((call) => call[0])).toEqual([ - 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - 'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - 'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - ]); - }); - - it('stops after the first Ptlogin port that yields a single account', async () => { - mockExec({ - 'ss -tlnp': [ssLine(4303, 5522), ssLine(4309, 5522)].join('\n'), - }); - httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '42', nickname: 'First' }]))); - - await expect(probeQqLoginInfo(5522)).resolves.toEqual({ - port: 4303, - uin: '42', - nickName: 'First', - identityKnown: true, - }); - expect(httpsGetMock).toHaveBeenCalledTimes(2); - }); - - it('uses account when uin is missing or empty, including a numeric 0 uin', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5530) }); - httpsGetMock - .mockImplementationOnce(replyBody(jsonp([{ uin: 0, account: 314159, nickname: 'Zero' }]))) - .mockImplementationOnce(replyBody(jsonp([{ uin: '', account: '314159', nickname: 'Zero' }]))); - - await expect(probeQqLoginInfo(5530)).resolves.toEqual({ - port: 4301, - uin: '314159', - nickName: 'Zero', - identityKnown: true, - }); - }); - - it('returns an empty uin when the single account has neither uin nor account', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5531) }); - httpsGetMock.mockImplementation(replyBody('[{"nickname":"Anon"}]')); - - await expect(probeQqLoginInfo(5531)).resolves.toEqual({ - port: 4301, - uin: '', - nickName: 'Anon', - identityKnown: true, - }); - }); - - it('keeps the shorter of the two pt_get_uins snapshots', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5540) }); - httpsGetMock - .mockImplementationOnce(replyBody(jsonp([ - { uin: '11', nickname: 'A' }, - { uin: '22', nickname: 'B' }, - ]))) - .mockImplementationOnce(replyBody(jsonp([{ uin: '33', nickname: 'Cora' }]))); - - await expect(probeQqLoginInfo(5540)).resolves.toEqual({ - port: 4301, - uin: '33', - nickName: 'Cora', - identityKnown: true, - }); - }); - - it('keeps the first snapshot when both pt_get_uins calls have one account', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5541) }); - httpsGetMock - .mockImplementationOnce(replyBody(jsonp([{ uin: '100', nickname: 'Left' }]))) - .mockImplementationOnce(replyBody(jsonp([{ uin: '200', nickname: 'Right' }]))); - - await expect(probeQqLoginInfo(5541)).resolves.toEqual({ - port: 4301, - uin: '100', - nickName: 'Left', - identityKnown: true, - }); - }); - - it('accepts a single account from the second fetch when the first fetch is unusable', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5542) }); - httpsGetMock - .mockImplementationOnce(replyError(new Error('ECONNRESET'))) - .mockImplementationOnce(replyBody(jsonp([{ uin: '9090', nickname: 'Retry' }]))); - - await expect(probeQqLoginInfo(5542)).resolves.toEqual({ - port: 4301, - uin: '9090', - nickName: 'Retry', - identityKnown: true, - }); - }); - - it('returns null for an empty pt_get_uins array and does not consult pgrep', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5550) }); - httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([]);')); - - await expect(probeQqLoginInfo(5550)).resolves.toBeNull(); - expect(execCommands()).toEqual(['ss -tlnp']); - }); - - it('returns null when both snapshots have more than one account', async () => { - mockExec({ 'ss -tlnp': ssLine(4304, 5551) }); - httpGetMock.mockImplementation(replyBody(jsonp([ - { uin: '1' }, - { uin: '2' }, - ]))); - - await expect(probeQqLoginInfo(5551)).resolves.toBeNull(); - }); - - it('returns null when both fetches fail to parse a pt_get_uins body', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5552) }); - httpsGetMock.mockImplementation(replyBody('not-jsonp')); - - await expect(probeQqLoginInfo(5552)).resolves.toBeNull(); - }); - - it('returns null when both fetches error', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5553) }); - httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED'))); - - await expect(probeQqLoginInfo(5553)).resolves.toBeNull(); - }); - - it('destroys the request and returns null when both fetches time out', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5554) }); - const seen: RequestLike[] = []; - httpsGetMock.mockImplementation(() => { - const req = requestStub(); - seen.push(req); - queueMicrotask(() => req.emit('timeout')); - return req; + await expect(probeQqLoginInfo(5501)).resolves.toEqual({ + port: 4301, + uin: '319427101', + nickName: 'Snow', + identityKnown: true, + }); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(httpsGetMock).toHaveBeenCalledTimes(2); + expect(httpsGetMock.mock.calls[0]?.[1]).toEqual({ + headers: PTLOGIN_HEADERS, + timeout: 500, + rejectUnauthorized: false, + }); }); - await expect(probeQqLoginInfo(5554)).resolves.toBeNull(); - expect(seen).toHaveLength(2); - expect(seen[0]?.destroy).toHaveBeenCalledTimes(1); - expect(seen[1]?.destroy).toHaveBeenCalledTimes(1); - }); + it('reads a single account from an even Ptlogin port over http', async () => { + mockExec({ 'ss -tlnp': ssLine(4302, 5502) }); + httpGetMock.mockImplementation( + replyBody( + jsonp([ + { + account: '2880036470', + }, + ]), + ), + ); - it('joins chunked pt_get_uins bodies including Buffer pieces', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5560) }); - httpsGetMock.mockImplementation(replyBody([ - 'ptui_getuins_CB([', - Buffer.from('{"uin":"10001","nickname":"Ada"}'), - ']);', - ])); - - await expect(probeQqLoginInfo(5560)).resolves.toEqual({ - port: 4301, - uin: '10001', - nickName: 'Ada', - identityKnown: true, + await expect(probeQqLoginInfo(5502)).resolves.toEqual({ + port: 4302, + uin: '2880036470', + nickName: '', + identityKnown: true, + }); + expect(httpsGetMock).not.toHaveBeenCalled(); + expect(httpGetMock).toHaveBeenCalledTimes(2); + expect(httpGetMock.mock.calls[0]?.[0]).toBe( + 'http://127.0.0.1:4302/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + ); + expect(httpGetMock.mock.calls[0]?.[1]).toEqual({ + headers: PTLOGIN_HEADERS, + timeout: 500, + }); }); - }); - it('treats a nickname that closes the JSONP array early as unusable', async () => { - mockExec({ 'ss -tlnp': ssLine(4301, 5561) }); - httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([{"nickname":"a]b","uin":"1"}]);')); + it('probes every documented odd Ptlogin port over https', async () => { + for (const port of [4301, 4303, 4305, 4307, 4309]) { + execMock.mockReset(); + httpsGetMock.mockReset(); + httpGetMock.mockReset(); + mockExec({ 'ss -tlnp': ssLine(port, 5510) }); + httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '70001', nickname: 'Odd' }]))); - await expect(probeQqLoginInfo(5561)).resolves.toBeNull(); - }); + await expect(probeQqLoginInfo(5510)).resolves.toEqual({ + port, + uin: '70001', + nickName: 'Odd', + identityKnown: true, + }); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(String(httpsGetMock.mock.calls[0]?.[0])).toBe( + `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`, + ); + } + }); + + it('probes every documented even Ptlogin port over http when no odd port is listening', async () => { + for (const port of [4302, 4304, 4306, 4308, 4310]) { + execMock.mockReset(); + httpsGetMock.mockReset(); + httpGetMock.mockReset(); + mockExec({ 'ss -tlnp': ssLine(port, 5511) }); + httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '70002', nickname: 'Even' }]))); + + await expect(probeQqLoginInfo(5511)).resolves.toEqual({ + port, + uin: '70002', + nickName: 'Even', + identityKnown: true, + }); + expect(httpsGetMock).not.toHaveBeenCalled(); + expect(String(httpGetMock.mock.calls[0]?.[0])).toBe( + `http://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`, + ); + } + }); + + it('prefers odd Ptlogin ports and never falls through to even ones', async () => { + mockExec({ + 'ss -tlnp': [ssLine(4302, 5520), ssLine(4301, 5520)].join('\n'), + }); + httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED'))); + + await expect(probeQqLoginInfo(5520)).resolves.toBeNull(); + expect(httpsGetMock).toHaveBeenCalled(); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(execCommands()).toEqual(['ss -tlnp']); + }); + + it('tries the next odd Ptlogin port after the first one fails', async () => { + mockExec({ + 'ss -tlnp': [ssLine(4301, 5521), ssLine(4305, 5521)].join('\n'), + }); + httpsGetMock + .mockImplementationOnce(replyBody('nope')) + .mockImplementationOnce(replyBody('nope')) + .mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }]))) + .mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }]))); + + await expect(probeQqLoginInfo(5521)).resolves.toEqual({ + port: 4305, + uin: '188888', + nickName: 'Next', + identityKnown: true, + }); + expect(httpsGetMock.mock.calls.map((call) => call[0])).toEqual([ + 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + 'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + 'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + ]); + }); + + it('stops after the first Ptlogin port that yields a single account', async () => { + mockExec({ + 'ss -tlnp': [ssLine(4303, 5522), ssLine(4309, 5522)].join('\n'), + }); + httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '42', nickname: 'First' }]))); + + await expect(probeQqLoginInfo(5522)).resolves.toEqual({ + port: 4303, + uin: '42', + nickName: 'First', + identityKnown: true, + }); + expect(httpsGetMock).toHaveBeenCalledTimes(2); + }); + + it('uses account when uin is missing or empty, including a numeric 0 uin', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5530) }); + httpsGetMock + .mockImplementationOnce( + replyBody(jsonp([{ uin: 0, account: 314159, nickname: 'Zero' }])), + ) + .mockImplementationOnce( + replyBody(jsonp([{ uin: '', account: '314159', nickname: 'Zero' }])), + ); + + await expect(probeQqLoginInfo(5530)).resolves.toEqual({ + port: 4301, + uin: '314159', + nickName: 'Zero', + identityKnown: true, + }); + }); + + it('returns an empty uin when the single account has neither uin nor account', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5531) }); + httpsGetMock.mockImplementation(replyBody('[{"nickname":"Anon"}]')); + + await expect(probeQqLoginInfo(5531)).resolves.toEqual({ + port: 4301, + uin: '', + nickName: 'Anon', + identityKnown: true, + }); + }); + + it('keeps the shorter of the two pt_get_uins snapshots', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5540) }); + httpsGetMock + .mockImplementationOnce( + replyBody( + jsonp([ + { uin: '11', nickname: 'A' }, + { uin: '22', nickname: 'B' }, + ]), + ), + ) + .mockImplementationOnce(replyBody(jsonp([{ uin: '33', nickname: 'Cora' }]))); + + await expect(probeQqLoginInfo(5540)).resolves.toEqual({ + port: 4301, + uin: '33', + nickName: 'Cora', + identityKnown: true, + }); + }); + + it('keeps the first snapshot when both pt_get_uins calls have one account', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5541) }); + httpsGetMock + .mockImplementationOnce(replyBody(jsonp([{ uin: '100', nickname: 'Left' }]))) + .mockImplementationOnce(replyBody(jsonp([{ uin: '200', nickname: 'Right' }]))); + + await expect(probeQqLoginInfo(5541)).resolves.toEqual({ + port: 4301, + uin: '100', + nickName: 'Left', + identityKnown: true, + }); + }); + + it('accepts a single account from the second fetch when the first fetch is unusable', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5542) }); + httpsGetMock + .mockImplementationOnce(replyError(new Error('ECONNRESET'))) + .mockImplementationOnce(replyBody(jsonp([{ uin: '9090', nickname: 'Retry' }]))); + + await expect(probeQqLoginInfo(5542)).resolves.toEqual({ + port: 4301, + uin: '9090', + nickName: 'Retry', + identityKnown: true, + }); + }); + + it('returns null for an empty pt_get_uins array and does not consult pgrep', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5550) }); + httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([]);')); + + await expect(probeQqLoginInfo(5550)).resolves.toBeNull(); + expect(execCommands()).toEqual(['ss -tlnp']); + }); + + it('returns null when both snapshots have more than one account', async () => { + mockExec({ 'ss -tlnp': ssLine(4304, 5551) }); + httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '1' }, { uin: '2' }]))); + + await expect(probeQqLoginInfo(5551)).resolves.toBeNull(); + }); + + it('returns null when both fetches fail to parse a pt_get_uins body', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5552) }); + httpsGetMock.mockImplementation(replyBody('not-jsonp')); + + await expect(probeQqLoginInfo(5552)).resolves.toBeNull(); + }); + + it('returns null when both fetches error', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5553) }); + httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED'))); + + await expect(probeQqLoginInfo(5553)).resolves.toBeNull(); + }); + + it('destroys the request and returns null when both fetches time out', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5554) }); + const seen: RequestLike[] = []; + httpsGetMock.mockImplementation(() => { + const req = requestStub(); + seen.push(req); + queueMicrotask(() => req.emit('timeout')); + return req; + }); + + await expect(probeQqLoginInfo(5554)).resolves.toBeNull(); + expect(seen).toHaveLength(2); + expect(seen[0]?.destroy).toHaveBeenCalledTimes(1); + expect(seen[1]?.destroy).toHaveBeenCalledTimes(1); + }); + + it('joins chunked pt_get_uins bodies including Buffer pieces', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5560) }); + httpsGetMock.mockImplementation( + replyBody([ + 'ptui_getuins_CB([', + Buffer.from('{"uin":"10001","nickname":"Ada"}'), + ']);', + ]), + ); + + await expect(probeQqLoginInfo(5560)).resolves.toEqual({ + port: 4301, + uin: '10001', + nickName: 'Ada', + identityKnown: true, + }); + }); + + it('treats a nickname that closes the JSONP array early as unusable', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5561) }); + httpsGetMock.mockImplementation( + replyBody('ptui_getuins_CB([{"nickname":"a]b","uin":"1"}]);'), + ); + + await expect(probeQqLoginInfo(5561)).resolves.toBeNull(); + }); }); describe('probeQqLoginInfo — win32 listing', () => { - beforeEach(() => { - setPlatform('win32'); - }); - - it('returns null when netstat cannot list sockets', async () => { - mockExec({ 'netstat -ano': new Error('netstat: access denied') }); - - await expect(probeQqLoginInfo(6610)).resolves.toBeNull(); - expect(execCommands()).toEqual(['netstat -ano']); - expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS); - }); - - it('counts QQ.exe rows from tasklist when netstat lists no sockets for the PID', async () => { - mockExec({ - 'netstat -ano': [ - 'Active Connections', - '', - ' Proto Local Address Foreign Address State PID', - netstatLine('127.0.0.1:4301', 1), - ].join('\n'), - 'tasklist /fi "imagename eq QQ.exe" /nh': [ - 'QQ.exe 100 Console 1 10,000 K', - 'QQ.exe 101 Console 1 11,000 K', - 'explorer.exe 200 Console 1 9,000 K', - ].join('\n'), + beforeEach(() => { + setPlatform('win32'); }); - await expect(probeQqLoginInfo(6611)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); - expect(execCommands()).toEqual([ - 'netstat -ano', - 'tasklist /fi "imagename eq QQ.exe" /nh', - ]); - }); + it('returns null when netstat cannot list sockets', async () => { + mockExec({ 'netstat -ano': new Error('netstat: access denied') }); - it('returns null when tasklist reports 6 or more QQ.exe rows and the PID has no sockets', async () => { - mockExec({ - 'netstat -ano': '', - 'tasklist /fi "imagename eq QQ.exe" /nh': [ - 'QQ.exe 1', - 'QQ.exe 2', - 'QQ.exe 3', - 'qq.exe 4', - 'QQ.EXE 5', - 'QQ.exe 6', - ].join('\n'), + await expect(probeQqLoginInfo(6610)).resolves.toBeNull(); + expect(execCommands()).toEqual(['netstat -ano']); + expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS); }); - await expect(probeQqLoginInfo(6612)).resolves.toBeNull(); - }); + it('counts QQ.exe rows from tasklist when netstat lists no sockets for the PID', async () => { + mockExec({ + 'netstat -ano': [ + 'Active Connections', + '', + ' Proto Local Address Foreign Address State PID', + netstatLine('127.0.0.1:4301', 1), + ].join('\n'), + 'tasklist /fi "imagename eq QQ.exe" /nh': [ + 'QQ.exe 100 Console 1 10,000 K', + 'QQ.exe 101 Console 1 11,000 K', + 'explorer.exe 200 Console 1 9,000 K', + ].join('\n'), + }); - it('does not treat a failed tasklist as logged out', async () => { - mockExec({ - 'netstat -ano': '', - 'tasklist /fi "imagename eq QQ.exe" /nh': new Error('tasklist: exit 1'), + await expect(probeQqLoginInfo(6611)).resolves.toEqual({ + port: 0, + uin: '', + identityKnown: false, + }); + expect(execCommands()).toEqual(['netstat -ano', 'tasklist /fi "imagename eq QQ.exe" /nh']); }); - await expect(probeQqLoginInfo(6613)).resolves.toBeNull(); - }); + it('returns null when tasklist reports 6 or more QQ.exe rows and the PID has no sockets', async () => { + mockExec({ + 'netstat -ano': '', + 'tasklist /fi "imagename eq QQ.exe" /nh': [ + 'QQ.exe 1', + 'QQ.exe 2', + 'QQ.exe 3', + 'qq.exe 4', + 'QQ.EXE 5', + 'QQ.exe 6', + ].join('\n'), + }); - it('parses netstat rows for the owning PID and skips short or portless lines', async () => { - mockExec({ - 'netstat -ano': [ - 'Active Connections', - ' TCP 127.0.0.1:4301 LISTENING', - ' TCP 127.0.0.1 0.0.0.0:0 LISTENING 6620', - netstatLine('10.0.0.8:18000', 1), - netstatLine('127.0.0.1:4303', 6620), - netstatLine('[::1]:4303', 6620), - netstatLine('127.0.0.1:9218', 6620), - ].join('\n'), - }); - httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '20002', nickname: 'Win' }]))); - - await expect(probeQqLoginInfo(6620)).resolves.toEqual({ - port: 4303, - uin: '20002', - nickName: 'Win', - identityKnown: true, - }); - expect(httpsGetMock).toHaveBeenCalledTimes(2); - expect(httpsGetMock.mock.calls[0]?.[0]).toBe( - 'https://127.0.0.1:4303/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', - ); - }); - - it('uses the first netstat port as a logged-out hint when no Ptlogin port is present', async () => { - mockExec({ - 'netstat -ano': [ - netstatLine('127.0.0.1:18000', 6630), - netstatLine('127.0.0.1:18001', 6630), - ].join('\n'), - 'tasklist /fi "imagename eq QQ.exe" /nh': 'QQ.exe 100\n', + await expect(probeQqLoginInfo(6612)).resolves.toBeNull(); }); - await expect(probeQqLoginInfo(6630)).resolves.toEqual({ - port: 18000, - uin: '', - identityKnown: false, + it('does not treat a failed tasklist as logged out', async () => { + mockExec({ + 'netstat -ano': '', + 'tasklist /fi "imagename eq QQ.exe" /nh': new Error('tasklist: exit 1'), + }); + + await expect(probeQqLoginInfo(6613)).resolves.toBeNull(); + }); + + it('parses netstat rows for the owning PID and skips short or portless lines', async () => { + mockExec({ + 'netstat -ano': [ + 'Active Connections', + ' TCP 127.0.0.1:4301 LISTENING', + ' TCP 127.0.0.1 0.0.0.0:0 LISTENING 6620', + netstatLine('10.0.0.8:18000', 1), + netstatLine('127.0.0.1:4303', 6620), + netstatLine('[::1]:4303', 6620), + netstatLine('127.0.0.1:9218', 6620), + ].join('\n'), + }); + httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '20002', nickname: 'Win' }]))); + + await expect(probeQqLoginInfo(6620)).resolves.toEqual({ + port: 4303, + uin: '20002', + nickName: 'Win', + identityKnown: true, + }); + expect(httpsGetMock).toHaveBeenCalledTimes(2); + expect(httpsGetMock.mock.calls[0]?.[0]).toBe( + 'https://127.0.0.1:4303/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + ); + }); + + it('uses the first netstat port as a logged-out hint when no Ptlogin port is present', async () => { + mockExec({ + 'netstat -ano': [ + netstatLine('127.0.0.1:18000', 6630), + netstatLine('127.0.0.1:18001', 6630), + ].join('\n'), + 'tasklist /fi "imagename eq QQ.exe" /nh': 'QQ.exe 100\n', + }); + + await expect(probeQqLoginInfo(6630)).resolves.toEqual({ + port: 18000, + uin: '', + identityKnown: false, + }); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(httpsGetMock).not.toHaveBeenCalled(); }); - expect(httpGetMock).not.toHaveBeenCalled(); - expect(httpsGetMock).not.toHaveBeenCalled(); - }); }); describe('probeQqLoginInfo — overall deadline', () => { - it('returns null and warns after 5000ms if listing never finishes', async () => { - vi.useFakeTimers(); - execMock.mockImplementation(() => undefined); - const previousLevel = getLogLevel(); - setLogLevel('info'); - const warnings: string[] = []; - const unsubscribe = subscribeLogs((entry) => { - if (entry.scope === 'LoginProbe' && entry.level === 'warn') { - warnings.push(entry.message); - } + it('returns null and warns after 5000ms if listing never finishes', async () => { + vi.useFakeTimers(); + execMock.mockImplementation(() => undefined); + const previousLevel = getLogLevel(); + setLogLevel('info'); + const warnings: string[] = []; + const unsubscribe = subscribeLogs((entry) => { + if (entry.scope === 'LoginProbe' && entry.level === 'warn') { + warnings.push(entry.message); + } + }); + + try { + const pending = probeQqLoginInfo(9001); + let settled: unknown = 'pending'; + void pending.then((value) => { + settled = value; + }); + + await vi.advanceTimersByTimeAsync(4999); + expect(settled).toBe('pending'); + + await vi.advanceTimersByTimeAsync(1); + await expect(pending).resolves.toBeNull(); + expect(warnings).toEqual(['login check timed out: PID=9001']); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } }); - try { - const pending = probeQqLoginInfo(9001); - let settled: unknown = 'pending'; - void pending.then((value) => { - settled = value; - }); + it('does not warn when the probe finishes before the deadline', async () => { + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': '2\n', + }); + const previousLevel = getLogLevel(); + setLogLevel('info'); + const warnings: string[] = []; + const unsubscribe = subscribeLogs((entry) => { + if (entry.scope === 'LoginProbe') { + warnings.push(entry.message); + } + }); - await vi.advanceTimersByTimeAsync(4999); - expect(settled).toBe('pending'); - - await vi.advanceTimersByTimeAsync(1); - await expect(pending).resolves.toBeNull(); - expect(warnings).toEqual(['login check timed out: PID=9001']); - } finally { - unsubscribe(); - setLogLevel(previousLevel); - } - }); - - it('does not warn when the probe finishes before the deadline', async () => { - mockExec({ - 'ss -tlnp': '', - 'pgrep -c qq': '2\n', - }); - const previousLevel = getLogLevel(); - setLogLevel('info'); - const warnings: string[] = []; - const unsubscribe = subscribeLogs((entry) => { - if (entry.scope === 'LoginProbe') warnings.push(entry.message); + try { + await expect(probeQqLoginInfo(9002)).resolves.toEqual({ + port: 0, + uin: '', + identityKnown: false, + }); + await probeQqLoginInfo(9002); + expect(warnings).toEqual(['login probe: PID=9002 result=no-ports ports=0 processes=2']); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } }); - try { - await expect(probeQqLoginInfo(9002)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, - }); - await probeQqLoginInfo(9002); - expect(warnings).toEqual(['login probe: PID=9002 result=no-ports ports=0 processes=2']); - } finally { - unsubscribe(); - setLogLevel(previousLevel); - } - }); + it('abandons a hung Ptlogin fetch at the overall deadline', async () => { + vi.useFakeTimers(); + mockExec({ 'ss -tlnp': ssLine(4301, 9003) }); + httpsGetMock.mockImplementation(() => requestStub()); - it('abandons a hung Ptlogin fetch at the overall deadline', async () => { - vi.useFakeTimers(); - mockExec({ 'ss -tlnp': ssLine(4301, 9003) }); - httpsGetMock.mockImplementation(() => requestStub()); - - const pending = probeQqLoginInfo(9003); - await vi.advanceTimersByTimeAsync(5000); - await expect(pending).resolves.toBeNull(); - }); + const pending = probeQqLoginInfo(9003); + await vi.advanceTimersByTimeAsync(5000); + await expect(pending).resolves.toBeNull(); + }); }); diff --git a/packages/bridge/tests/qq-port-probe.test.ts b/packages/bridge/tests/qq-port-probe.test.ts index 9f555700..56ad297f 100644 --- a/packages/bridge/tests/qq-port-probe.test.ts +++ b/packages/bridge/tests/qq-port-probe.test.ts @@ -1,63 +1,65 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const execMock = vi.hoisted(() => vi.fn()); -const socketCtorMock = vi.hoisted(() => vi.fn(function MockSocket() { - throw new Error('interactive QQ probe must not run'); -})); +const socketCtorMock = vi.hoisted(() => + vi.fn(function MockSocket() { + throw new Error('interactive QQ probe must not run'); + }), +); vi.mock('child_process', () => ({ exec: execMock })); vi.mock('net', () => ({ - default: { Socket: socketCtorMock }, - Socket: socketCtorMock, + default: { Socket: socketCtorMock }, + Socket: socketCtorMock, })); import { probeQqLoginInfo } from '../src/qq-port-probe'; describe('probeQqLoginInfo — bounded execution', () => { - beforeEach(() => { - vi.useFakeTimers(); - execMock.mockReset(); - socketCtorMock.mockClear(); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - it('allows a later probe after a timed-out attempt', async () => { - execMock.mockImplementation(() => undefined); - const first = probeQqLoginInfo(4242); - await vi.advanceTimersByTimeAsync(10_000); - await expect(first).resolves.toBeNull(); - - execMock - .mockImplementationOnce((_command, _options, callback) => { - callback(null, { stdout: '', stderr: '' }); - }) - .mockImplementationOnce((_command, _options, callback) => { - callback(null, { stdout: '1\n', stderr: '' }); - }); - - await expect(probeQqLoginInfo(4242)).resolves.toEqual({ - port: 0, - uin: '', - identityKnown: false, + beforeEach(() => { + vi.useFakeTimers(); + execMock.mockReset(); + socketCtorMock.mockClear(); }); - }); - it('keeps background identity discovery passive', async () => { - execMock - .mockImplementationOnce((_command, _options, callback) => { - callback(null, { - stdout: 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n', - stderr: '', + afterEach(() => { + vi.useRealTimers(); + }); + + it('allows a later probe after a timed-out attempt', async () => { + execMock.mockImplementation(() => undefined); + const first = probeQqLoginInfo(4242); + await vi.advanceTimersByTimeAsync(10_000); + await expect(first).resolves.toBeNull(); + + execMock + .mockImplementationOnce((_command, _options, callback) => { + callback(null, { stdout: '', stderr: '' }); + }) + .mockImplementationOnce((_command, _options, callback) => { + callback(null, { stdout: '1\n', stderr: '' }); + }); + + await expect(probeQqLoginInfo(4242)).resolves.toEqual({ + port: 0, + uin: '', + identityKnown: false, }); - }) - .mockImplementationOnce((_command, _options, callback) => { - callback(null, { stdout: '8\n', stderr: '' }); - }); + }); - await expect(probeQqLoginInfo(4242)).resolves.toBeNull(); - expect(socketCtorMock).not.toHaveBeenCalled(); - }); + it('keeps background identity discovery passive', async () => { + execMock + .mockImplementationOnce((_command, _options, callback) => { + callback(null, { + stdout: 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n', + stderr: '', + }); + }) + .mockImplementationOnce((_command, _options, callback) => { + callback(null, { stdout: '8\n', stderr: '' }); + }); + + await expect(probeQqLoginInfo(4242)).resolves.toBeNull(); + expect(socketCtorMock).not.toHaveBeenCalled(); + }); }); diff --git a/packages/bridge/vitest.config.ts b/packages/bridge/vitest.config.ts index b0e95a5a..4dea4350 100644 --- a/packages/bridge/vitest.config.ts +++ b/packages/bridge/vitest.config.ts @@ -1,8 +1,8 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ - test: { - include: ['tests/**/*.test.ts'], - environment: 'node', - }, + test: { + include: ['tests/**/*.test.ts'], + environment: 'node', + }, }); diff --git a/packages/common/src/access-token.ts b/packages/common/src/access-token.ts index 903a8616..914b17ee 100644 --- a/packages/common/src/access-token.ts +++ b/packages/common/src/access-token.ts @@ -5,35 +5,40 @@ import { translations } from '@zxcvbn-ts/language-en'; export const ACCESS_TOKEN_MIN_LENGTH = 16; export const ACCESS_TOKEN_MIN_SCORE = 3; -export type AccessTokenAssessmentReason = - | 'empty' - | 'too-short' - | 'guessable' - | 'acceptable'; +export type AccessTokenAssessmentReason = 'empty' | 'too-short' | 'guessable' | 'acceptable'; export interface AccessTokenAssessment { - acceptable: boolean; - reason: AccessTokenAssessmentReason; - score: number; + acceptable: boolean; + reason: AccessTokenAssessmentReason; + score: number; } const checker = new ZxcvbnFactory({ - translations, - graphs: adjacencyGraphs, - dictionary, + translations, + graphs: adjacencyGraphs, + dictionary, }); function normalizeUserInputs(values: readonly (string | number)[]): Array { - const unique = new Set(['SnowLuma', 'OneBot']); - for (const value of values) { - if (typeof value === 'number') { - if (Number.isFinite(value)) unique.add(value); - continue; + const unique = new Set(['SnowLuma', 'OneBot']); + + for (const value of values) { + if (typeof value === 'number') { + if (Number.isFinite(value)) { + unique.add(value); + } + + continue; + } + + const trimmed = value.trim(); + + if (trimmed) { + unique.add(trimmed.slice(0, 256)); + } } - const trimmed = value.trim(); - if (trimmed) unique.add(trimmed.slice(0, 256)); - } - return [...unique].slice(0, 24); + + return [...unique].slice(0, 24); } /** @@ -42,17 +47,22 @@ function normalizeUserInputs(values: readonly (string | number)[]): Array { - return typeof value === 'object' && value !== null && !Array.isArray(value); + return typeof value === 'object' && value !== null && !Array.isArray(value); } /** The value when it is a real boolean, else the fallback. Strings/numbers * are NOT coerced — `'true'` and `1` both yield the fallback. */ export function boolOr(value: unknown, fallback: boolean): boolean { - return typeof value === 'boolean' ? value : fallback; + return typeof value === 'boolean' ? value : fallback; } /** A finite number (numeric strings coerced) clamped to `[min, max]`, else * the fallback. Fractional precision is preserved — use `clampInt` to floor. */ export function clampNum(value: unknown, min: number, max: number, fallback: number): number { - const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN; - if (!Number.isFinite(n)) return fallback; - return Math.min(max, Math.max(min, n)); + const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN; + + if (!Number.isFinite(n)) { + return fallback; + } + + return Math.min(max, Math.max(min, n)); } /** `clampNum` truncated toward zero — clamp first, then drop the fraction. */ export function clampInt(value: unknown, min: number, max: number, fallback: number): number { - return Math.trunc(clampNum(value, min, max, fallback)); + return Math.trunc(clampNum(value, min, max, fallback)); } diff --git a/packages/common/src/concurrency.ts b/packages/common/src/concurrency.ts index 5da07645..e6114926 100644 --- a/packages/common/src/concurrency.ts +++ b/packages/common/src/concurrency.ts @@ -12,16 +12,21 @@ * shape that was previously hand-rolled at each such call site. */ export async function mapWithConcurrency( - items: readonly T[], - concurrency: number, - fn: (item: T, index: number) => Promise, + items: readonly T[], + concurrency: number, + fn: (item: T, index: number) => Promise, ): Promise { - const limit = Math.max(1, Math.trunc(concurrency)); - const results = new Array(items.length); - for (let i = 0; i < items.length; i += limit) { - const batch = items.slice(i, i + limit); - const settled = await Promise.all(batch.map((item, j) => fn(item, i + j))); - for (let j = 0; j < settled.length; j++) results[i + j] = settled[j]!; - } - return results; + const limit = Math.max(1, Math.trunc(concurrency)); + const results = new Array(items.length); + + for (let i = 0; i < items.length; i += limit) { + const batch = items.slice(i, i + limit); + const settled = await Promise.all(batch.map((item, j) => fn(item, i + j))); + + for (let j = 0; j < settled.length; j++) { + results[i + j] = settled[j]!; + } + } + + return results; } diff --git a/packages/common/src/env.ts b/packages/common/src/env.ts index 2b02cce2..c7aa66e3 100644 --- a/packages/common/src/env.ts +++ b/packages/common/src/env.ts @@ -11,18 +11,24 @@ const MAX_POSITIVE_INT = 2_147_483_647; * value is ignored, with a warning, and also returns `fallback`. */ export function positiveIntEnv( - name: string, - fallback: number, - options?: { max?: number; env?: NodeJS.ProcessEnv }, + name: string, + fallback: number, + options?: { max?: number; env?: NodeJS.ProcessEnv }, ): number { - const max = options?.max ?? MAX_POSITIVE_INT; - const raw = (options?.env ?? process.env)[name]; - if (typeof raw !== 'string' || !raw.trim()) return fallback; - const value = raw.trim(); - const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN; - if (!Number.isSafeInteger(parsed) || parsed > max) { - log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max); - return fallback; - } - return parsed; + const max = options?.max ?? MAX_POSITIVE_INT; + const raw = (options?.env ?? process.env)[name]; + + if (typeof raw !== 'string' || !raw.trim()) { + return fallback; + } + + const value = raw.trim(); + const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN; + + if (!Number.isSafeInteger(parsed) || parsed > max) { + log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max); + return fallback; + } + + return parsed; } diff --git a/packages/common/src/hex.ts b/packages/common/src/hex.ts index 26974244..f738031b 100644 --- a/packages/common/src/hex.ts +++ b/packages/common/src/hex.ts @@ -2,34 +2,43 @@ const HEX_CHARS = '0123456789abcdef'; const HEX_CHARS_UPPER = '0123456789ABCDEF'; export function toHex(data: Uint8Array | Buffer): string { - let h = ''; - for (const b of data) { - h += HEX_CHARS[b >> 4]; - h += HEX_CHARS[b & 0xf]; - } - return h; + let h = ''; + + for (const b of data) { + h += HEX_CHARS[b >> 4]; + h += HEX_CHARS[b & 0xf]; + } + + return h; } export function toHexUpper(data: Uint8Array | Buffer): string { - let h = ''; - for (const b of data) { - h += HEX_CHARS_UPPER[b >> 4]; - h += HEX_CHARS_UPPER[b & 0xf]; - } - return h; + let h = ''; + + for (const b of data) { + h += HEX_CHARS_UPPER[b >> 4]; + h += HEX_CHARS_UPPER[b & 0xf]; + } + + return h; } export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string { - const limit = Math.max(0, Math.min(maxBytes, data.length)); - const head = toHex(data.subarray(0, limit)); - return data.length > limit ? `${head}...` : head; + const limit = Math.max(0, Math.min(maxBytes, data.length)); + const head = toHex(data.subarray(0, limit)); + return data.length > limit ? `${head}...` : head; } export function fromHex(hex: string): Buffer { - if (hex.length % 2 !== 0) throw new Error('Invalid hex string length'); - const buf = Buffer.alloc(hex.length / 2); - for (let i = 0; i < buf.length; i++) { - buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16); - } - return buf; + if (hex.length % 2 !== 0) { + throw new Error('Invalid hex string length'); + } + + const buf = Buffer.alloc(hex.length / 2); + + for (let i = 0; i < buf.length; i++) { + buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16); + } + + return buf; } diff --git a/packages/common/src/json.ts b/packages/common/src/json.ts index 5d8dd735..758be288 100644 --- a/packages/common/src/json.ts +++ b/packages/common/src/json.ts @@ -1,6 +1,6 @@ export type JsonPrimitive = string | number | boolean | null; export type JsonValue = JsonPrimitive | JsonObject | JsonArray; export interface JsonObject { - [key: string]: JsonValue; + [key: string]: JsonValue; } export type JsonArray = JsonValue[]; diff --git a/packages/common/src/log-file-transport.ts b/packages/common/src/log-file-transport.ts index 6e943060..4a0ab5e8 100644 --- a/packages/common/src/log-file-transport.ts +++ b/packages/common/src/log-file-transport.ts @@ -1,10 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { sanitizeLogLine } from './log-sanitize'; -import { - MAX_LOG_RETAIN_DAYS, - MAX_LOG_TOTAL_MB, -} from './runtime'; +import { MAX_LOG_RETAIN_DAYS, MAX_LOG_TOTAL_MB } from './runtime'; const DEFAULT_DIR = 'logs'; const DEFAULT_MAX_MB = 50; @@ -19,95 +16,116 @@ const QUOTA_RETRY_MS = 5_000; export type LogStorageState = 'disabled' | 'healthy' | 'warning' | 'degraded'; export interface LogStorageStatus { - state: LogStorageState; - directory: string; - totalBytes: number; - maxTotalBytes: number; - retainDays: number; - perUinEnabled: boolean; - fileCount: number; - activeFileCount: number; - droppedLines: number; - lastError?: string; + state: LogStorageState; + directory: string; + totalBytes: number; + maxTotalBytes: number; + retainDays: number; + perUinEnabled: boolean; + fileCount: number; + activeFileCount: number; + droppedLines: number; + lastError?: string; } export interface LogStoragePolicy { - maxTotalMb: number; - retainDays: number; - perUinEnabled: boolean; + maxTotalMb: number; + retainDays: number; + perUinEnabled: boolean; } export interface LogCleanupResult { - deletedFiles: number; - freedBytes: number; - failures: Array<{ file: string; message: string }>; - status: LogStorageStatus; + deletedFiles: number; + freedBytes: number; + failures: Array<{ file: string; message: string }>; + status: LogStorageStatus; } function parseNonNegativeInt( - value: string | undefined, - fallback: number, - max: number, - field?: string, + value: string | undefined, + fallback: number, + max: number, + field?: string, ): number { - if (value === undefined || value.trim() === '') return fallback; - const parsed = Number(value.trim()); - if (Number.isSafeInteger(parsed) && parsed >= 0 && parsed <= max) return parsed; - if (field) { - throw new RangeError(`${field} must be an integer in 0..${String(max)}`); - } - return fallback; + if (value === undefined || value.trim() === '') { + return fallback; + } + + const parsed = Number(value.trim()); + + if (Number.isSafeInteger(parsed) && parsed >= 0 && parsed <= max) { + return parsed; + } + + if (field) { + throw new RangeError(`${field} must be an integer in 0..${String(max)}`); + } + + return fallback; } function parseRequiredPositiveInt( - value: string | undefined, - fallback: number, - max: number, - field: string, + value: string | undefined, + fallback: number, + max: number, + field: string, ): number { - if (value === undefined || value.trim() === '') return fallback; - const parsed = Number(value.trim()); - if (Number.isSafeInteger(parsed) && parsed > 0 && parsed <= max) return parsed; - throw new RangeError(`${field} must be an integer in 1..${String(max)}`); + if (value === undefined || value.trim() === '') { + return fallback; + } + + const parsed = Number(value.trim()); + + if (Number.isSafeInteger(parsed) && parsed > 0 && parsed <= max) { + return parsed; + } + + throw new RangeError(`${field} must be an integer in 1..${String(max)}`); } -function parseRequiredBool( - value: string | undefined, - fallback: boolean, - field: string, -): boolean { - if (value === undefined || value.trim() === '') return fallback; - const normalized = value.trim().toLowerCase(); - if (['1', 'true', 'yes', 'on'].includes(normalized)) return true; - if (['0', 'false', 'no', 'off'].includes(normalized)) return false; - throw new TypeError(`${field} must be a boolean`); +function parseRequiredBool(value: string | undefined, fallback: boolean, field: string): boolean { + if (value === undefined || value.trim() === '') { + return fallback; + } + + const normalized = value.trim().toLowerCase(); + + if (['1', 'true', 'yes', 'on'].includes(normalized)) { + return true; + } + + if (['0', 'false', 'no', 'off'].includes(normalized)) { + return false; + } + + throw new TypeError(`${field} must be a boolean`); } function todayString(d: Date = new Date()): string { - const y = d.getFullYear(); - const m = String(d.getMonth() + 1).padStart(2, '0'); - const day = String(d.getDate()).padStart(2, '0'); - return `${y}-${m}-${day}`; + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; } function dateOf(s: string): Date { - const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10)); - return new Date(y!, m! - 1, d!); + const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10)); + return new Date(y!, m! - 1, d!); } interface OpenFile { - stream: fs.WriteStream; - bytes: number; - date: string; - splitIndex: number; - path: string; + stream: fs.WriteStream; + bytes: number; + date: string; + splitIndex: number; + path: string; } interface ManagedLogFile { - path: string; - bytes: number; - mtimeMs: number; - date: string; + path: string; + bytes: number; + mtimeMs: number; + date: string; } /** @@ -116,330 +134,421 @@ interface ManagedLogFile { * the hard limit even before fs.stat can observe them. */ class LogQuota { - private readonly files = new Map(); - private readonly active = new Set(); - private usedBytes = 0; - private degraded = false; - private lastError: string | null = null; - private nextRetryAt = 0; - private droppedLines = 0; - private maintenanceSuspensions = 0; + private readonly files = new Map(); + private readonly active = new Set(); + private usedBytes = 0; + private degraded = false; + private lastError: string | null = null; + private nextRetryAt = 0; + private droppedLines = 0; + private maintenanceSuspensions = 0; - constructor( - private readonly root: string, - private maxTotalBytes: number, - private retainDays: number, - maintainOnLoad = true, - ) { - this.loadManagedFiles(); - if (maintainOnLoad) { - this.cleanupExpired(); - this.ensureCapacity(0); - } - } + constructor( + private readonly root: string, + private maxTotalBytes: number, + private retainDays: number, + maintainOnLoad = true, + ) { + this.loadManagedFiles(); - activate(filePath: string): number | null { - const normalized = path.resolve(filePath); - const known = this.files.get(normalized); - if (known) { - this.active.add(normalized); - return known.bytes; + if (maintainOnLoad) { + this.cleanupExpired(); + this.ensureCapacity(0); + } } - let bytes = 0; - let mtimeMs = Date.now(); - try { - const stat = fs.statSync(normalized); - bytes = stat.size; - mtimeMs = stat.mtimeMs; - } catch (error) { - if (!isMissing(error)) { + + activate(filePath: string): number | null { + const normalized = path.resolve(filePath); + const known = this.files.get(normalized); + + if (known) { + this.active.add(normalized); + return known.bytes; + } + + let bytes = 0; + let mtimeMs = Date.now(); + + try { + const stat = fs.statSync(normalized); + bytes = stat.size; + mtimeMs = stat.mtimeMs; + } catch (error) { + if (!isMissing(error)) { + this.enterDegraded( + `failed to inspect active log ${normalized}: ${errorMessage(error)}`, + ); + return null; + } + } + + const date = FILE_RE.exec(path.basename(normalized))?.[1] ?? todayString(); + this.files.set(normalized, { path: normalized, bytes, mtimeMs, date }); + this.usedBytes += bytes; + this.active.add(normalized); + return bytes; + } + + deactivate(filePath: string): void { + this.active.delete(path.resolve(filePath)); + + if (this.maintenanceSuspensions > 0) { + return; + } + + this.maintainAfterClose(); + } + + suspendMaintenance(): () => void { + this.maintenanceSuspensions += 1; + let resumed = false; + + return () => { + if (resumed) { + return; + } + + resumed = true; + this.maintenanceSuspensions = Math.max(0, this.maintenanceSuspensions - 1); + }; + } + + reserve(filePath: string, bytes: number): boolean { + if (bytes <= 0) { + return true; + } + + if (this.degraded && !this.retry(false)) { + this.droppedLines += 1; + return false; + } + + if (!this.ensureCapacity(bytes)) { + this.droppedLines += 1; + return false; + } + + const normalized = path.resolve(filePath); + const file = this.files.get(normalized); + + if (!file) { + if (this.activate(normalized) === null) { + this.droppedLines += 1; + return false; + } + + return this.reserve(normalized, bytes); + } + + file.bytes += bytes; + file.mtimeMs = Date.now(); + this.usedBytes += bytes; + return true; + } + + writeFailed(filePath: string, error: unknown): void { + this.storageFailed(`write ${filePath}`, error); + } + + storageFailed(operation: string, error: unknown): void { + this.enterDegraded(`${operation}: ${errorMessage(error)}`); + } + + snapshot(): Omit< + LogStorageStatus, + 'directory' | 'maxTotalBytes' | 'retainDays' | 'perUinEnabled' + > { + return { + state: this.degraded ? 'degraded' : this.lastError ? 'warning' : 'healthy', + totalBytes: this.usedBytes, + fileCount: this.files.size, + activeFileCount: this.active.size, + droppedLines: this.droppedLines, + ...(this.lastError ? { lastError: this.lastError } : {}), + }; + } + + updatePolicy(maxTotalBytes: number, retainDays: number): void { + this.maxTotalBytes = maxTotalBytes; + this.retainDays = retainDays; + this.degraded = false; + this.lastError = null; + this.nextRetryAt = 0; + + try { + this.refreshClosedFiles(); + this.cleanupExpired(); + this.ensureCapacity(0); + } catch (error) { + this.enterDegraded(`failed to apply log storage policy: ${errorMessage(error)}`); + throw error; + } + } + + clearClosedFiles(): Omit { + this.refreshClosedFiles(); + let deletedFiles = 0; + let freedBytes = 0; + const failures: LogCleanupResult['failures'] = []; + const candidates = [...this.files.values()] + .filter((file) => !this.active.has(file.path)) + .sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path)); + + for (const file of candidates) { + const bytes = file.bytes; + + if (this.deleteManagedFile(file, 'capacity')) { + deletedFiles += 1; + freedBytes += bytes; + } else { + failures.push({ + file: path.relative(this.root, file.path), + message: this.lastError ?? 'unknown cleanup error', + }); + } + } + + if (failures.length === 0) { + this.degraded = false; + this.lastError = null; + this.nextRetryAt = 0; + } else if (this.usedBytes > this.maxTotalBytes) { + this.enterDegraded( + `managed logs still use ${String(this.usedBytes)} bytes after manual cleanup, ` + + `exceeding the ${String(this.maxTotalBytes)} byte limit`, + ); + } + + this.ensureCapacity(0); + return { deletedFiles, freedBytes, failures }; + } + + private retry(force: boolean): boolean { + if (!force && Date.now() < this.nextRetryAt) { + return false; + } + + this.degraded = false; + this.lastError = null; + + try { + this.refreshClosedFiles(); + const recovered = this.ensureCapacity(0); + + if (recovered) { + this.nextRetryAt = 0; + } + + return recovered; + } catch (error) { + this.enterDegraded(`failed to refresh managed logs: ${errorMessage(error)}`); + return false; + } + } + + private maintainAfterClose(): void { + try { + this.refreshClosedFiles(); + this.cleanupExpired(); + + if (this.degraded) { + this.retry(true); + } else { + this.ensureCapacity(0); + } + } catch (error) { + this.enterDegraded( + `failed to maintain managed logs after rotation: ${errorMessage(error)}`, + ); + } + } + + private ensureCapacity(incomingBytes: number): boolean { + if (this.usedBytes + incomingBytes <= this.maxTotalBytes) { + return true; + } + + const candidates = [...this.files.values()] + .filter((file) => !this.active.has(file.path)) + .sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path)); + + for (const file of candidates) { + if (this.usedBytes + incomingBytes <= this.maxTotalBytes) { + break; + } + + if (!this.deleteManagedFile(file, 'capacity')) { + break; + } + } + + if (this.usedBytes + incomingBytes <= this.maxTotalBytes) { + return true; + } + this.enterDegraded( - `failed to inspect active log ${normalized}: ${errorMessage(error)}`, + `managed logs require ${String(this.usedBytes + incomingBytes)} bytes, ` + + `exceeding the ${String(this.maxTotalBytes)} byte limit; no closed log can be reclaimed`, ); - return null; - } - } - const date = FILE_RE.exec(path.basename(normalized))?.[1] ?? todayString(); - this.files.set(normalized, { path: normalized, bytes, mtimeMs, date }); - this.usedBytes += bytes; - this.active.add(normalized); - return bytes; - } - - deactivate(filePath: string): void { - this.active.delete(path.resolve(filePath)); - if (this.maintenanceSuspensions > 0) return; - this.maintainAfterClose(); - } - - suspendMaintenance(): () => void { - this.maintenanceSuspensions += 1; - let resumed = false; - return () => { - if (resumed) return; - resumed = true; - this.maintenanceSuspensions = Math.max(0, this.maintenanceSuspensions - 1); - }; - } - - reserve(filePath: string, bytes: number): boolean { - if (bytes <= 0) return true; - if (this.degraded && !this.retry(false)) { - this.droppedLines += 1; - return false; - } - if (!this.ensureCapacity(bytes)) { - this.droppedLines += 1; - return false; - } - - const normalized = path.resolve(filePath); - const file = this.files.get(normalized); - if (!file) { - if (this.activate(normalized) === null) { - this.droppedLines += 1; return false; - } - return this.reserve(normalized, bytes); - } - file.bytes += bytes; - file.mtimeMs = Date.now(); - this.usedBytes += bytes; - return true; - } - - writeFailed(filePath: string, error: unknown): void { - this.storageFailed(`write ${filePath}`, error); - } - - storageFailed(operation: string, error: unknown): void { - this.enterDegraded(`${operation}: ${errorMessage(error)}`); - } - - snapshot(): Omit { - return { - state: this.degraded ? 'degraded' : this.lastError ? 'warning' : 'healthy', - totalBytes: this.usedBytes, - fileCount: this.files.size, - activeFileCount: this.active.size, - droppedLines: this.droppedLines, - ...(this.lastError ? { lastError: this.lastError } : {}), - }; - } - - updatePolicy(maxTotalBytes: number, retainDays: number): void { - this.maxTotalBytes = maxTotalBytes; - this.retainDays = retainDays; - this.degraded = false; - this.lastError = null; - this.nextRetryAt = 0; - try { - this.refreshClosedFiles(); - this.cleanupExpired(); - this.ensureCapacity(0); - } catch (error) { - this.enterDegraded(`failed to apply log storage policy: ${errorMessage(error)}`); - throw error; - } - } - - clearClosedFiles(): Omit { - this.refreshClosedFiles(); - let deletedFiles = 0; - let freedBytes = 0; - const failures: LogCleanupResult['failures'] = []; - const candidates = [...this.files.values()] - .filter((file) => !this.active.has(file.path)) - .sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path)); - for (const file of candidates) { - const bytes = file.bytes; - if (this.deleteManagedFile(file, 'capacity')) { - deletedFiles += 1; - freedBytes += bytes; - } else { - failures.push({ - file: path.relative(this.root, file.path), - message: this.lastError ?? 'unknown cleanup error', - }); - } - } - if (failures.length === 0) { - this.degraded = false; - this.lastError = null; - this.nextRetryAt = 0; - } else if (this.usedBytes > this.maxTotalBytes) { - this.enterDegraded( - `managed logs still use ${String(this.usedBytes)} bytes after manual cleanup, ` - + `exceeding the ${String(this.maxTotalBytes)} byte limit`, - ); - } - this.ensureCapacity(0); - return { deletedFiles, freedBytes, failures }; - } - - private retry(force: boolean): boolean { - if (!force && Date.now() < this.nextRetryAt) return false; - this.degraded = false; - this.lastError = null; - try { - this.refreshClosedFiles(); - const recovered = this.ensureCapacity(0); - if (recovered) this.nextRetryAt = 0; - return recovered; - } catch (error) { - this.enterDegraded(`failed to refresh managed logs: ${errorMessage(error)}`); - return false; - } - } - - private maintainAfterClose(): void { - try { - this.refreshClosedFiles(); - this.cleanupExpired(); - if (this.degraded) this.retry(true); - else this.ensureCapacity(0); - } catch (error) { - this.enterDegraded(`failed to maintain managed logs after rotation: ${errorMessage(error)}`); - } - } - - private ensureCapacity(incomingBytes: number): boolean { - if (this.usedBytes + incomingBytes <= this.maxTotalBytes) return true; - - const candidates = [...this.files.values()] - .filter((file) => !this.active.has(file.path)) - .sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path)); - for (const file of candidates) { - if (this.usedBytes + incomingBytes <= this.maxTotalBytes) break; - if (!this.deleteManagedFile(file, 'capacity')) break; } - if (this.usedBytes + incomingBytes <= this.maxTotalBytes) return true; - this.enterDegraded( - `managed logs require ${String(this.usedBytes + incomingBytes)} bytes, ` - + `exceeding the ${String(this.maxTotalBytes)} byte limit; no closed log can be reclaimed`, - ); - return false; - } + private enterDegraded(message: string): void { + const shouldReport = !this.degraded || this.lastError !== message; + this.degraded = true; + this.lastError = message; + this.nextRetryAt = Date.now() + QUOTA_RETRY_MS; - private enterDegraded(message: string): void { - const shouldReport = !this.degraded || this.lastError !== message; - this.degraded = true; - this.lastError = message; - this.nextRetryAt = Date.now() + QUOTA_RETRY_MS; - if (shouldReport) reportStorageError(message); - } + if (shouldReport) { + reportStorageError(message); + } + } - private cleanupExpired(): void { - if (this.retainDays === 0) return; - const cutoff = Date.now() - this.retainDays * 24 * 60 * 60 * 1000; - const expired = [...this.files.values()] - .filter( - (file) => !this.active.has(file.path) && dateOf(file.date).getTime() < cutoff, - ) - .sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path)); - for (const file of expired) { - if (!this.deleteManagedFile(file, 'retention')) break; - } - } + private cleanupExpired(): void { + if (this.retainDays === 0) { + return; + } - private deleteManagedFile(file: ManagedLogFile, reason: 'capacity' | 'retention'): boolean { - try { - fs.unlinkSync(file.path); - this.files.delete(file.path); - this.usedBytes = Math.max(0, this.usedBytes - file.bytes); - return true; - } catch (error) { - this.lastError = - `${reason} cleanup failed for ${file.path}: ${error instanceof Error ? error.message : String(error)}`; - reportStorageError(this.lastError); - return false; - } - } + const cutoff = Date.now() - this.retainDays * 24 * 60 * 60 * 1000; + const expired = [...this.files.values()] + .filter((file) => !this.active.has(file.path) && dateOf(file.date).getTime() < cutoff) + .sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path)); - private loadManagedFiles(): void { - for (const file of listManagedLogFiles(this.root)) { - this.files.set(file.path, file); - this.usedBytes += file.bytes; + for (const file of expired) { + if (!this.deleteManagedFile(file, 'retention')) { + break; + } + } } - } - /** Refresh only closed files; active stream bytes are tracked in-memory and - * may be newer than fs.stat while the WriteStream buffer is still flushing. */ - private refreshClosedFiles(): void { - const disk = new Map(listManagedLogFiles(this.root).map((file) => [file.path, file])); - for (const [filePath, file] of this.files) { - if (this.active.has(filePath)) continue; - const next = disk.get(filePath); - this.usedBytes -= file.bytes; - if (next) { - this.files.set(filePath, next); - this.usedBytes += next.bytes; - disk.delete(filePath); - } else { - this.files.delete(filePath); - } + private deleteManagedFile(file: ManagedLogFile, reason: 'capacity' | 'retention'): boolean { + try { + fs.unlinkSync(file.path); + this.files.delete(file.path); + this.usedBytes = Math.max(0, this.usedBytes - file.bytes); + return true; + } catch (error) { + this.lastError = `${reason} cleanup failed for ${file.path}: ${error instanceof Error ? error.message : String(error)}`; + reportStorageError(this.lastError); + return false; + } } - for (const file of disk.values()) { - if (this.files.has(file.path)) continue; - this.files.set(file.path, file); - this.usedBytes += file.bytes; + + private loadManagedFiles(): void { + for (const file of listManagedLogFiles(this.root)) { + this.files.set(file.path, file); + this.usedBytes += file.bytes; + } + } + + /** Refresh only closed files; active stream bytes are tracked in-memory and + * may be newer than fs.stat while the WriteStream buffer is still flushing. */ + private refreshClosedFiles(): void { + const disk = new Map(listManagedLogFiles(this.root).map((file) => [file.path, file])); + + for (const [filePath, file] of this.files) { + if (this.active.has(filePath)) { + continue; + } + + const next = disk.get(filePath); + this.usedBytes -= file.bytes; + + if (next) { + this.files.set(filePath, next); + this.usedBytes += next.bytes; + disk.delete(filePath); + } else { + this.files.delete(filePath); + } + } + + for (const file of disk.values()) { + if (this.files.has(file.path)) { + continue; + } + + this.files.set(file.path, file); + this.usedBytes += file.bytes; + } } - } } function listManagedLogFiles(root: string): ManagedLogFile[] { - const out: ManagedLogFile[] = []; - const readDirectory = (dir: string): fs.Dirent[] | null => { - try { - return fs.readdirSync(dir, { withFileTypes: true }); - } catch (error) { - if (isMissing(error)) return null; - throw new Error( - `failed to read managed log directory ${dir}: ${errorMessage(error)}`, - { cause: error }, - ); - } - }; - const visit = (dir: string, entries: fs.Dirent[]): void => { - for (const entry of entries) { - if (!entry.isFile()) continue; - const match = FILE_RE.exec(entry.name); - if (!match) continue; - const filePath = path.resolve(dir, entry.name); - try { - const stat = fs.statSync(filePath); - out.push({ - path: filePath, - bytes: stat.size, - mtimeMs: stat.mtimeMs, - date: match[1]!, - }); - } catch (error) { - if (isMissing(error)) continue; - throw new Error( - `failed to stat managed log ${filePath}: ${errorMessage(error)}`, - { cause: error }, - ); - } - } - }; + const out: ManagedLogFile[] = []; - const rootEntries = readDirectory(root); - if (!rootEntries) return out; - visit(root, rootEntries); - for (const entry of rootEntries) { - if (entry.isDirectory() && ACCOUNT_DIR_RE.test(entry.name)) { - const accountDir = path.join(root, entry.name); - const accountEntries = readDirectory(accountDir); - if (accountEntries) visit(accountDir, accountEntries); + const readDirectory = (dir: string): fs.Dirent[] | null => { + try { + return fs.readdirSync(dir, { withFileTypes: true }); + } catch (error) { + if (isMissing(error)) { + return null; + } + + throw new Error(`failed to read managed log directory ${dir}: ${errorMessage(error)}`, { + cause: error, + }); + } + }; + + const visit = (dir: string, entries: fs.Dirent[]): void => { + for (const entry of entries) { + if (!entry.isFile()) { + continue; + } + + const match = FILE_RE.exec(entry.name); + + if (!match) { + continue; + } + + const filePath = path.resolve(dir, entry.name); + + try { + const stat = fs.statSync(filePath); + out.push({ + path: filePath, + bytes: stat.size, + mtimeMs: stat.mtimeMs, + date: match[1]!, + }); + } catch (error) { + if (isMissing(error)) { + continue; + } + + throw new Error(`failed to stat managed log ${filePath}: ${errorMessage(error)}`, { + cause: error, + }); + } + } + }; + + const rootEntries = readDirectory(root); + + if (!rootEntries) { + return out; } - } - return out; + + visit(root, rootEntries); + + for (const entry of rootEntries) { + if (entry.isDirectory() && ACCOUNT_DIR_RE.test(entry.name)) { + const accountDir = path.join(root, entry.name); + const accountEntries = readDirectory(accountDir); + + if (accountEntries) { + visit(accountDir, accountEntries); + } + } + } + + return out; } function reportStorageError(message: string): void { - process.stderr.write(`[logger.storage] ${message}\n`); + process.stderr.write(`[logger.storage] ${message}\n`); } /** @@ -448,546 +557,687 @@ function reportStorageError(message: string): void { * belong to the shared LogQuota, never to each writer independently. */ class FileWriter { - private disabled = false; - private file: OpenFile | null = null; - private readonly pendingCloses = new Set>(); + private disabled = false; + private file: OpenFile | null = null; + private readonly pendingCloses = new Set>(); - constructor( - private readonly dir: string, - private readonly maxBytes: number, - private readonly quota: LogQuota, - ) { - try { - fs.mkdirSync(dir, { recursive: true }); - } catch (err) { - this.disabled = true; - this.quota.storageFailed(`failed to create log directory ${dir}`, err); - return; - } - } - - get isDisabled(): boolean { - return this.disabled; - } - - get currentPath(): string | null { - return this.file?.path ?? null; - } - - async prepare(): Promise { - this.ensureForToday(todayString()); - const stream = this.file?.stream; - if (!stream) { - throw new Error(`failed to prepare log writer in ${this.dir}`); - } - await new Promise((resolve, reject) => { - const opened = () => { - stream.off('error', failed); - resolve(); - }; - const failed = (error: Error) => { - stream.off('open', opened); - reject(error); - }; - stream.once('open', opened); - stream.once('error', failed); - }); - } - - write(data: string, bytes: number): boolean { - if (this.disabled) return false; - const today = todayString(); - this.ensureForToday(today); - if (!this.file) return false; - - if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) { - this.rotateBySize(); - if (!this.file) return false; + constructor( + private readonly dir: string, + private readonly maxBytes: number, + private readonly quota: LogQuota, + ) { + try { + fs.mkdirSync(dir, { recursive: true }); + } catch (err) { + this.disabled = true; + this.quota.storageFailed(`failed to create log directory ${dir}`, err); + return; + } } - if (!this.quota.reserve(this.file.path, bytes)) return false; - try { - this.file.stream.write(data); - } catch (error) { - this.disabled = true; - this.quota.writeFailed(this.file.path, error); - return false; - } - this.file.bytes += bytes; - return true; - } - - async close(): Promise { - this.closeCurrent(); - await Promise.all(this.pendingCloses); - } - - private ensureForToday(today: string): void { - if (this.file && this.file.date === today) return; - - if (this.file) { - this.closeCurrent(); + get isDisabled(): boolean { + return this.disabled; } - // Resume from the highest existing split index for today (so two - // process starts on the same day share files / don't clobber). - let idx = 0; - while (fs.existsSync(this.pathFor(today, idx + 1))) idx++; - this.file = this.openFile(today, idx); - } - - private rotateBySize(): void { - if (!this.file) return; - const date = this.file.date; - const previousIndex = this.file.splitIndex; - this.closeCurrent(); - let next = previousIndex + 1; - while (fs.existsSync(this.pathFor(date, next))) next++; - this.file = this.openFile(date, next); - } - - private closeCurrent(): void { - const file = this.file; - this.file = null; - if (!file) return; - - let finish!: () => void; - const closed = new Promise((resolve) => { - let settled = false; - finish = () => { - if (settled) return; - settled = true; - this.quota.deactivate(file.path); - resolve(); - }; - }); - this.pendingCloses.add(closed); - void closed.finally(() => this.pendingCloses.delete(closed)); - - file.stream.once('error', finish); - try { - file.stream.end(finish); - } catch (error) { - this.quota.writeFailed(file.path, error); - finish(); + get currentPath(): string | null { + return this.file?.path ?? null; } - } - private openFile(date: string, splitIndex: number): OpenFile | null { - const p = this.pathFor(date, splitIndex); - const existingBytes = this.quota.activate(p); - if (existingBytes === null) return null; - try { - const stream = fs.createWriteStream(p, { flags: 'a' }); - stream.on('error', (err) => { - this.disabled = true; - if (this.file?.stream === stream) this.file = null; - this.quota.deactivate(p); - this.quota.writeFailed(p, err); - }); - return { stream, bytes: existingBytes, date, splitIndex, path: p }; - } catch (err) { - this.disabled = true; - this.quota.deactivate(p); - this.quota.storageFailed(`failed to open log file ${p}`, err); - return null; + async prepare(): Promise { + this.ensureForToday(todayString()); + const stream = this.file?.stream; + + if (!stream) { + throw new Error(`failed to prepare log writer in ${this.dir}`); + } + + await new Promise((resolve, reject) => { + const opened = () => { + stream.off('error', failed); + resolve(); + }; + + const failed = (error: Error) => { + stream.off('open', opened); + reject(error); + }; + + stream.once('open', opened); + stream.once('error', failed); + }); } - } - private pathFor(date: string, splitIndex: number): string { - const tail = splitIndex > 0 ? `.${splitIndex}` : ''; - return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`); - } + write(data: string, bytes: number): boolean { + if (this.disabled) { + return false; + } + + const today = todayString(); + this.ensureForToday(today); + + if (!this.file) { + return false; + } + + if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) { + this.rotateBySize(); + + if (!this.file) { + return false; + } + } + + if (!this.quota.reserve(this.file.path, bytes)) { + return false; + } + + try { + this.file.stream.write(data); + } catch (error) { + this.disabled = true; + this.quota.writeFailed(this.file.path, error); + return false; + } + + this.file.bytes += bytes; + return true; + } + + async close(): Promise { + this.closeCurrent(); + await Promise.all(this.pendingCloses); + } + + private ensureForToday(today: string): void { + if (this.file && this.file.date === today) { + return; + } + + if (this.file) { + this.closeCurrent(); + } + + // Resume from the highest existing split index for today (so two + // process starts on the same day share files / don't clobber). + let idx = 0; + + while (fs.existsSync(this.pathFor(today, idx + 1))) { + idx++; + } + + this.file = this.openFile(today, idx); + } + + private rotateBySize(): void { + if (!this.file) { + return; + } + + const date = this.file.date; + const previousIndex = this.file.splitIndex; + this.closeCurrent(); + let next = previousIndex + 1; + + while (fs.existsSync(this.pathFor(date, next))) { + next++; + } + + this.file = this.openFile(date, next); + } + + private closeCurrent(): void { + const file = this.file; + this.file = null; + + if (!file) { + return; + } + + let finish!: () => void; + const closed = new Promise((resolve) => { + let settled = false; + + finish = () => { + if (settled) { + return; + } + + settled = true; + this.quota.deactivate(file.path); + resolve(); + }; + }); + this.pendingCloses.add(closed); + void closed.finally(() => this.pendingCloses.delete(closed)); + + file.stream.once('error', finish); + + try { + file.stream.end(finish); + } catch (error) { + this.quota.writeFailed(file.path, error); + finish(); + } + } + + private openFile(date: string, splitIndex: number): OpenFile | null { + const p = this.pathFor(date, splitIndex); + const existingBytes = this.quota.activate(p); + + if (existingBytes === null) { + return null; + } + + try { + const stream = fs.createWriteStream(p, { flags: 'a' }); + stream.on('error', (err) => { + this.disabled = true; + + if (this.file?.stream === stream) { + this.file = null; + } + + this.quota.deactivate(p); + this.quota.writeFailed(p, err); + }); + return { stream, bytes: existingBytes, date, splitIndex, path: p }; + } catch (err) { + this.disabled = true; + this.quota.deactivate(p); + this.quota.storageFailed(`failed to open log file ${p}`, err); + return null; + } + } + + private pathFor(date: string, splitIndex: number): string { + const tail = splitIndex > 0 ? `.${splitIndex}` : ''; + return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`); + } } export class FileTransport { - private readonly dir: string; - private readonly maxBytes: number; - private maxTotalBytes: number; - private retainDays: number; - private readonly enabled: boolean; - private perUinEnabled: boolean; - private initializationError: string | null = null; - private nextWriterRetryAt = 0; - private quota: LogQuota | null = null; - private shared: FileWriter | null = null; - private perUin = new Map(); + private readonly dir: string; + private readonly maxBytes: number; + private maxTotalBytes: number; + private retainDays: number; + private readonly enabled: boolean; + private perUinEnabled: boolean; + private initializationError: string | null = null; + private nextWriterRetryAt = 0; + private quota: LogQuota | null = null; + private shared: FileWriter | null = null; + private perUin = new Map(); - constructor(policy?: LogStoragePolicy) { - if (policy) validatePolicy(policy); - this.dir = path.resolve(process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR); - this.maxBytes = - parseRequiredPositiveInt( - process.env.SNOWLUMA_LOG_MAX_MB, - DEFAULT_MAX_MB, - MAX_LOG_TOTAL_MB, - 'SNOWLUMA_LOG_MAX_MB', - ) * 1024 * 1024; - this.maxTotalBytes = - (policy?.maxTotalMb - ?? parseRequiredPositiveInt( - process.env.SNOWLUMA_LOG_MAX_TOTAL_MB, - DEFAULT_MAX_TOTAL_MB, - MAX_LOG_TOTAL_MB, - 'SNOWLUMA_LOG_MAX_TOTAL_MB', - )) * 1024 * 1024; - this.retainDays = policy?.retainDays - ?? parseNonNegativeInt( - process.env.SNOWLUMA_LOG_RETAIN_DAYS, - DEFAULT_RETAIN_DAYS, - MAX_LOG_RETAIN_DAYS, - 'SNOWLUMA_LOG_RETAIN_DAYS', - ); - this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0'; - this.perUinEnabled = policy?.perUinEnabled - ?? parseRequiredBool( - process.env.SNOWLUMA_LOG_PER_UIN, - false, - 'SNOWLUMA_LOG_PER_UIN', - ); - - if (this.enabled) this.initialize(); - } - - /** True when no file output will happen (env disable or init failure). */ - get isDisabled(): boolean { - return !this.shared; - } - - /** Current shared-file path (or null if disabled / not yet opened). */ - get currentPath(): string | null { - return this.shared?.currentPath ?? null; - } - - /** Path of the per-UIN file for the given UIN, if open. */ - perUinPath(uin: number): string | null { - return this.perUin.get(uin)?.currentPath ?? null; - } - - getStorageStatus(): LogStorageStatus { - if (!this.quota) { - return { - state: 'disabled', - directory: this.dir, - totalBytes: 0, - maxTotalBytes: this.maxTotalBytes, - retainDays: this.retainDays, - perUinEnabled: this.perUinEnabled, - fileCount: 0, - activeFileCount: 0, - droppedLines: 0, - ...(this.initializationError ? { lastError: this.initializationError } : {}), - }; - } - return { - ...this.quota.snapshot(), - directory: this.dir, - maxTotalBytes: this.maxTotalBytes, - retainDays: this.retainDays, - perUinEnabled: this.perUinEnabled, - }; - } - - async updatePolicy(policy: LogStoragePolicy): Promise { - validatePolicy(policy); - this.maxTotalBytes = policy.maxTotalMb * 1024 * 1024; - this.retainDays = policy.retainDays; - - const disablingPerUin = this.perUinEnabled && !policy.perUinEnabled; - this.perUinEnabled = policy.perUinEnabled; - if (disablingPerUin) { - const writers = [...this.perUin.values()]; - this.perUin.clear(); - await Promise.all(writers.map((writer) => writer.close())); - } - if (this.quota) this.quota.updatePolicy(this.maxTotalBytes, this.retainDays); - if (this.enabled && (!this.quota || !this.shared || this.shared.isDisabled)) { - await this.recoverSharedWriter(true); - } - return this.getStorageStatus(); - } - - async clearManagedLogs(): Promise { - if (!this.enabled) return this.clearLogsWhileDisabled(); - if (!this.quota) { - try { - this.quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays); - } catch (error) { - this.recordWriterRecoveryFailure(error); - } - } - if (!this.quota) { - return { - deletedFiles: 0, - freedBytes: 0, - failures: this.initializationError - ? [{ file: '.', message: this.initializationError }] - : [], - status: this.getStorageStatus(), - }; - } - - const quota = this.quota; - const accountUins = [...this.perUin.keys()]; - const writers = [ - ...(this.shared ? [this.shared] : []), - ...this.perUin.values(), - ]; - this.shared = null; - this.perUin.clear(); - const resumeMaintenance = quota.suspendMaintenance(); - try { - await Promise.all(writers.map((writer) => writer.close())); - } finally { - resumeMaintenance(); - } - - const result = quota.clearClosedFiles(); - - const shared = new FileWriter(this.dir, this.maxBytes, quota); - try { - await shared.prepare(); - this.shared = shared; - this.initializationError = null; - this.nextWriterRetryAt = 0; - } catch (error) { - this.recordWriterRecoveryFailure(error); - result.failures.push({ - file: '.', - message: this.initializationError ?? 'failed to reopen the shared log writer', - }); - } - if (this.perUinEnabled) { - for (const uin of accountUins) { - const writer = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, quota); - if (writer.isDisabled) continue; - try { - await writer.prepare(); - this.perUin.set(uin, writer); - } catch (error) { - quota.storageFailed(`failed to reopen account log writer for ${String(uin)}`, error); - result.failures.push({ - file: String(uin), - message: `failed to reopen account log writer: ${errorMessage(error)}`, - }); + constructor(policy?: LogStoragePolicy) { + if (policy) { + validatePolicy(policy); + } + + this.dir = path.resolve(process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR); + this.maxBytes = + parseRequiredPositiveInt( + process.env.SNOWLUMA_LOG_MAX_MB, + DEFAULT_MAX_MB, + MAX_LOG_TOTAL_MB, + 'SNOWLUMA_LOG_MAX_MB', + ) * + 1024 * + 1024; + this.maxTotalBytes = + (policy?.maxTotalMb ?? + parseRequiredPositiveInt( + process.env.SNOWLUMA_LOG_MAX_TOTAL_MB, + DEFAULT_MAX_TOTAL_MB, + MAX_LOG_TOTAL_MB, + 'SNOWLUMA_LOG_MAX_TOTAL_MB', + )) * + 1024 * + 1024; + this.retainDays = + policy?.retainDays ?? + parseNonNegativeInt( + process.env.SNOWLUMA_LOG_RETAIN_DAYS, + DEFAULT_RETAIN_DAYS, + MAX_LOG_RETAIN_DAYS, + 'SNOWLUMA_LOG_RETAIN_DAYS', + ); + this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0'; + this.perUinEnabled = + policy?.perUinEnabled ?? + parseRequiredBool(process.env.SNOWLUMA_LOG_PER_UIN, false, 'SNOWLUMA_LOG_PER_UIN'); + + if (this.enabled) { + this.initialize(); } - } } - return { ...result, status: this.getStorageStatus() }; - } - - write(line: string, uin?: number): void { - if (!this.enabled) return; - if (!this.shared || this.shared.isDisabled) { - if (!this.recoverSharedWriterForWrite()) return; + /** True when no file output will happen (env disable or init failure). */ + get isDisabled(): boolean { + return !this.shared; } - if (!this.shared) return; - const data = sanitizeLogLine(line) + '\n'; - const bytes = Buffer.byteLength(data, 'utf8'); - if (!this.shared.write(data, bytes)) { - if (this.shared.isDisabled) { + /** Current shared-file path (or null if disabled / not yet opened). */ + get currentPath(): string | null { + return this.shared?.currentPath ?? null; + } + + /** Path of the per-UIN file for the given UIN, if open. */ + perUinPath(uin: number): string | null { + return this.perUin.get(uin)?.currentPath ?? null; + } + + getStorageStatus(): LogStorageStatus { + if (!this.quota) { + return { + state: 'disabled', + directory: this.dir, + totalBytes: 0, + maxTotalBytes: this.maxTotalBytes, + retainDays: this.retainDays, + perUinEnabled: this.perUinEnabled, + fileCount: 0, + activeFileCount: 0, + droppedLines: 0, + ...(this.initializationError ? { lastError: this.initializationError } : {}), + }; + } + + return { + ...this.quota.snapshot(), + directory: this.dir, + maxTotalBytes: this.maxTotalBytes, + retainDays: this.retainDays, + perUinEnabled: this.perUinEnabled, + }; + } + + async updatePolicy(policy: LogStoragePolicy): Promise { + validatePolicy(policy); + this.maxTotalBytes = policy.maxTotalMb * 1024 * 1024; + this.retainDays = policy.retainDays; + + const disablingPerUin = this.perUinEnabled && !policy.perUinEnabled; + this.perUinEnabled = policy.perUinEnabled; + + if (disablingPerUin) { + const writers = [...this.perUin.values()]; + this.perUin.clear(); + await Promise.all(writers.map((writer) => writer.close())); + } + + if (this.quota) { + this.quota.updatePolicy(this.maxTotalBytes, this.retainDays); + } + + if (this.enabled && (!this.quota || !this.shared || this.shared.isDisabled)) { + await this.recoverSharedWriter(true); + } + + return this.getStorageStatus(); + } + + async clearManagedLogs(): Promise { + if (!this.enabled) { + return this.clearLogsWhileDisabled(); + } + + if (!this.quota) { + try { + this.quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays); + } catch (error) { + this.recordWriterRecoveryFailure(error); + } + } + + if (!this.quota) { + return { + deletedFiles: 0, + freedBytes: 0, + failures: this.initializationError + ? [{ file: '.', message: this.initializationError }] + : [], + status: this.getStorageStatus(), + }; + } + + const quota = this.quota; + const accountUins = [...this.perUin.keys()]; + const writers = [...(this.shared ? [this.shared] : []), ...this.perUin.values()]; this.shared = null; + this.perUin.clear(); + const resumeMaintenance = quota.suspendMaintenance(); + + try { + await Promise.all(writers.map((writer) => writer.close())); + } finally { + resumeMaintenance(); + } + + const result = quota.clearClosedFiles(); + + const shared = new FileWriter(this.dir, this.maxBytes, quota); + + try { + await shared.prepare(); + this.shared = shared; + this.initializationError = null; + this.nextWriterRetryAt = 0; + } catch (error) { + this.recordWriterRecoveryFailure(error); + result.failures.push({ + file: '.', + message: this.initializationError ?? 'failed to reopen the shared log writer', + }); + } + + if (this.perUinEnabled) { + for (const uin of accountUins) { + const writer = new FileWriter( + path.join(this.dir, String(uin)), + this.maxBytes, + quota, + ); + + if (writer.isDisabled) { + continue; + } + + try { + await writer.prepare(); + this.perUin.set(uin, writer); + } catch (error) { + quota.storageFailed( + `failed to reopen account log writer for ${String(uin)}`, + error, + ); + result.failures.push({ + file: String(uin), + message: `failed to reopen account log writer: ${errorMessage(error)}`, + }); + } + } + } + + return { ...result, status: this.getStorageStatus() }; + } + + write(line: string, uin?: number): void { + if (!this.enabled) { + return; + } + + if (!this.shared || this.shared.isDisabled) { + if (!this.recoverSharedWriterForWrite()) { + return; + } + } + + if (!this.shared) { + return; + } + + const data = sanitizeLogLine(line) + '\n'; + const bytes = Buffer.byteLength(data, 'utf8'); + + if (!this.shared.write(data, bytes)) { + if (this.shared.isDisabled) { + this.shared = null; + this.nextWriterRetryAt = Date.now() + QUOTA_RETRY_MS; + } + + return; + } + + if (uin !== undefined && this.perUinEnabled && this.quota) { + let w = this.perUin.get(uin); + + if (w?.isDisabled) { + this.perUin.delete(uin); + w = undefined; + } + + if (!w) { + w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.quota); + + if (w.isDisabled) { + return; + } + + this.perUin.set(uin, w); + } + + w.write(data, bytes); + } + } + + async close(): Promise { + const closes: Promise[] = []; + + if (this.shared) { + closes.push(this.shared.close()); + } + + for (const w of this.perUin.values()) { + closes.push(w.close()); + } + + this.shared = null; + this.perUin.clear(); + await Promise.all(closes); + } + + private async recoverSharedWriter(force: boolean): Promise { + if (!this.enabled) { + return; + } + + if (!force && Date.now() < this.nextWriterRetryAt) { + throw new Error(this.initializationError ?? 'log writer retry is rate-limited'); + } + + if (this.shared?.isDisabled) { + this.shared = null; + } + + if (!this.quota) { + this.initialize(); + } + + if (!this.shared && this.quota) { + const writer = new FileWriter(this.dir, this.maxBytes, this.quota); + + if (!writer.isDisabled) { + this.shared = writer; + } + } + + const writer = this.shared; + + if (!writer) { + throw new Error(this.initializationError ?? 'failed to create the shared log writer'); + } + + try { + await writer.prepare(); + + if (writer.isDisabled || !writer.currentPath) { + throw new Error('the shared log writer did not open a file'); + } + + this.initializationError = null; + this.nextWriterRetryAt = 0; + } catch (error) { + this.shared = null; + this.recordWriterRecoveryFailure(error); + throw error; + } + } + + private recoverSharedWriterForWrite(): boolean { + if (!this.enabled || Date.now() < this.nextWriterRetryAt) { + return false; + } + + if (this.shared?.isDisabled) { + this.shared = null; + } + + if (!this.quota) { + this.initialize(); + } + + if (!this.shared && this.quota) { + const writer = new FileWriter(this.dir, this.maxBytes, this.quota); + + if (!writer.isDisabled) { + this.shared = writer; + } + } + + if (this.shared) { + this.initializationError = null; + this.nextWriterRetryAt = 0; + return true; + } + + return false; + } + + private clearLogsWhileDisabled(): LogCleanupResult { + try { + const quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays, false); + const result = quota.clearClosedFiles(); + const snapshot = quota.snapshot(); + return { + ...result, + status: { + ...snapshot, + state: 'disabled', + directory: this.dir, + maxTotalBytes: this.maxTotalBytes, + retainDays: this.retainDays, + perUinEnabled: this.perUinEnabled, + }, + }; + } catch (error) { + const message = `failed to clear disabled log storage ${this.dir}: ${errorMessage(error)}`; + reportStorageError(message); + return { + deletedFiles: 0, + freedBytes: 0, + failures: [{ file: '.', message }], + status: { + state: 'disabled', + directory: this.dir, + totalBytes: 0, + maxTotalBytes: this.maxTotalBytes, + retainDays: this.retainDays, + perUinEnabled: this.perUinEnabled, + fileCount: 0, + activeFileCount: 0, + droppedLines: 0, + lastError: message, + }, + }; + } + } + + private recordWriterRecoveryFailure(error: unknown): void { + this.initializationError = `failed to initialize log storage ${this.dir}: ${errorMessage(error)}`; this.nextWriterRetryAt = Date.now() + QUOTA_RETRY_MS; - } - return; + reportStorageError(this.initializationError); } - if (uin !== undefined && this.perUinEnabled && this.quota) { - let w = this.perUin.get(uin); - if (w?.isDisabled) { - this.perUin.delete(uin); - w = undefined; - } - if (!w) { - w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.quota); - if (w.isDisabled) return; - this.perUin.set(uin, w); - } - w.write(data, bytes); - } - } + private initialize(): void { + try { + fs.mkdirSync(this.dir, { recursive: true }); + const quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays); + const writer = new FileWriter(this.dir, this.maxBytes, quota); - async close(): Promise { - const closes: Promise[] = []; - if (this.shared) closes.push(this.shared.close()); - for (const w of this.perUin.values()) closes.push(w.close()); - this.shared = null; - this.perUin.clear(); - await Promise.all(closes); - } + if (writer.isDisabled) { + throw new Error(`failed to create shared log writer in ${this.dir}`); + } - private async recoverSharedWriter(force: boolean): Promise { - if (!this.enabled) return; - if (!force && Date.now() < this.nextWriterRetryAt) { - throw new Error(this.initializationError ?? 'log writer retry is rate-limited'); + this.quota = quota; + this.shared = writer; + this.initializationError = null; + this.nextWriterRetryAt = 0; + } catch (error) { + this.quota = null; + this.shared = null; + this.recordWriterRecoveryFailure(error); + } } - if (this.shared?.isDisabled) this.shared = null; - if (!this.quota) this.initialize(); - if (!this.shared && this.quota) { - const writer = new FileWriter(this.dir, this.maxBytes, this.quota); - if (!writer.isDisabled) this.shared = writer; - } - const writer = this.shared; - if (!writer) { - throw new Error(this.initializationError ?? 'failed to create the shared log writer'); - } - try { - await writer.prepare(); - if (writer.isDisabled || !writer.currentPath) { - throw new Error('the shared log writer did not open a file'); - } - this.initializationError = null; - this.nextWriterRetryAt = 0; - } catch (error) { - this.shared = null; - this.recordWriterRecoveryFailure(error); - throw error; - } - } - - private recoverSharedWriterForWrite(): boolean { - if (!this.enabled || Date.now() < this.nextWriterRetryAt) return false; - if (this.shared?.isDisabled) this.shared = null; - if (!this.quota) this.initialize(); - if (!this.shared && this.quota) { - const writer = new FileWriter(this.dir, this.maxBytes, this.quota); - if (!writer.isDisabled) this.shared = writer; - } - if (this.shared) { - this.initializationError = null; - this.nextWriterRetryAt = 0; - return true; - } - return false; - } - - private clearLogsWhileDisabled(): LogCleanupResult { - try { - const quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays, false); - const result = quota.clearClosedFiles(); - const snapshot = quota.snapshot(); - return { - ...result, - status: { - ...snapshot, - state: 'disabled', - directory: this.dir, - maxTotalBytes: this.maxTotalBytes, - retainDays: this.retainDays, - perUinEnabled: this.perUinEnabled, - }, - }; - } catch (error) { - const message = `failed to clear disabled log storage ${this.dir}: ${errorMessage(error)}`; - reportStorageError(message); - return { - deletedFiles: 0, - freedBytes: 0, - failures: [{ file: '.', message }], - status: { - state: 'disabled', - directory: this.dir, - totalBytes: 0, - maxTotalBytes: this.maxTotalBytes, - retainDays: this.retainDays, - perUinEnabled: this.perUinEnabled, - fileCount: 0, - activeFileCount: 0, - droppedLines: 0, - lastError: message, - }, - }; - } - } - - private recordWriterRecoveryFailure(error: unknown): void { - this.initializationError = - `failed to initialize log storage ${this.dir}: ${errorMessage(error)}`; - this.nextWriterRetryAt = Date.now() + QUOTA_RETRY_MS; - reportStorageError(this.initializationError); - } - - private initialize(): void { - try { - fs.mkdirSync(this.dir, { recursive: true }); - const quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays); - const writer = new FileWriter(this.dir, this.maxBytes, quota); - if (writer.isDisabled) { - throw new Error(`failed to create shared log writer in ${this.dir}`); - } - this.quota = quota; - this.shared = writer; - this.initializationError = null; - this.nextWriterRetryAt = 0; - } catch (error) { - this.quota = null; - this.shared = null; - this.recordWriterRecoveryFailure(error); - } - } } function validatePolicy(policy: LogStoragePolicy): void { - if ( - !Number.isSafeInteger(policy.maxTotalMb) - || policy.maxTotalMb <= 0 - || policy.maxTotalMb > MAX_LOG_TOTAL_MB - ) { - throw new RangeError( - `maxTotalMb must be an integer in 1..${String(MAX_LOG_TOTAL_MB)}`, - ); - } - if ( - !Number.isSafeInteger(policy.retainDays) - || policy.retainDays < 0 - || policy.retainDays > MAX_LOG_RETAIN_DAYS - ) { - throw new RangeError( - `retainDays must be an integer in 0..${String(MAX_LOG_RETAIN_DAYS)}`, - ); - } - if (typeof policy.perUinEnabled !== 'boolean') { - throw new TypeError('perUinEnabled must be a boolean'); - } + if ( + !Number.isSafeInteger(policy.maxTotalMb) || + policy.maxTotalMb <= 0 || + policy.maxTotalMb > MAX_LOG_TOTAL_MB + ) { + throw new RangeError(`maxTotalMb must be an integer in 1..${String(MAX_LOG_TOTAL_MB)}`); + } + + if ( + !Number.isSafeInteger(policy.retainDays) || + policy.retainDays < 0 || + policy.retainDays > MAX_LOG_RETAIN_DAYS + ) { + throw new RangeError(`retainDays must be an integer in 0..${String(MAX_LOG_RETAIN_DAYS)}`); + } + + if (typeof policy.perUinEnabled !== 'boolean') { + throw new TypeError('perUinEnabled must be a boolean'); + } } let singleton: FileTransport | null = null; let configuredPolicy: LogStoragePolicy | null = null; export function getFileTransport(): FileTransport { - if (!singleton) singleton = new FileTransport(configuredPolicy ?? undefined); - return singleton; + if (!singleton) { + singleton = new FileTransport(configuredPolicy ?? undefined); + } + + return singleton; } export async function configureFileTransport(policy: LogStoragePolicy): Promise { - validatePolicy(policy); - configuredPolicy = { ...policy }; - if (!singleton) singleton = new FileTransport(configuredPolicy); - else await singleton.updatePolicy(configuredPolicy); - return singleton.getStorageStatus(); + validatePolicy(policy); + configuredPolicy = { ...policy }; + + if (!singleton) { + singleton = new FileTransport(configuredPolicy); + } else { + await singleton.updatePolicy(configuredPolicy); + } + + return singleton.getStorageStatus(); } export function getLogStorageStatus(): LogStorageStatus { - return getFileTransport().getStorageStatus(); + return getFileTransport().getStorageStatus(); } export function clearManagedLogs(): Promise { - return getFileTransport().clearManagedLogs(); + return getFileTransport().clearManagedLogs(); } /** Reset state between tests. Closes all active file handles. */ export async function _resetFileTransportForTesting(): Promise { - if (singleton) await singleton.close(); - singleton = null; - configuredPolicy = null; + if (singleton) { + await singleton.close(); + } + + singleton = null; + configuredPolicy = null; } function isMissing(error: unknown): boolean { - return error instanceof Error && 'code' in error && error.code === 'ENOENT'; + return error instanceof Error && 'code' in error && error.code === 'ENOENT'; } function errorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error); + return error instanceof Error ? error.message : String(error); } diff --git a/packages/common/src/log-sanitize.ts b/packages/common/src/log-sanitize.ts index 34f773ff..654d2894 100644 --- a/packages/common/src/log-sanitize.ts +++ b/packages/common/src/log-sanitize.ts @@ -6,41 +6,70 @@ const C1_OSC = 0x9d; const C1_STRING_STARTERS = new Set([0x90, 0x98, 0x9e, 0x9f]); function skipCsi(line: string, start: number): number { - for (let i = start; i < line.length; i += 1) { - const code = line.charCodeAt(i); - if (code >= 0x40 && code <= 0x7e) return i + 1; - } - return line.length; + for (let i = start; i < line.length; i += 1) { + const code = line.charCodeAt(i); + + if (code >= 0x40 && code <= 0x7e) { + return i + 1; + } + } + + return line.length; } function skipControlString(line: string, start: number, allowBell: boolean): number { - for (let i = start; i < line.length; i += 1) { - const code = line.charCodeAt(i); - if (allowBell && code === BEL) return i + 1; - if (code === C1_ST) return i + 1; - if (code === ESC && line.charCodeAt(i + 1) === 0x5c) return i + 2; - } - return line.length; + for (let i = start; i < line.length; i += 1) { + const code = line.charCodeAt(i); + + if (allowBell && code === BEL) { + return i + 1; + } + + if (code === C1_ST) { + return i + 1; + } + + if (code === ESC && line.charCodeAt(i + 1) === 0x5c) { + return i + 2; + } + } + + return line.length; } function skipEscSequence(line: string, start: number): number { - if (start >= line.length) return line.length; + if (start >= line.length) { + return line.length; + } - const first = line.charCodeAt(start); - if (first === 0x5b) return skipCsi(line, start + 1); - if (first === 0x5d) return skipControlString(line, start + 1, true); - if (first === 0x50 || first === 0x58 || first === 0x5e || first === 0x5f) { - return skipControlString(line, start + 1, false); - } + const first = line.charCodeAt(start); - let i = start; - while (i < line.length) { - const code = line.charCodeAt(i); - if (code < 0x20 || code > 0x2f) break; - i += 1; - } - const final = line.charCodeAt(i); - return final >= 0x30 && final <= 0x7e ? i + 1 : start; + if (first === 0x5b) { + return skipCsi(line, start + 1); + } + + if (first === 0x5d) { + return skipControlString(line, start + 1, true); + } + + if (first === 0x50 || first === 0x58 || first === 0x5e || first === 0x5f) { + return skipControlString(line, start + 1, false); + } + + let i = start; + + while (i < line.length) { + const code = line.charCodeAt(i); + + if (code < 0x20 || code > 0x2f) { + break; + } + + i += 1; + } + + const final = line.charCodeAt(i); + return final >= 0x30 && final <= 0x7e ? i + 1 : start; } /** @@ -53,29 +82,34 @@ function skipEscSequence(line: string, start: number): number { * invisible payload into persisted or downloaded logs. */ export function sanitizeLogLine(line: string): string { - let plain = ''; - for (let i = 0; i < line.length;) { - const code = line.charCodeAt(i); + let plain = ''; - if (code === ESC) { - i = skipEscSequence(line, i + 1); - continue; - } - if (code === C1_CSI) { - i = skipCsi(line, i + 1); - continue; - } - if (code === C1_OSC || C1_STRING_STARTERS.has(code)) { - i = skipControlString(line, i + 1, code === C1_OSC); - continue; - } - if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) { - i += 1; - continue; + for (let i = 0; i < line.length;) { + const code = line.charCodeAt(i); + + if (code === ESC) { + i = skipEscSequence(line, i + 1); + continue; + } + + if (code === C1_CSI) { + i = skipCsi(line, i + 1); + continue; + } + + if (code === C1_OSC || C1_STRING_STARTERS.has(code)) { + i = skipControlString(line, i + 1, code === C1_OSC); + continue; + } + + if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) { + i += 1; + continue; + } + + plain += line[i]; + i += 1; } - plain += line[i]; - i += 1; - } - return plain; + return plain; } diff --git a/packages/common/src/log-summary.ts b/packages/common/src/log-summary.ts index 78250cd6..357912c6 100644 --- a/packages/common/src/log-summary.ts +++ b/packages/common/src/log-summary.ts @@ -1,54 +1,67 @@ const MAX_FIELD = 40; const MAX_TOTAL = 200; const SENSITIVE_SEGMENTS = new Set([ - 'authorization', - 'cookie', - 'credential', - 'credentials', - 'password', - 'passwd', - 'secret', - 'token', - 'apikey', - 'privatekey', - 'sessionkey', + 'authorization', + 'cookie', + 'credential', + 'credentials', + 'password', + 'passwd', + 'secret', + 'token', + 'apikey', + 'privatekey', + 'sessionkey', ]); function isSensitiveKey(key: string): boolean { - const segments = key - .replace(/([a-z0-9])([A-Z])/g, '$1 $2') - .split(/[-_.\s]+/) - .filter(Boolean) - .map((segment) => segment.toLowerCase()); + const segments = key + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .split(/[-_.\s]+/) + .filter(Boolean) + .map((segment) => segment.toLowerCase()); - return segments.some((segment, index) => { - if (SENSITIVE_SEGMENTS.has(segment)) return true; - const next = segments[index + 1]; - return next === 'key' && ( - segment === 'api' - || segment === 'private' - || segment === 'session' - ); - }); + return segments.some((segment, index) => { + if (SENSITIVE_SEGMENTS.has(segment)) { + return true; + } + + const next = segments[index + 1]; + return ( + next === 'key' && (segment === 'api' || segment === 'private' || segment === 'session') + ); + }); } function valueRepr(v: unknown, key?: string): string { - if (key !== undefined && isSensitiveKey(key)) return '"***"'; - if (v === null) return 'null'; - if (v === undefined) return 'undefined'; - switch (typeof v) { - case 'string': - return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`; - case 'number': - case 'boolean': - case 'bigint': - return String(v); - case 'object': - if (Array.isArray(v)) return `[len=${v.length}]`; - return '{...}'; - default: - return typeof v; - } + if (key !== undefined && isSensitiveKey(key)) { + return '"***"'; + } + + if (v === null) { + return 'null'; + } + + if (v === undefined) { + return 'undefined'; + } + + switch (typeof v) { + case 'string': + return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`; + case 'number': + case 'boolean': + case 'bigint': + return String(v); + case 'object': + if (Array.isArray(v)) { + return `[len=${v.length}]`; + } + + return '{...}'; + default: + return typeof v; + } } /** @@ -60,218 +73,265 @@ function valueRepr(v: unknown, key?: string): string { * replaced with `...` so the next field doesn't get half-rendered. */ export function summarizeParams(params: unknown): string { - if (params === null || params === undefined) return '{}'; - if (typeof params !== 'object') { - const s = String(params); - return s.length > MAX_TOTAL - ? `${s.slice(0, MAX_TOTAL - 3)}...` - : s; - } - if (Array.isArray(params)) return `[len=${params.length}]`; - - const out: string[] = []; - let total = 0; - for (const [k, v] of Object.entries(params as Record)) { - const entry = `${k}=${valueRepr(v, k)}`; - const separatorLength = out.length > 0 ? 1 : 0; - if (total + separatorLength + entry.length > MAX_TOTAL) { - if (out.length === 0) { - return `${entry.slice(0, MAX_TOTAL - 3)}...`; - } - - const rendered = out.join(' '); - return rendered.length + 4 <= MAX_TOTAL - ? `${rendered} ...` - : `${rendered.slice(0, MAX_TOTAL - 3)}...`; + if (params === null || params === undefined) { + return '{}'; } - out.push(entry); - total += separatorLength + entry.length; - } - return out.join(' '); + + if (typeof params !== 'object') { + const s = String(params); + return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL - 3)}...` : s; + } + + if (Array.isArray(params)) { + return `[len=${params.length}]`; + } + + const out: string[] = []; + let total = 0; + + for (const [k, v] of Object.entries(params as Record)) { + const entry = `${k}=${valueRepr(v, k)}`; + const separatorLength = out.length > 0 ? 1 : 0; + + if (total + separatorLength + entry.length > MAX_TOTAL) { + if (out.length === 0) { + return `${entry.slice(0, MAX_TOTAL - 3)}...`; + } + + const rendered = out.join(' '); + return rendered.length + 4 <= MAX_TOTAL + ? `${rendered} ...` + : `${rendered.slice(0, MAX_TOTAL - 3)}...`; + } + + out.push(entry); + total += separatorLength + entry.length; + } + + return out.join(' '); } -const ASSIGNMENT_START = /(^|[^A-Za-z0-9_-])(["']?)([-_]*(?=[A-Za-z0-9_.-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9_.-]*)\2(\s*[:=]\s*)/gi; +const ASSIGNMENT_START = + /(^|[^A-Za-z0-9_-])(["']?)([-_]*(?=[A-Za-z0-9_.-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9_.-]*)\2(\s*[:=]\s*)/gi; const AUTHORIZATION_BOUNDARY_SEGMENTS = new Set([ - 'authorization', - 'cookie', - 'password', - 'passwd', - 'secret', - 'token', - 'apikey', - 'privatekey', - 'sessionkey', + 'authorization', + 'cookie', + 'password', + 'passwd', + 'secret', + 'token', + 'apikey', + 'privatekey', + 'sessionkey', ]); function keySegments(key: string): string[] { - return key - .replace(/([a-z0-9])([A-Z])/g, '$1 $2') - .split(/[-_.\s]+/) - .filter(Boolean) - .map((segment) => segment.toLowerCase()); + return key + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .split(/[-_.\s]+/) + .filter(Boolean) + .map((segment) => segment.toLowerCase()); } function isKeyKind(key: string, kind: 'authorization' | 'cookie'): boolean { - return keySegments(key).includes(kind); + return keySegments(key).includes(kind); } function isAuthorizationBoundaryKey(key: string): boolean { - const segments = keySegments(key); - return segments.some((segment, index) => { - if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) return true; - const next = segments[index + 1]; - return next === 'key' && ( - segment === 'api' - || segment === 'private' - || segment === 'session' - ); - }); + const segments = keySegments(key); + return segments.some((segment, index) => { + if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) { + return true; + } + + const next = segments[index + 1]; + return ( + next === 'key' && (segment === 'api' || segment === 'private' || segment === 'session') + ); + }); } function quotedValueEnd(message: string, start: number): number | undefined { - const quote = message[start]; - if (quote !== '"' && quote !== "'") return undefined; + const quote = message[start]; - for (let index = start + 1; index < message.length; index += 1) { - if (message[index] === '\\') { - index += 1; - } else if (message[index] === quote) { - return index + 1; + if (quote !== '"' && quote !== "'") { + return undefined; } - } - return message.length; + + for (let index = start + 1; index < message.length; index += 1) { + if (message[index] === '\\') { + index += 1; + } else if (message[index] === quote) { + return index + 1; + } + } + + return message.length; } function cookieValueEnd(message: string, start: number): number { - const initialQuotedEnd = quotedValueEnd(message, start); - let end: number; - if (initialQuotedEnd !== undefined) { - end = initialQuotedEnd; - } else { - end = start; - while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) { - end += 1; - } - } + const initialQuotedEnd = quotedValueEnd(message, start); + let end: number; - while (end < message.length) { - let semicolon: number = end; - while (message[semicolon] === ' ' || message[semicolon] === '\t') { - semicolon += 1; - } - if (message[semicolon] !== ';') break; + if (initialQuotedEnd !== undefined) { + end = initialQuotedEnd; + } else { + end = start; - let nameStart = semicolon + 1; - while (message[nameStart] === ' ' || message[nameStart] === '\t') { - nameStart += 1; - } - let nameEnd = nameStart; - while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) nameEnd += 1; - if (nameEnd === nameStart) break; - - end = nameEnd; - if (message[end] !== '=') continue; - - const attribute = message.slice(nameStart, nameEnd).toLowerCase(); - const valueStart = end + 1; - const quotedEnd = quotedValueEnd(message, valueStart); - if (quotedEnd !== undefined) { - end = quotedEnd; - continue; + while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) { + end += 1; + } } - if (attribute !== 'expires') { - end = valueStart; - while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) { - end += 1; - } - continue; + while (end < message.length) { + let semicolon: number = end; + + while (message[semicolon] === ' ' || message[semicolon] === '\t') { + semicolon += 1; + } + + if (message[semicolon] !== ';') { + break; + } + + let nameStart = semicolon + 1; + + while (message[nameStart] === ' ' || message[nameStart] === '\t') { + nameStart += 1; + } + + let nameEnd = nameStart; + + while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) { + nameEnd += 1; + } + + if (nameEnd === nameStart) { + break; + } + + end = nameEnd; + + if (message[end] !== '=') { + continue; + } + + const attribute = message.slice(nameStart, nameEnd).toLowerCase(); + const valueStart = end + 1; + const quotedEnd = quotedValueEnd(message, valueStart); + + if (quotedEnd !== undefined) { + end = quotedEnd; + continue; + } + + if (attribute !== 'expires') { + end = valueStart; + + while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) { + end += 1; + } + + continue; + } + + end = valueStart; + + while (end < message.length && !/[;}\]&\r\n]/.test(message[end]!)) { + end += 1; + } + + const assignments = new RegExp(ASSIGNMENT_START.source, 'gi'); + assignments.lastIndex = valueStart; + const nextField = assignments.exec(message); + + if (nextField && nextField.index < end) { + end = nextField.index; + } } - end = valueStart; - while (end < message.length && !/[;}\]&\r\n]/.test(message[end]!)) { - end += 1; - } - const assignments = new RegExp(ASSIGNMENT_START.source, 'gi'); - assignments.lastIndex = valueStart; - const nextField = assignments.exec(message); - if (nextField && nextField.index < end) end = nextField.index; - } - return end; + return end; } function genericValueEnd(message: string, start: number): number { - const quotedEnd = quotedValueEnd(message, start); - if (quotedEnd !== undefined) return quotedEnd; + const quotedEnd = quotedValueEnd(message, start); - let end = start; - while (end < message.length && !/[\s,}\]&\r\n]/.test(message[end]!)) { - end += 1; - } - return end; + if (quotedEnd !== undefined) { + return quotedEnd; + } + + let end = start; + + while (end < message.length && !/[\s,}\]&\r\n]/.test(message[end]!)) { + end += 1; + } + + return end; } -function authorizationValueEnd( - message: string, - start: number, - query: boolean, -): number { - const quotedEnd = quotedValueEnd(message, start); - if (quotedEnd !== undefined) return quotedEnd; +function authorizationValueEnd(message: string, start: number, query: boolean): number { + const quotedEnd = quotedValueEnd(message, start); - if (query) { - const queryEnd = message.indexOf('&', start); - return queryEnd >= 0 ? queryEnd : message.length; - } - - let end = message.length; - const structural = message.slice(start).search(/[\r\n}\]]/); - if (structural >= 0) end = start + structural; - - const assignments = new RegExp(ASSIGNMENT_START.source, 'gi'); - const remaining = message.slice(start, end); - for (let match = assignments.exec(remaining); match; match = assignments.exec(remaining)) { - if (isAuthorizationBoundaryKey(match[3]!)) { - end = start + match.index; - break; + if (quotedEnd !== undefined) { + return quotedEnd; } - } - return end; + + if (query) { + const queryEnd = message.indexOf('&', start); + return queryEnd >= 0 ? queryEnd : message.length; + } + + let end = message.length; + const structural = message.slice(start).search(/[\r\n}\]]/); + + if (structural >= 0) { + end = start + structural; + } + + const assignments = new RegExp(ASSIGNMENT_START.source, 'gi'); + const remaining = message.slice(start, end); + + for (let match = assignments.exec(remaining); match; match = assignments.exec(remaining)) { + if (isAuthorizationBoundaryKey(match[3]!)) { + end = start + match.index; + break; + } + } + + return end; } /** Redact explicit authentication assignments in ordinary formatted logs. */ export function redactLogMessage(message: string): string { - let out = ''; - let cursor = 0; - ASSIGNMENT_START.lastIndex = 0; + let out = ''; + let cursor = 0; + ASSIGNMENT_START.lastIndex = 0; - for (let match = ASSIGNMENT_START.exec(message); match; match = ASSIGNMENT_START.exec(message)) { - const key = match[3]!; - if (!isSensitiveKey(key)) { - ASSIGNMENT_START.lastIndex = Math.max( - match.index + 1, - ASSIGNMENT_START.lastIndex - 1, - ); - continue; + for ( + let match = ASSIGNMENT_START.exec(message); + match; + match = ASSIGNMENT_START.exec(message) + ) { + const key = match[3]!; + + if (!isSensitiveKey(key)) { + ASSIGNMENT_START.lastIndex = Math.max(match.index + 1, ASSIGNMENT_START.lastIndex - 1); + continue; + } + + const valueStart = ASSIGNMENT_START.lastIndex; + const valueEnd = isKeyKind(key, 'authorization') + ? authorizationValueEnd(message, valueStart, match[1] === '?' || match[1] === '&') + : isKeyKind(key, 'cookie') + ? cookieValueEnd(message, valueStart) + : genericValueEnd(message, valueStart); + + out += message.slice(cursor, valueStart) + '***'; + cursor = valueEnd; + ASSIGNMENT_START.lastIndex = valueEnd; } - const valueStart = ASSIGNMENT_START.lastIndex; - const valueEnd = isKeyKind(key, 'authorization') - ? authorizationValueEnd( - message, - valueStart, - match[1] === '?' || match[1] === '&', - ) - : isKeyKind(key, 'cookie') - ? cookieValueEnd(message, valueStart) - : genericValueEnd(message, valueStart); - - out += message.slice(cursor, valueStart) + '***'; - cursor = valueEnd; - ASSIGNMENT_START.lastIndex = valueEnd; - } - - return out + message.slice(cursor); + return out + message.slice(cursor); } /** @@ -280,34 +340,44 @@ export function redactLogMessage(message: string): string { * unredacted so a reproduction contains the complete business input. */ export function renderParamsVerbose(params: unknown): string { - const seen = new WeakSet(); + const seen = new WeakSet(); - const walk = (value: unknown): string => { - if (value === null) return 'null'; - if (value === undefined) return 'undefined'; + const walk = (value: unknown): string => { + if (value === null) { + return 'null'; + } - switch (typeof value) { - case 'string': - return JSON.stringify(value); - case 'number': - case 'boolean': - case 'bigint': - return String(value); - case 'object': { - if (seen.has(value as object)) return '"[circular]"'; - seen.add(value as object); - const out = Array.isArray(value) - ? `[${value.map((item) => walk(item)).join(',')}]` - : `{${Object.entries(value as Record) - .map(([key, item]) => `${key}:${walk(item)}`) - .join(',')}}`; - seen.delete(value as object); - return out; - } - default: - return typeof value; - } - }; + if (value === undefined) { + return 'undefined'; + } - return walk(params); + switch (typeof value) { + case 'string': + return JSON.stringify(value); + case 'number': + case 'boolean': + case 'bigint': + return String(value); + + case 'object': { + if (seen.has(value as object)) { + return '"[circular]"'; + } + + seen.add(value as object); + const out = Array.isArray(value) + ? `[${value.map((item) => walk(item)).join(',')}]` + : `{${Object.entries(value as Record) + .map(([key, item]) => `${key}:${walk(item)}`) + .join(',')}}`; + seen.delete(value as object); + return out; + } + + default: + return typeof value; + } + }; + + return walk(params); } diff --git a/packages/common/src/logger.ts b/packages/common/src/logger.ts index 4903f82c..30ae1584 100644 --- a/packages/common/src/logger.ts +++ b/packages/common/src/logger.ts @@ -3,64 +3,64 @@ import { getFileTransport } from './log-file-transport'; import { redactLogMessage } from './log-summary'; import { sanitizeLogLine } from './log-sanitize'; import { - currentRequestId, - nextRequestId, - runWithoutRequestContext, - runWithRequestId, + currentRequestId, + nextRequestId, + runWithoutRequestContext, + runWithRequestId, } from './request-context'; type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error'; type FileLogLevel = Exclude; export interface LogEntry { - id: number; - time: string; - level: LogLevel; - scope: string; - /** QQ uin, when the source logger was derived via `.child({ uin })`. */ - uin?: number; - /** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */ - req?: number; - message: string; - line: string; + id: number; + time: string; + level: LogLevel; + scope: string; + /** QQ uin, when the source logger was derived via `.child({ uin })`. */ + uin?: number; + /** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */ + req?: number; + message: string; + line: string; } interface LogOptions { - scope: string; - uin?: number; - /** Free-form meta carried across `.child(...)` calls. Currently only - * `uin` is rendered, but the bag is preserved for future fields - * (requestId / traceId / etc.). */ - meta?: Record; + scope: string; + uin?: number; + /** Free-form meta carried across `.child(...)` calls. Currently only + * `uin` is rendered, but the bag is preserved for future fields + * (requestId / traceId / etc.). */ + meta?: Record; } const UIN_SLOT_WIDTH = 12; const LEVEL_WEIGHT: Record = { - trace: 5, - debug: 10, - info: 20, - success: 25, - warn: 30, - error: 40, + trace: 5, + debug: 10, + info: 20, + success: 25, + warn: 30, + error: 40, }; const LEVEL_LABEL: Record = { - trace: 'TRACE', - debug: 'DEBUG', - info: 'INFO', - success: 'OK', - warn: 'WARN', - error: 'ERROR', + trace: 'TRACE', + debug: 'DEBUG', + info: 'INFO', + success: 'OK', + warn: 'WARN', + error: 'ERROR', }; const COLOR_CODE: Record = { - trace: 90, - debug: 90, - info: 36, - success: 32, - warn: 33, - error: 31, + trace: 90, + debug: 90, + info: 36, + success: 32, + warn: 33, + error: 31, }; const COLOR_SCOPE = 35; @@ -70,9 +70,10 @@ const MAX_LOG_ENTRIES = 1000; /** Trace ring cap — env-tunable since trace is the high-volume stream. */ function resolveTraceBufferMax(): number { - const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10); - return Number.isFinite(raw) && raw >= 100 ? raw : 5000; + const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10); + return Number.isFinite(raw) && raw >= 100 ? raw : 5000; } + const TRACE_BUFFER_MAX = resolveTraceBufferMax(); /** @@ -80,32 +81,40 @@ const TRACE_BUFFER_MAX = resolveTraceBufferMax(); * so the high-throughput trace stream never pays an O(n) shift per overflow. */ class RingBuffer { - private readonly buf: (T | undefined)[]; - private start = 0; - private count = 0; - constructor(private readonly cap: number) { - this.buf = new Array(cap); - } - push(item: T): void { - const end = (this.start + this.count) % this.cap; - this.buf[end] = item; - if (this.count < this.cap) this.count += 1; - else this.start = (this.start + 1) % this.cap; // full → overwrite oldest - } - /** Most recent `n` items, oldest→newest. */ - recent(n: number): T[] { - const take = Math.max(0, Math.min(Math.trunc(n), this.count)); - const out: T[] = new Array(take); - const first = this.start + (this.count - take); - for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!; - return out; - } - toArray(): T[] { - return this.recent(this.count); - } - get size(): number { - return this.count; - } + private readonly buf: (T | undefined)[]; + private start = 0; + private count = 0; + constructor(private readonly cap: number) { + this.buf = new Array(cap); + } + push(item: T): void { + const end = (this.start + this.count) % this.cap; + this.buf[end] = item; + + if (this.count < this.cap) { + this.count += 1; + } else { + this.start = (this.start + 1) % this.cap; + } // full → overwrite oldest + } + /** Most recent `n` items, oldest→newest. */ + recent(n: number): T[] { + const take = Math.max(0, Math.min(Math.trunc(n), this.count)); + const out: T[] = new Array(take); + const first = this.start + (this.count - take); + + for (let i = 0; i < take; i += 1) { + out[i] = this.buf[(first + i) % this.cap]!; + } + + return out; + } + toArray(): T[] { + return this.recent(this.count); + } + get size(): number { + return this.count; + } } const logRing = new RingBuffer(MAX_LOG_ENTRIES); @@ -114,25 +123,44 @@ const logSubscribers = new Set<(entry: LogEntry) => void>(); let nextLogId = 1; function resolveMinLevel(): LogLevel { - const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase(); - if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') { - return raw; - } - return 'info'; + const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase(); + + if ( + raw === 'trace' || + raw === 'debug' || + raw === 'info' || + raw === 'success' || + raw === 'warn' || + raw === 'error' + ) { + return raw; + } + + return 'info'; } function resolveFileMinLevel(): FileLogLevel { - const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL; - if (raw === undefined || raw.trim() === '') return 'debug'; + const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL; - const normalized = raw.trim().toLowerCase(); - if (normalized === 'debug' || normalized === 'info' || normalized === 'success' || - normalized === 'warn' || normalized === 'error') { - return normalized; - } - throw new TypeError( - 'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error', - ); + if (raw === undefined || raw.trim() === '') { + return 'debug'; + } + + const normalized = raw.trim().toLowerCase(); + + if ( + normalized === 'debug' || + normalized === 'info' || + normalized === 'success' || + normalized === 'warn' || + normalized === 'error' + ) { + return normalized; + } + + throw new TypeError( + 'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error', + ); } // Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but @@ -145,141 +173,158 @@ let currentLevel: LogLevel = resolveMinLevel(); const currentFileLevel: FileLogLevel = resolveFileMinLevel(); function shouldLog(level: LogLevel): boolean { - return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel]; + return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel]; } function shouldLogToFile(level: LogLevel): boolean { - return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentFileLevel]; + return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentFileLevel]; } -export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error']; +export const LOG_LEVELS: readonly LogLevel[] = [ + 'trace', + 'debug', + 'info', + 'success', + 'warn', + 'error', +]; export function getLogLevel(): LogLevel { - return currentLevel; + return currentLevel; } - // Change the console / subscriber level at runtime. // Invalid input is a no-op (returns false). // Does not affect the file transport log level. export function setLogLevel(level: string): boolean { - const lower = String(level).toLowerCase(); - if (!LOG_LEVELS.includes(lower as LogLevel)) return false; - currentLevel = lower as LogLevel; - return true; + const lower = String(level).toLowerCase(); + + if (!LOG_LEVELS.includes(lower as LogLevel)) { + return false; + } + + currentLevel = lower as LogLevel; + return true; } function useColor(): boolean { - if (process.env.NO_COLOR === '1') return false; - return Boolean(process.stdout.isTTY); + if (process.env.NO_COLOR === '1') { + return false; + } + + return Boolean(process.stdout.isTTY); } function ansi(code: number, text: string): string { - return `\x1b[${code}m${text}${COLOR_RESET}`; + return `\x1b[${code}m${text}${COLOR_RESET}`; } function currentTime(): string { - const d = new Date(); - const hh = String(d.getHours()).padStart(2, '0'); - const mm = String(d.getMinutes()).padStart(2, '0'); - const ss = String(d.getSeconds()).padStart(2, '0'); - return `${hh}:${mm}:${ss}`; + const d = new Date(); + const hh = String(d.getHours()).padStart(2, '0'); + const mm = String(d.getMinutes()).padStart(2, '0'); + const ss = String(d.getSeconds()).padStart(2, '0'); + return `${hh}:${mm}:${ss}`; } function render(level: LogLevel, options: LogOptions, message: string, reqId?: number): string { - const ts = currentTime(); - const label = LEVEL_LABEL[level].padEnd(5, ' '); - const uinTag = options.uin !== undefined ? `[${options.uin}]` : ''; - const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH); - const reqTag = reqId !== undefined ? `[req#${reqId}]` : ''; + const ts = currentTime(); + const label = LEVEL_LABEL[level].padEnd(5, ' '); + const uinTag = options.uin !== undefined ? `[${options.uin}]` : ''; + const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH); + const reqTag = reqId !== undefined ? `[req#${reqId}]` : ''; - if (!useColor()) { - return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`; - } + if (!useColor()) { + return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`; + } - const cTs = ansi(COLOR_DIM, ts); - const cLabel = ansi(COLOR_CODE[level], label); - // Pad first, then color only the visible tag so escape codes don't eat - // into the alignment width. - const cUin = uinTag - ? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length)) - : ' '.repeat(UIN_SLOT_WIDTH); - const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`); - const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : ''; - return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`; + const cTs = ansi(COLOR_DIM, ts); + const cLabel = ansi(COLOR_CODE[level], label); + // Pad first, then color only the visible tag so escape codes don't eat + // into the alignment width. + const cUin = uinTag + ? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length)) + : ' '.repeat(UIN_SLOT_WIDTH); + const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`); + const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : ''; + return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`; } -function emit( - level: LogLevel, - options: LogOptions, - args: unknown[], -): void { - // Console / subscriber and file filters are independent. If no destination - // accepts the record, stop before formatting or building a LogEntry. - const passesConsole = shouldLog(level); - const passesFile = level !== 'trace' - && shouldLogToFile(level); - if (!passesConsole && !passesFile) return; +function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { + // Console / subscriber and file filters are independent. If no destination + // accepts the record, stop before formatting or building a LogEntry. + const passesConsole = shouldLog(level); + const passesFile = level !== 'trace' && shouldLogToFile(level); - // `trace` is the high-volume full-chain diagnostic stream, intentionally - // excluded from disk to avoid I/O saturation. When console is not dialed - // to trace, the early return below skips format/render/disk entirely. - // Set SNOWLUMA_LOG_LEVEL=trace to inspect trace output in console/memory; - // trace never reaches disk regardless. - if (level === 'trace' && !passesConsole) return; - - // Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer - // (and its expensive deep render) only runs now that trace is confirmed live. - let realArgs = args; - if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') { - realArgs = (args[0] as () => unknown[])(); - } - - const reqId = currentRequestId(); - const formattedMessage = format(...realArgs); - const message = level === 'trace' - ? formattedMessage - : redactLogMessage(formattedMessage); - const line = render(level, options, message, reqId); - const entry: LogEntry = { - id: nextLogId++, - time: new Date().toISOString(), - level, - scope: options.scope, - ...(options.uin !== undefined ? { uin: options.uin } : {}), - ...(reqId !== undefined ? { req: reqId } : {}), - message, - line: sanitizeLogLine(line), - }; - - if (passesConsole) { - // Trace gets its own ring so its volume never evicts the normal log buffer. - (level === 'trace' ? traceRing : logRing).push(entry); - for (const subscriber of logSubscribers) subscriber(entry); - const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout; - // Strip ASCII control characters before writing to terminal to prevent - // BEL (0x07) in user-provided strings (e.g. group member names) from - // triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A) - // and ESC (0x1B) so multi-line records (stack traces) and ANSI color - // sequences emitted by render() pass through intact. - // eslint-disable-next-line no-control-regex - const consoleLine = line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n'; - try { - stream.write(consoleLine); - } catch { - // A full Docker json-file log volume can make stdout/stderr throw. - // Logging must not take down message handling or the WebUI. + if (!passesConsole && !passesFile) { + return; } - } - // File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL, - // default debug). `trace` is memory / WebUI only (omitted here to avoid huge - // on-disk volume). ANSI stripping happens inside the transport. UIN routes - // the line to its per-account sub-file in addition to the shared one. - if (passesFile) { - getFileTransport().write(line, options.uin); - } + // `trace` is the high-volume full-chain diagnostic stream, intentionally + // excluded from disk to avoid I/O saturation. When console is not dialed + // to trace, the early return below skips format/render/disk entirely. + // Set SNOWLUMA_LOG_LEVEL=trace to inspect trace output in console/memory; + // trace never reaches disk regardless. + if (level === 'trace' && !passesConsole) { + return; + } + + // Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer + // (and its expensive deep render) only runs now that trace is confirmed live. + let realArgs = args; + + if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') { + realArgs = (args[0] as () => unknown[])(); + } + + const reqId = currentRequestId(); + const formattedMessage = format(...realArgs); + const message = level === 'trace' ? formattedMessage : redactLogMessage(formattedMessage); + const line = render(level, options, message, reqId); + const entry: LogEntry = { + id: nextLogId++, + time: new Date().toISOString(), + level, + scope: options.scope, + ...(options.uin !== undefined ? { uin: options.uin } : {}), + ...(reqId !== undefined ? { req: reqId } : {}), + message, + line: sanitizeLogLine(line), + }; + + if (passesConsole) { + // Trace gets its own ring so its volume never evicts the normal log buffer. + (level === 'trace' ? traceRing : logRing).push(entry); + + for (const subscriber of logSubscribers) { + subscriber(entry); + } + + const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout; + // Strip ASCII control characters before writing to terminal to prevent + // BEL (0x07) in user-provided strings (e.g. group member names) from + // triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A) + // and ESC (0x1B) so multi-line records (stack traces) and ANSI color + // sequences emitted by render() pass through intact. + // eslint-disable-next-line no-control-regex + const consoleLine = line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n'; + + try { + stream.write(consoleLine); + } catch { + // A full Docker json-file log volume can make stdout/stderr throw. + // Logging must not take down message handling or the WebUI. + } + } + + // File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL, + // default debug). `trace` is memory / WebUI only (omitted here to avoid huge + // on-disk volume). ANSI stripping happens inside the transport. UIN routes + // the line to its per-account sub-file in addition to the shared one. + if (passesFile) { + getFileTransport().write(line, options.uin); + } } /** @@ -289,97 +334,101 @@ function emit( * has finalized the write. */ export function closeLogger(): Promise { - return getFileTransport().close(); + return getFileTransport().close(); } function mergeLogRings(): LogEntry[] { - return traceRing.size > 0 - ? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id) - : logRing.toArray(); + return traceRing.size > 0 + ? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id) + : logRing.toArray(); } export function getLogSnapshot(): LogEntry[] { - return mergeLogRings(); + return mergeLogRings(); } export function getRecentLogs(limit = 300): LogEntry[] { - const n = Math.max(1, Math.trunc(limit)); - return mergeLogRings().slice(-n); + const n = Math.max(1, Math.trunc(limit)); + return mergeLogRings().slice(-n); } export function subscribeLogs(callback: (entry: LogEntry) => void): () => void { - logSubscribers.add(callback); - return () => { - logSubscribers.delete(callback); - }; + logSubscribers.add(callback); + + return () => { + logSubscribers.delete(callback); + }; } export interface Logger { - /** - * High-volume, memory-only diagnostic level (never written to disk). Pass a - * lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the - * arguments (and any costly rendering) are built only when trace is active. - * A plain `trace('msg', x)` works too but evaluates its args eagerly. - */ - trace: (...args: unknown[]) => void; - debug: (...args: unknown[]) => void; - info: (...args: unknown[]) => void; - success: (...args: unknown[]) => void; - warn: (...args: unknown[]) => void; - error: (...args: unknown[]) => void; - /** - * Derive a new logger that inherits this one's scope and carries - * additional metadata. Currently `uin` is the only key with rendering - * support (shown in the `[UIN]` slot and routed to a per-UIN file); - * other keys are preserved on the options bag for forward compat. - */ - child: (meta: { uin?: number;[k: string]: unknown }) => Logger; + /** + * High-volume, memory-only diagnostic level (never written to disk). Pass a + * lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the + * arguments (and any costly rendering) are built only when trace is active. + * A plain `trace('msg', x)` works too but evaluates its args eagerly. + */ + trace: (...args: unknown[]) => void; + debug: (...args: unknown[]) => void; + info: (...args: unknown[]) => void; + success: (...args: unknown[]) => void; + warn: (...args: unknown[]) => void; + error: (...args: unknown[]) => void; + /** + * Derive a new logger that inherits this one's scope and carries + * additional metadata. Currently `uin` is the only key with rendering + * support (shown in the `[UIN]` slot and routed to a per-UIN file); + * other keys are preserved on the options bag for forward compat. + */ + child: (meta: { uin?: number; [k: string]: unknown }) => Logger; } function makeLogger(opts: LogOptions): Logger { - return { - trace: (...args: unknown[]) => emit('trace', opts, args), - debug: (...args: unknown[]) => emit('debug', opts, args), - info: (...args: unknown[]) => emit('info', opts, args), - success: (...args: unknown[]) => emit('success', opts, args), - warn: (...args: unknown[]) => emit('warn', opts, args), - error: (...args: unknown[]) => emit('error', opts, args), - child: (meta) => { - const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin; - return makeLogger({ - scope: opts.scope, - uin: nextUin, - meta: { ...(opts.meta ?? {}), ...meta }, - }); - }, - }; + return { + trace: (...args: unknown[]) => emit('trace', opts, args), + debug: (...args: unknown[]) => emit('debug', opts, args), + info: (...args: unknown[]) => emit('info', opts, args), + success: (...args: unknown[]) => emit('success', opts, args), + warn: (...args: unknown[]) => emit('warn', opts, args), + error: (...args: unknown[]) => emit('error', opts, args), + child: (meta) => { + const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin; + return makeLogger({ + scope: opts.scope, + uin: nextUin, + meta: { ...(opts.meta ?? {}), ...meta }, + }); + }, + }; } export function createLogger(scope: string): Logger { - return makeLogger({ scope }); + return makeLogger({ scope }); } export function renderTraceBytes(body: Uint8Array): string { - return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('hex'); + return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('hex'); } export function runWithTraceRequest(fn: () => T): T { - if (currentRequestId() !== undefined || currentLevel !== 'trace') return fn(); - return runWithRequestId(nextRequestId(), fn); + if (currentRequestId() !== undefined || currentLevel !== 'trace') { + return fn(); + } + + return runWithRequestId(nextRequestId(), fn); } export function logInitialWebuiCredentials(password: string): void { - // This is deliberately not a LogEntry: application logs can be retained on - // disk, exported through WebUI, and delivered to subscribers. First-run - // credentials must only cross the process terminal boundary. - const line = render( - 'info', - { scope: 'WebUI' }, - format('initial credentials: user=admin password=%s', password), - ); - // Keep the same terminal control-character policy as regular console logs. - // eslint-disable-next-line no-control-regex - process.stdout.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n'); + // This is deliberately not a LogEntry: application logs can be retained on + // disk, exported through WebUI, and delivered to subscribers. First-run + // credentials must only cross the process terminal boundary. + const line = render( + 'info', + { scope: 'WebUI' }, + format('initial credentials: user=admin password=%s', password), + ); + // Keep the same terminal control-character policy as regular console logs. + // eslint-disable-next-line no-control-regex + process.stdout.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n'); } // Request-correlation primitives remain available for callers that already own diff --git a/packages/common/src/packet-sender.ts b/packages/common/src/packet-sender.ts index ad2b5a19..cfdeb2ed 100644 --- a/packages/common/src/packet-sender.ts +++ b/packages/common/src/packet-sender.ts @@ -1,11 +1,11 @@ export interface SendPacketResult { - success: boolean; - gotResponse: boolean; - errorCode: number; - errorMessage: string; - responseData: Buffer | null; + success: boolean; + gotResponse: boolean; + errorCode: number; + errorMessage: string; + responseData: Buffer | null; } export interface PacketSender { - sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise; + sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise; } diff --git a/packages/common/src/protocol-types.ts b/packages/common/src/protocol-types.ts index ce34f342..590ecc60 100644 --- a/packages/common/src/protocol-types.ts +++ b/packages/common/src/protocol-types.ts @@ -1,11 +1,11 @@ export interface PacketInfo { - pid: number; - uin: string; - packetType?: number; - serviceCmd: string; - seqId: number; - retCode: number; - fromClient: boolean; - body: Uint8Array; + pid: number; + uin: string; + packetType?: number; + serviceCmd: string; + seqId: number; + retCode: number; + fromClient: boolean; + body: Uint8Array; } export type PacketSink = (packet: PacketInfo) => void; diff --git a/packages/common/src/request-context.ts b/packages/common/src/request-context.ts index e6ca6ce0..18efc760 100644 --- a/packages/common/src/request-context.ts +++ b/packages/common/src/request-context.ts @@ -1,7 +1,7 @@ import { AsyncLocalStorage } from 'async_hooks'; interface RequestStore { - id: number; + id: number; } const storage = new AsyncLocalStorage(); @@ -13,9 +13,13 @@ let counter = 0; * unambiguous. */ export function nextRequestId(): number { - counter = (counter + 1) >>> 0; - if (counter === 0) counter = 1; - return counter; + counter = (counter + 1) >>> 0; + + if (counter === 0) { + counter = 1; + } + + return counter; } /** @@ -26,15 +30,15 @@ export function nextRequestId(): number { * journey (entry → outbound packets → exit) under one `[req#N]` tag. */ export function runWithRequestId(id: number, fn: () => T): T { - return storage.run({ id }, fn); + return storage.run({ id }, fn); } /** Run `fn` without inheriting an ambient request id. */ export function runWithoutRequestContext(fn: () => T): T { - return storage.run(undefined, fn); + return storage.run(undefined, fn); } /** The request id bound to the current async context, or undefined outside one. */ export function currentRequestId(): number | undefined { - return storage.getStore()?.id; + return storage.getStore()?.id; } diff --git a/packages/common/src/runtime.ts b/packages/common/src/runtime.ts index e0f6392b..b676f6f4 100644 --- a/packages/common/src/runtime.ts +++ b/packages/common/src/runtime.ts @@ -2,26 +2,26 @@ import fs from 'fs'; import path from 'path'; export interface RuntimeConfig { - webuiPort?: number; - /** When true, every newly-discovered QQ process gets auto-injected by - * 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. '127.0.0.1' = localhost-only (default), - * '0.0.0.0' = all IPv4 interfaces. 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; - /** Aggregate cap for every managed file below the log root. */ - logMaxTotalMb?: number; - /** Calendar-day retention. Zero disables date-based deletion. */ - logRetainDays?: number; - /** Duplicate UIN-scoped lines into logs// in addition to the shared log. */ - logPerUin?: boolean; + webuiPort?: number; + /** When true, every newly-discovered QQ process gets auto-injected by + * 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. '127.0.0.1' = localhost-only (default), + * '0.0.0.0' = all IPv4 interfaces. 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; + /** Aggregate cap for every managed file below the log root. */ + logMaxTotalMb?: number; + /** Calendar-day retention. Zero disables date-based deletion. */ + logRetainDays?: number; + /** Duplicate UIN-scoped lines into logs// in addition to the shared log. */ + logPerUin?: boolean; } const CONFIG_DIR = 'config'; @@ -33,38 +33,38 @@ export const DEFAULT_LOG_MAX_TOTAL_MB = 1024; export const DEFAULT_LOG_RETAIN_DAYS = 7; export const DEFAULT_LOG_PER_UIN = false; export const MAX_LOG_TOTAL_MB = Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024)); -export const MAX_LOG_RETAIN_DAYS = Math.floor( - Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000), -); +export const MAX_LOG_RETAIN_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000)); /** * 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 : '', - logMaxTotalMb: normalizeRequiredInteger( - obj.logMaxTotalMb, - DEFAULT_LOG_MAX_TOTAL_MB, - 1, - MAX_LOG_TOTAL_MB, - 'logMaxTotalMb', - ), - logRetainDays: normalizeRequiredInteger( - obj.logRetainDays, - DEFAULT_LOG_RETAIN_DAYS, - 0, - MAX_LOG_RETAIN_DAYS, - 'logRetainDays', - ), - logPerUin: normalizeRequiredBool(obj.logPerUin, DEFAULT_LOG_PER_UIN, 'logPerUin'), - }; + 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 : '', + logMaxTotalMb: normalizeRequiredInteger( + obj.logMaxTotalMb, + DEFAULT_LOG_MAX_TOTAL_MB, + 1, + MAX_LOG_TOTAL_MB, + 'logMaxTotalMb', + ), + logRetainDays: normalizeRequiredInteger( + obj.logRetainDays, + DEFAULT_LOG_RETAIN_DAYS, + 0, + MAX_LOG_RETAIN_DAYS, + 'logRetainDays', + ), + logPerUin: normalizeRequiredBool(obj.logPerUin, DEFAULT_LOG_PER_UIN, 'logPerUin'), + }; } /** @@ -73,61 +73,79 @@ export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig { * rewriting the file). Absent vars produce no key. */ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial { - const out: Partial = {}; + const out: Partial = {}; - const port = parsePortString(env.SNOWLUMA_WEBUI_PORT); - if (port !== undefined) out.webuiPort = port; + const port = parsePortString(env.SNOWLUMA_WEBUI_PORT); - const host = env.SNOWLUMA_WEBUI_HOST; - if (typeof host === 'string' && host.trim()) out.webuiHost = host.trim(); + if (port !== undefined) { + out.webuiPort = port; + } - // 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; + const host = env.SNOWLUMA_WEBUI_HOST; - const logMaxTotalMb = parseRequiredIntegerEnv( - env.SNOWLUMA_LOG_MAX_TOTAL_MB, - 1, - MAX_LOG_TOTAL_MB, - 'SNOWLUMA_LOG_MAX_TOTAL_MB', - ); - if (logMaxTotalMb !== undefined) out.logMaxTotalMb = logMaxTotalMb; + if (typeof host === 'string' && host.trim()) { + out.webuiHost = host.trim(); + } - const logRetainDays = parseRequiredIntegerEnv( - env.SNOWLUMA_LOG_RETAIN_DAYS, - 0, - MAX_LOG_RETAIN_DAYS, - 'SNOWLUMA_LOG_RETAIN_DAYS', - ); - if (logRetainDays !== undefined) out.logRetainDays = logRetainDays; + // 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; - const logPerUin = parseRequiredBoolEnv( - env.SNOWLUMA_LOG_PER_UIN, - 'SNOWLUMA_LOG_PER_UIN', - ); - if (logPerUin !== undefined) out.logPerUin = logPerUin; + if (typeof tp === 'string') { + out.trustProxy = tp; + } - const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS'); - if (webuiTls !== undefined) out.webuiTls = { enabled: webuiTls }; + const logMaxTotalMb = parseRequiredIntegerEnv( + env.SNOWLUMA_LOG_MAX_TOTAL_MB, + 1, + MAX_LOG_TOTAL_MB, + 'SNOWLUMA_LOG_MAX_TOTAL_MB', + ); - return out; + if (logMaxTotalMb !== undefined) { + out.logMaxTotalMb = logMaxTotalMb; + } + + const logRetainDays = parseRequiredIntegerEnv( + env.SNOWLUMA_LOG_RETAIN_DAYS, + 0, + MAX_LOG_RETAIN_DAYS, + 'SNOWLUMA_LOG_RETAIN_DAYS', + ); + + if (logRetainDays !== undefined) { + out.logRetainDays = logRetainDays; + } + + const logPerUin = parseRequiredBoolEnv(env.SNOWLUMA_LOG_PER_UIN, 'SNOWLUMA_LOG_PER_UIN'); + + if (logPerUin !== undefined) { + out.logPerUin = logPerUin; + } + + const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS'); + + if (webuiTls !== undefined) { + out.webuiTls = { enabled: webuiTls }; + } + + return out; } export function loadRuntimeConfig(): RuntimeConfig { - fs.mkdirSync(CONFIG_DIR, { recursive: true }); + fs.mkdirSync(CONFIG_DIR, { recursive: true }); - const parsed = tryLoadRuntimeConfig(); - const normalized = normalizeRuntimeConfig(parsed ?? {}); + 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); - } + // 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); + } - // Env overrides apply in-memory only — never written back to disk. - return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) }; + // Env overrides apply in-memory only — never written back to disk. + return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) }; } /** @@ -135,7 +153,7 @@ export function loadRuntimeConfig(): RuntimeConfig { * settings panel's GET — shows what's actually saved/editable on disk. */ export function readRuntimeConfig(): RuntimeConfig { - return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {}); + return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {}); } /** @@ -144,165 +162,243 @@ export function readRuntimeConfig(): RuntimeConfig { * 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; + 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 parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown; - return isObject(parsed) ? parsed : null; - } catch { - return null; - } + if (!fs.existsSync(RUNTIME_CONFIG_PATH)) { + return null; + } + + try { + const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown; + return isObject(parsed) ? parsed : null; + } catch { + return null; + } } function saveRuntimeConfig(config: RuntimeConfig): void { - const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`; - try { - fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8'); - fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH); - } catch (error) { + const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`; + try { - fs.unlinkSync(temporaryPath); - } catch (cleanupError) { - if (!isErrnoCode(cleanupError, 'ENOENT')) { - throw new AggregateError( - [error, cleanupError], - 'failed to persist runtime config and remove its temporary file', - ); - } + fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8'); + fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH); + } catch (error) { + try { + fs.unlinkSync(temporaryPath); + } catch (cleanupError) { + if (!isErrnoCode(cleanupError, 'ENOENT')) { + throw new AggregateError( + [error, cleanupError], + 'failed to persist runtime config and remove its temporary file', + ); + } + } + + throw error; } - throw error; - } } /** 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 - && parsed.logMaxTotalMb === n.logMaxTotalMb - && parsed.logRetainDays === n.logRetainDays - && parsed.logPerUin === n.logPerUin - ); + 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 && + parsed.logMaxTotalMb === n.logMaxTotalMb && + parsed.logRetainDays === n.logRetainDays && + parsed.logPerUin === n.logPerUin + ); } 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; + 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; + 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); - if (n > 0 && n <= 65535) return n; - return fallback; - } - if (typeof value === 'string' && value.trim()) { - const n = Number(value); - if (Number.isFinite(n)) { - const port = Math.trunc(n); - if (port > 0 && port <= 65535) return port; + if (typeof value === 'number' && Number.isFinite(value)) { + const n = Math.trunc(value); + + if (n > 0 && n <= 65535) { + return n; + } + + return fallback; } - } - return fallback; + + if (typeof value === 'string' && value.trim()) { + const n = Number(value); + + if (Number.isFinite(n)) { + const port = Math.trunc(n); + + if (port > 0 && port <= 65535) { + return port; + } + } + } + + return fallback; } function normalizeRequiredInteger( - value: unknown, - fallback: number, - min: number, - max: number, - field: string, + value: unknown, + fallback: number, + min: number, + max: number, + field: string, ): number { - if (value === undefined) return fallback; - const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value; - if ( - typeof n === 'number' - && Number.isSafeInteger(n) - && n >= min - && n <= max - ) { - return n; - } - throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`); + if (value === undefined) { + return fallback; + } + + const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value; + + if (typeof n === 'number' && Number.isSafeInteger(n) && n >= min && n <= max) { + return n; + } + + throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`); } -function normalizeRequiredBool( - value: unknown, - fallback: boolean, - field: string, -): boolean { - if (value === undefined) return fallback; - const parsed = parseBoolValue(value); - if (parsed !== undefined) return parsed; - throw new TypeError(`${field} must be a boolean`); +function normalizeRequiredBool(value: unknown, fallback: boolean, field: string): boolean { + if (value === undefined) { + return fallback; + } + + const parsed = parseBoolValue(value); + + if (parsed !== undefined) { + return parsed; + } + + throw new TypeError(`${field} must be a boolean`); } function normalizeBool(value: unknown, fallback: boolean): boolean { - if (typeof value === 'boolean') return value; - if (typeof value === 'number') return value !== 0; - if (typeof value === 'string') { - const v = value.trim().toLowerCase(); - if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true; - if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') return false; - } - return fallback; + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return value !== 0; + } + + if (typeof value === 'string') { + const v = value.trim().toLowerCase(); + + if (v === 'true' || v === '1' || v === 'yes' || v === 'on') { + return true; + } + + if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') { + return false; + } + } + + return fallback; } function parseRequiredIntegerEnv( - raw: unknown, - min: number, - max: number, - field: string, + raw: unknown, + min: number, + max: number, + field: string, ): number | undefined { - if (typeof raw !== 'string' || !raw.trim()) return undefined; - const n = Number(raw.trim()); - if (Number.isSafeInteger(n) && n >= min && n <= max) return n; - throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`); + if (typeof raw !== 'string' || !raw.trim()) { + return undefined; + } + + const n = Number(raw.trim()); + + if (Number.isSafeInteger(n) && n >= min && n <= max) { + return n; + } + + throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`); } function parseRequiredBoolEnv(raw: unknown, field: string): boolean | undefined { - if (typeof raw !== 'string' || !raw.trim()) return undefined; - const parsed = parseBoolValue(raw); - if (parsed !== undefined) return parsed; - throw new TypeError(`${field} must be a boolean`); + if (typeof raw !== 'string' || !raw.trim()) { + return undefined; + } + + const parsed = parseBoolValue(raw); + + if (parsed !== undefined) { + return parsed; + } + + throw new TypeError(`${field} must be a boolean`); } function parseBoolValue(raw: unknown): boolean | undefined { - if (typeof raw === 'boolean') return raw; - if (raw === 1) return true; - if (raw === 0) return false; - if (typeof raw !== 'string') return undefined; - const value = raw.trim().toLowerCase(); - if (value === 'true' || value === '1' || value === 'yes' || value === 'on') return true; - if (value === 'false' || value === '0' || value === 'no' || value === 'off') return false; - return undefined; + if (typeof raw === 'boolean') { + return raw; + } + + if (raw === 1) { + return true; + } + + if (raw === 0) { + return false; + } + + if (typeof raw !== 'string') { + return undefined; + } + + const value = raw.trim().toLowerCase(); + + if (value === 'true' || value === '1' || value === 'yes' || value === 'on') { + return true; + } + + if (value === 'false' || value === '0' || value === 'no' || value === 'off') { + return false; + } + + return undefined; } function isObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); + return typeof value === 'object' && value !== null && !Array.isArray(value); } function isErrnoCode(error: unknown, code: string): boolean { - return error instanceof Error && 'code' in error && error.code === code; + return error instanceof Error && 'code' in error && error.code === code; } diff --git a/packages/common/src/single-flight-cache.ts b/packages/common/src/single-flight-cache.ts index 4b21ab0b..7789e7c7 100644 --- a/packages/common/src/single-flight-cache.ts +++ b/packages/common/src/single-flight-cache.ts @@ -16,78 +16,90 @@ */ export interface SingleFlightCacheOptions { - /** Freshness window in ms. A cached entry older than this is reloaded. */ - ttlMs: number; - /** Load the value for a key. Rejections propagate and are never cached. */ - load: (key: K) => Promise; - /** - * Decide whether a resolved value should be cached. Default: always. - * Return `false` to leave an entry uncached (e.g. an error-shaped result the - * next call should retry) while still de-duping concurrent in-flight callers. - */ - shouldCache?: (value: V) => boolean; - /** Clock, injectable for tests. Defaults to `Date.now`. */ - now?: () => number; + /** Freshness window in ms. A cached entry older than this is reloaded. */ + ttlMs: number; + /** Load the value for a key. Rejections propagate and are never cached. */ + load: (key: K) => Promise; + /** + * Decide whether a resolved value should be cached. Default: always. + * Return `false` to leave an entry uncached (e.g. an error-shaped result the + * next call should retry) while still de-duping concurrent in-flight callers. + */ + shouldCache?: (value: V) => boolean; + /** Clock, injectable for tests. Defaults to `Date.now`. */ + now?: () => number; } export class SingleFlightCache { - private readonly ttlMs: number; - private readonly load: (key: K) => Promise; - private readonly shouldCache: (value: V) => boolean; - private readonly now: () => number; - private readonly fresh = new Map(); - private readonly inflight = new Map>(); + private readonly ttlMs: number; + private readonly load: (key: K) => Promise; + private readonly shouldCache: (value: V) => boolean; + private readonly now: () => number; + private readonly fresh = new Map(); + private readonly inflight = new Map>(); - constructor(opts: SingleFlightCacheOptions) { - this.ttlMs = opts.ttlMs; - this.load = opts.load; - this.shouldCache = opts.shouldCache ?? (() => true); - this.now = opts.now ?? Date.now; - } - - /** - * Get the value for `key`. - * - * - Returns a fresh cached value when the last load was within `ttlMs`. - * - Otherwise de-dupes concurrent callers onto a single `load()` and caches - * the result (subject to `shouldCache`). A rejected `load` propagates to - * every joined caller, clears the in-flight slot, and is not cached. - * - `force` bypasses the freshness check but still joins an in-flight load - * rather than starting a second one. - */ - get(key: K, opts: { force?: boolean } = {}): Promise { - if (!opts.force) { - const hit = this.fresh.get(key); - if (hit && this.now() - hit.at < this.ttlMs) return Promise.resolve(hit.value); + constructor(opts: SingleFlightCacheOptions) { + this.ttlMs = opts.ttlMs; + this.load = opts.load; + this.shouldCache = opts.shouldCache ?? (() => true); + this.now = opts.now ?? Date.now; } - const existing = this.inflight.get(key); - if (existing) return existing; - const task = (async () => { - try { - const value = await this.load(key); - if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value }); - return value; - } finally { - this.inflight.delete(key); - } - })(); - this.inflight.set(key, task); - return task; - } - /** Drop a cached entry. Does not abort an in-flight load. */ - invalidate(key: K): void { - this.fresh.delete(key); - } + /** + * Get the value for `key`. + * + * - Returns a fresh cached value when the last load was within `ttlMs`. + * - Otherwise de-dupes concurrent callers onto a single `load()` and caches + * the result (subject to `shouldCache`). A rejected `load` propagates to + * every joined caller, clears the in-flight slot, and is not cached. + * - `force` bypasses the freshness check but still joins an in-flight load + * rather than starting a second one. + */ + get(key: K, opts: { force?: boolean } = {}): Promise { + if (!opts.force) { + const hit = this.fresh.get(key); - /** Drop all cached entries. Does not abort in-flight loads. */ - clear(): void { - this.fresh.clear(); - } + if (hit && this.now() - hit.at < this.ttlMs) { + return Promise.resolve(hit.value); + } + } + + const existing = this.inflight.get(key); + + if (existing) { + return existing; + } + + const task = (async () => { + try { + const value = await this.load(key); + + if (this.shouldCache(value)) { + this.fresh.set(key, { at: this.now(), value }); + } + + return value; + } finally { + this.inflight.delete(key); + } + })(); + this.inflight.set(key, task); + return task; + } + + /** Drop a cached entry. Does not abort an in-flight load. */ + invalidate(key: K): void { + this.fresh.delete(key); + } + + /** Drop all cached entries. Does not abort in-flight loads. */ + clear(): void { + this.fresh.clear(); + } } export function createSingleFlightCache( - opts: SingleFlightCacheOptions, + opts: SingleFlightCacheOptions, ): SingleFlightCache { - return new SingleFlightCache(opts); + return new SingleFlightCache(opts); } diff --git a/packages/common/src/uin.ts b/packages/common/src/uin.ts index 62b8f77f..27021d4f 100644 --- a/packages/common/src/uin.ts +++ b/packages/common/src/uin.ts @@ -7,5 +7,5 @@ // Callers rely on a `true` result guaranteeing a BigInt()-safe pure-digit // string. Keep that contract if the pattern ever changes. export function isRealUin(uin: string): boolean { - return /^\d{5,10}$/.test(uin); + return /^\d{5,10}$/.test(uin); } diff --git a/packages/common/tests/access-token.test.ts b/packages/common/tests/access-token.test.ts index 5363483f..de9694a7 100644 --- a/packages/common/tests/access-token.test.ts +++ b/packages/common/tests/access-token.test.ts @@ -1,28 +1,32 @@ import { describe, expect, it } from 'vitest'; import { - ACCESS_TOKEN_MIN_LENGTH, - ACCESS_TOKEN_MIN_SCORE, - assessAccessToken, + ACCESS_TOKEN_MIN_LENGTH, + ACCESS_TOKEN_MIN_SCORE, + assessAccessToken, } from '../src/access-token'; describe('access token strength', () => { - it('requires the configured minimum length', () => { - expect(assessAccessToken('a'.repeat(ACCESS_TOKEN_MIN_LENGTH - 1))).toMatchObject({ - acceptable: false, - reason: 'too-short', + it('requires the configured minimum length', () => { + expect(assessAccessToken('a'.repeat(ACCESS_TOKEN_MIN_LENGTH - 1))).toMatchObject({ + acceptable: false, + reason: 'too-short', + }); }); - }); - it('scores system and user-specific words as guessable', () => { - expect(assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001'])) - .toMatchObject({ acceptable: false, reason: 'guessable' }); - }); + it('scores system and user-specific words as guessable', () => { + expect( + assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001']), + ).toMatchObject({ + acceptable: false, + reason: 'guessable', + }); + }); - it('accepts a sufficiently long, hard-to-guess token', () => { - const result = assessAccessToken('E5xqVb7_9pLt2QwR4M8kZ1nY', ['SnowLuma', 'OneBot']); + it('accepts a sufficiently long, hard-to-guess token', () => { + const result = assessAccessToken('E5xqVb7_9pLt2QwR4M8kZ1nY', ['SnowLuma', 'OneBot']); - expect(result.acceptable).toBe(true); - expect(result.reason).toBe('acceptable'); - expect(result.score).toBeGreaterThanOrEqual(ACCESS_TOKEN_MIN_SCORE); - }); + expect(result.acceptable).toBe(true); + expect(result.reason).toBe('acceptable'); + expect(result.score).toBeGreaterThanOrEqual(ACCESS_TOKEN_MIN_SCORE); + }); }); diff --git a/packages/common/tests/coerce.test.ts b/packages/common/tests/coerce.test.ts index b156ae22..d6e8575b 100644 --- a/packages/common/tests/coerce.test.ts +++ b/packages/common/tests/coerce.test.ts @@ -2,77 +2,77 @@ import { describe, it, expect } from 'vitest'; import { isObject, boolOr, clampNum, clampInt } from '../src/coerce'; describe('isObject', () => { - it('is true only for plain non-null non-array objects', () => { - expect(isObject({})).toBe(true); - expect(isObject({ a: 1 })).toBe(true); - expect(isObject(null)).toBe(false); - expect(isObject([])).toBe(false); - expect(isObject('x')).toBe(false); - expect(isObject(42)).toBe(false); - expect(isObject(undefined)).toBe(false); - }); + it('is true only for plain non-null non-array objects', () => { + expect(isObject({})).toBe(true); + expect(isObject({ a: 1 })).toBe(true); + expect(isObject(null)).toBe(false); + expect(isObject([])).toBe(false); + expect(isObject('x')).toBe(false); + expect(isObject(42)).toBe(false); + expect(isObject(undefined)).toBe(false); + }); }); describe('boolOr', () => { - it('returns the value only when it is a real boolean, else the fallback', () => { - expect(boolOr(true, false)).toBe(true); - expect(boolOr(false, true)).toBe(false); - expect(boolOr('true', false)).toBe(false); // strings are NOT coerced - expect(boolOr(1, false)).toBe(false); - expect(boolOr(undefined, true)).toBe(true); - expect(boolOr(null, true)).toBe(true); - }); + it('returns the value only when it is a real boolean, else the fallback', () => { + expect(boolOr(true, false)).toBe(true); + expect(boolOr(false, true)).toBe(false); + expect(boolOr('true', false)).toBe(false); // strings are NOT coerced + expect(boolOr(1, false)).toBe(false); + expect(boolOr(undefined, true)).toBe(true); + expect(boolOr(null, true)).toBe(true); + }); }); describe('clampNum', () => { - it('passes finite numbers through, clamped to [min,max]', () => { - expect(clampNum(5, 0, 10, -1)).toBe(5); - expect(clampNum(-3, 0, 10, -1)).toBe(0); // below min - expect(clampNum(99, 0, 10, -1)).toBe(10); // above max - }); + it('passes finite numbers through, clamped to [min,max]', () => { + expect(clampNum(5, 0, 10, -1)).toBe(5); + expect(clampNum(-3, 0, 10, -1)).toBe(0); // below min + expect(clampNum(99, 0, 10, -1)).toBe(10); // above max + }); - it('coerces numeric strings', () => { - expect(clampNum('7', 0, 10, -1)).toBe(7); - expect(clampNum('7.5', 0, 10, -1)).toBe(7.5); // NOT truncated (that is clampInt) - }); + it('coerces numeric strings', () => { + expect(clampNum('7', 0, 10, -1)).toBe(7); + expect(clampNum('7.5', 0, 10, -1)).toBe(7.5); // NOT truncated (that is clampInt) + }); - it('falls back on non-finite / non-numeric input', () => { - expect(clampNum('abc', 0, 10, 3)).toBe(3); - expect(clampNum(NaN, 0, 10, 3)).toBe(3); - expect(clampNum(Infinity, 0, 10, 3)).toBe(3); - expect(clampNum(undefined, 0, 10, 3)).toBe(3); - expect(clampNum(null, 0, 10, 3)).toBe(3); - expect(clampNum({}, 0, 10, 3)).toBe(3); - }); + it('falls back on non-finite / non-numeric input', () => { + expect(clampNum('abc', 0, 10, 3)).toBe(3); + expect(clampNum(NaN, 0, 10, 3)).toBe(3); + expect(clampNum(Infinity, 0, 10, 3)).toBe(3); + expect(clampNum(undefined, 0, 10, 3)).toBe(3); + expect(clampNum(null, 0, 10, 3)).toBe(3); + expect(clampNum({}, 0, 10, 3)).toBe(3); + }); - it('preserves fractional precision within bounds', () => { - expect(clampNum(0.42, 0, 1, 0)).toBe(0.42); - }); + it('preserves fractional precision within bounds', () => { + expect(clampNum(0.42, 0, 1, 0)).toBe(0.42); + }); }); describe('clampInt', () => { - it('is clampNum truncated toward zero', () => { - expect(clampInt(7.9, 0, 10, -1)).toBe(7); - expect(clampInt('7.9', 0, 10, -1)).toBe(7); - expect(clampInt(5, 0, 10, -1)).toBe(5); - }); + it('is clampNum truncated toward zero', () => { + expect(clampInt(7.9, 0, 10, -1)).toBe(7); + expect(clampInt('7.9', 0, 10, -1)).toBe(7); + expect(clampInt(5, 0, 10, -1)).toBe(5); + }); - it('clamps before truncating', () => { - expect(clampInt(99.9, 0, 10, -1)).toBe(10); - expect(clampInt(-3.5, 0, 10, -1)).toBe(0); - }); + it('clamps before truncating', () => { + expect(clampInt(99.9, 0, 10, -1)).toBe(10); + expect(clampInt(-3.5, 0, 10, -1)).toBe(0); + }); - it('clamp-then-trunc ordering: a fractional lower bound is crossed by the clamp, not the trunc', () => { - // Distinguishes clamp→trunc (this contract) from trunc→clamp: input 2.4 - // with min 2.5 → clamp lifts to 2.5, then trunc → 2. A trunc-first impl - // would floor to 2 then clamp up to 2.5. Pins the order for the shared - // primitive (future callers may use fractional bounds). - expect(clampInt(2.4, 2.5, 10, 0)).toBe(2); - }); + it('clamp-then-trunc ordering: a fractional lower bound is crossed by the clamp, not the trunc', () => { + // Distinguishes clamp→trunc (this contract) from trunc→clamp: input 2.4 + // with min 2.5 → clamp lifts to 2.5, then trunc → 2. A trunc-first impl + // would floor to 2 then clamp up to 2.5. Pins the order for the shared + // primitive (future callers may use fractional bounds). + expect(clampInt(2.4, 2.5, 10, 0)).toBe(2); + }); - it('falls back on non-finite input', () => { - expect(clampInt('abc', 0, 10, 4)).toBe(4); - expect(clampInt(NaN, 0, 10, 4)).toBe(4); - expect(clampInt(undefined, 0, 10, 4)).toBe(4); - }); + it('falls back on non-finite input', () => { + expect(clampInt('abc', 0, 10, 4)).toBe(4); + expect(clampInt(NaN, 0, 10, 4)).toBe(4); + expect(clampInt(undefined, 0, 10, 4)).toBe(4); + }); }); diff --git a/packages/common/tests/concurrency.test.ts b/packages/common/tests/concurrency.test.ts index 8706cac3..df707bc7 100644 --- a/packages/common/tests/concurrency.test.ts +++ b/packages/common/tests/concurrency.test.ts @@ -4,65 +4,78 @@ import { mapWithConcurrency } from '../src/concurrency'; const tick = () => new Promise((r) => setTimeout(r, 0)); describe('mapWithConcurrency', () => { - it('returns results in input order', async () => { - const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10); - expect(out).toEqual([10, 20, 30, 40, 50]); - }); - - it('passes the absolute index (across batch boundaries)', async () => { - const seen: Array<[number, number]> = []; - await mapWithConcurrency(['a', 'b', 'c', 'd', 'e'], 2, async (item, i) => { - seen.push([i, item.charCodeAt(0)]); - return i; + it('returns results in input order', async () => { + const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10); + expect(out).toEqual([10, 20, 30, 40, 50]); }); - expect(seen.map(([i]) => i).sort((x, y) => x - y)).toEqual([0, 1, 2, 3, 4]); - }); - it('never runs more than `concurrency` at once (batched), and serializes across batches', async () => { - let inFlight = 0; - let peak = 0; - const order: number[] = []; - await mapWithConcurrency([0, 1, 2, 3, 4, 5, 6], 3, async (n) => { - inFlight++; - peak = Math.max(peak, inFlight); - await tick(); - order.push(n); - inFlight--; - return n; + it('passes the absolute index (across batch boundaries)', async () => { + const seen: Array<[number, number]> = []; + await mapWithConcurrency(['a', 'b', 'c', 'd', 'e'], 2, async (item, i) => { + seen.push([i, item.charCodeAt(0)]); + return i; + }); + expect(seen.map(([i]) => i).sort((x, y) => x - y)).toEqual([0, 1, 2, 3, 4]); }); - expect(peak).toBeLessThanOrEqual(3); - // batched: first 3 (0,1,2) settle before the next batch (3,4,5) starts. - expect(order.slice(0, 3).sort((a, b) => a - b)).toEqual([0, 1, 2]); - expect(order.slice(3, 6).sort((a, b) => a - b)).toEqual([3, 4, 5]); - expect(order[6]).toBe(6); - }); - it('handles a length not divisible by concurrency (short final batch)', async () => { - const out = await mapWithConcurrency([1, 2, 3, 4, 5], 3, async (n) => n); - expect(out).toEqual([1, 2, 3, 4, 5]); - }); - - it('runs everything in one batch when concurrency >= length', async () => { - let peak = 0, inFlight = 0; - const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => { - inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n; + it('never runs more than `concurrency` at once (batched), and serializes across batches', async () => { + let inFlight = 0; + let peak = 0; + const order: number[] = []; + await mapWithConcurrency([0, 1, 2, 3, 4, 5, 6], 3, async (n) => { + inFlight++; + peak = Math.max(peak, inFlight); + await tick(); + order.push(n); + inFlight--; + return n; + }); + expect(peak).toBeLessThanOrEqual(3); + // batched: first 3 (0,1,2) settle before the next batch (3,4,5) starts. + expect(order.slice(0, 3).sort((a, b) => a - b)).toEqual([0, 1, 2]); + expect(order.slice(3, 6).sort((a, b) => a - b)).toEqual([3, 4, 5]); + expect(order[6]).toBe(6); }); - expect(out).toEqual([1, 2, 3]); - expect(peak).toBe(3); - }); - it('returns [] for an empty input without calling fn', async () => { - let called = 0; - const out = await mapWithConcurrency([], 4, async (n) => { called++; return n; }); - expect(out).toEqual([]); - expect(called).toBe(0); - }); - - it('treats concurrency < 1 as 1 (fully serial)', async () => { - let peak = 0, inFlight = 0; - await mapWithConcurrency([1, 2, 3], 0, async (n) => { - inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n; + it('handles a length not divisible by concurrency (short final batch)', async () => { + const out = await mapWithConcurrency([1, 2, 3, 4, 5], 3, async (n) => n); + expect(out).toEqual([1, 2, 3, 4, 5]); + }); + + it('runs everything in one batch when concurrency >= length', async () => { + let peak = 0, + inFlight = 0; + const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => { + inFlight++; + peak = Math.max(peak, inFlight); + await tick(); + inFlight--; + return n; + }); + expect(out).toEqual([1, 2, 3]); + expect(peak).toBe(3); + }); + + it('returns [] for an empty input without calling fn', async () => { + let called = 0; + const out = await mapWithConcurrency([], 4, async (n) => { + called++; + return n; + }); + expect(out).toEqual([]); + expect(called).toBe(0); + }); + + it('treats concurrency < 1 as 1 (fully serial)', async () => { + let peak = 0, + inFlight = 0; + await mapWithConcurrency([1, 2, 3], 0, async (n) => { + inFlight++; + peak = Math.max(peak, inFlight); + await tick(); + inFlight--; + return n; + }); + expect(peak).toBe(1); }); - expect(peak).toBe(1); - }); }); diff --git a/packages/common/tests/env.test.ts b/packages/common/tests/env.test.ts index 3b296f13..300a467d 100644 --- a/packages/common/tests/env.test.ts +++ b/packages/common/tests/env.test.ts @@ -2,25 +2,33 @@ import { describe, expect, it } from 'vitest'; import { positiveIntEnv } from '../src/env'; describe('positiveIntEnv', () => { - it('returns the fallback when the variable is absent or blank', () => { - expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15); - expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(15); - }); + it('returns the fallback when the variable is absent or blank', () => { + expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15); + expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe( + 15, + ); + }); - it('reads a positive integer and honors the max', () => { - expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } })).toBe(2500); - expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { - max: 65535, - env: { SNOWLUMA_TEST_INT: '80' }, - })).toBe(80); - }); + it('reads a positive integer and honors the max', () => { + expect( + positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } }), + ).toBe(2500); + expect( + positiveIntEnv('SNOWLUMA_TEST_INT', 15, { + max: 65535, + env: { SNOWLUMA_TEST_INT: '80' }, + }), + ).toBe(80); + }); - it('ignores zero, negatives, fractions, and values above the max', () => { - for (const raw of ['0', '-5', '1.5', 'nope', '70000']) { - expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { - max: 65535, - env: { SNOWLUMA_TEST_INT: raw }, - })).toBe(15); - } - }); + it('ignores zero, negatives, fractions, and values above the max', () => { + for (const raw of ['0', '-5', '1.5', 'nope', '70000']) { + expect( + positiveIntEnv('SNOWLUMA_TEST_INT', 15, { + max: 65535, + env: { SNOWLUMA_TEST_INT: raw }, + }), + ).toBe(15); + } + }); }); diff --git a/packages/common/tests/hex.test.ts b/packages/common/tests/hex.test.ts index 4125b22c..49ad7cd0 100644 --- a/packages/common/tests/hex.test.ts +++ b/packages/common/tests/hex.test.ts @@ -2,25 +2,25 @@ import { describe, expect, it } from 'vitest'; import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex'; describe('hex', () => { - it('toHex / toHexUpper render bytes as zero-padded hex', () => { - const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]); - expect(toHex(b)).toBe('000fa0ff'); - expect(toHexUpper(b)).toBe('000FA0FF'); - expect(toHex(Uint8Array.of())).toBe(''); - }); + it('toHex / toHexUpper render bytes as zero-padded hex', () => { + const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]); + expect(toHex(b)).toBe('000fa0ff'); + expect(toHexUpper(b)).toBe('000FA0FF'); + expect(toHex(Uint8Array.of())).toBe(''); + }); - it('hexPreview appends "..." only past maxBytes', () => { - const b = Uint8Array.from([1, 2, 3, 4, 5]); - expect(hexPreview(b)).toBe('0102030405'); // under the default 64-byte cap - expect(hexPreview(b, 5)).toBe('0102030405'); // exactly at the cap → no ellipsis - expect(hexPreview(b, 2)).toBe('0102...'); // truncated - expect(hexPreview(b, 0)).toBe('...'); // nothing shown, but bytes remain - }); + it('hexPreview appends "..." only past maxBytes', () => { + const b = Uint8Array.from([1, 2, 3, 4, 5]); + expect(hexPreview(b)).toBe('0102030405'); // under the default 64-byte cap + expect(hexPreview(b, 5)).toBe('0102030405'); // exactly at the cap → no ellipsis + expect(hexPreview(b, 2)).toBe('0102...'); // truncated + expect(hexPreview(b, 0)).toBe('...'); // nothing shown, but bytes remain + }); - it('fromHex round-trips toHex and rejects odd-length input', () => { - const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]); - expect(fromHex(toHex(b)).equals(b)).toBe(true); - expect(toHex(fromHex('00ffa0'))).toBe('00ffa0'); - expect(() => fromHex('abc')).toThrow(); - }); + it('fromHex round-trips toHex and rejects odd-length input', () => { + const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]); + expect(fromHex(toHex(b)).equals(b)).toBe(true); + expect(toHex(fromHex('00ffa0'))).toBe('00ffa0'); + expect(() => fromHex('abc')).toThrow(); + }); }); diff --git a/packages/common/tests/log-file-transport.test.ts b/packages/common/tests/log-file-transport.test.ts index 4ea2bd14..b6de1fc2 100644 --- a/packages/common/tests/log-file-transport.test.ts +++ b/packages/common/tests/log-file-transport.test.ts @@ -3,22 +3,22 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { - FileTransport, - _resetFileTransportForTesting, - clearManagedLogs, - configureFileTransport, - getFileTransport, - getLogStorageStatus, - type LogStoragePolicy, + FileTransport, + _resetFileTransportForTesting, + clearManagedLogs, + configureFileTransport, + getFileTransport, + getLogStorageStatus, + type LogStoragePolicy, } from '../src/log-file-transport'; const ENV_KEYS = [ - 'SNOWLUMA_LOG_FILE', - 'SNOWLUMA_LOG_DIR', - 'SNOWLUMA_LOG_MAX_MB', - 'SNOWLUMA_LOG_MAX_TOTAL_MB', - 'SNOWLUMA_LOG_RETAIN_DAYS', - 'SNOWLUMA_LOG_PER_UIN', + 'SNOWLUMA_LOG_FILE', + 'SNOWLUMA_LOG_DIR', + 'SNOWLUMA_LOG_MAX_MB', + 'SNOWLUMA_LOG_MAX_TOTAL_MB', + 'SNOWLUMA_LOG_RETAIN_DAYS', + 'SNOWLUMA_LOG_PER_UIN', ] as const; const savedEnv: Record = {}; @@ -27,1023 +27,1104 @@ const opened: FileTransport[] = []; let tmpDir: string; function setEnv(env: Partial>): void { - for (const [key, value] of Object.entries(env)) { - if (value === undefined) delete process.env[key]; - else process.env[key] = value; - } + for (const [key, value] of Object.entries(env)) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } } function createTransport(policy?: LogStoragePolicy): FileTransport { - const transport = new FileTransport(policy); - opened.push(transport); - return transport; + const transport = new FileTransport(policy); + opened.push(transport); + return transport; } function listLogFiles(dir: string): string[] { - return fs.readdirSync(dir).filter((name) => name.endsWith('.log')).sort(); + return fs + .readdirSync(dir) + .filter((name) => name.endsWith('.log')) + .sort(); } async function waitForLogFiles(dir: string, expected: string[]): Promise { - await vi.waitFor(() => { - expect(listLogFiles(dir)).toEqual(expected); - }); + await vi.waitFor(() => { + expect(listLogFiles(dir)).toEqual(expected); + }); } function silenceStderr(): ReturnType { - return vi.spyOn(process.stderr, 'write').mockImplementation(() => true); + return vi.spyOn(process.stderr, 'write').mockImplementation(() => true); } beforeEach(() => { - for (const key of ENV_KEYS) savedEnv[key] = process.env[key]; - tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-common-log-')); - setEnv({ - SNOWLUMA_LOG_DIR: tmpDir, - SNOWLUMA_LOG_FILE: '1', - SNOWLUMA_LOG_MAX_MB: '1', - SNOWLUMA_LOG_MAX_TOTAL_MB: '2', - SNOWLUMA_LOG_RETAIN_DAYS: '7', - SNOWLUMA_LOG_PER_UIN: '0', - }); + for (const key of ENV_KEYS) { + savedEnv[key] = process.env[key]; + } + + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-common-log-')); + setEnv({ + SNOWLUMA_LOG_DIR: tmpDir, + SNOWLUMA_LOG_FILE: '1', + SNOWLUMA_LOG_MAX_MB: '1', + SNOWLUMA_LOG_MAX_TOTAL_MB: '2', + SNOWLUMA_LOG_RETAIN_DAYS: '7', + SNOWLUMA_LOG_PER_UIN: '0', + }); }); afterEach(async () => { - await Promise.all(opened.splice(0).map((transport) => transport.close())); - await _resetFileTransportForTesting(); - for (const key of ENV_KEYS) { - if (savedEnv[key] === undefined) delete process.env[key]; - else process.env[key] = savedEnv[key]; - } - vi.useRealTimers(); - vi.restoreAllMocks(); - fs.rmSync(tmpDir, { recursive: true, force: true }); + await Promise.all(opened.splice(0).map((transport) => transport.close())); + await _resetFileTransportForTesting(); + + for (const key of ENV_KEYS) { + if (savedEnv[key] === undefined) { + delete process.env[key]; + } else { + process.env[key] = savedEnv[key]; + } + } + + vi.useRealTimers(); + vi.restoreAllMocks(); + fs.rmSync(tmpDir, { recursive: true, force: true }); }); describe('FileTransport environment and policy', () => { - it('uses the constructor policy for total size, retention, and per-UIN instead of env', () => { - setEnv({ - SNOWLUMA_LOG_MAX_TOTAL_MB: '8', - SNOWLUMA_LOG_RETAIN_DAYS: '14', - SNOWLUMA_LOG_PER_UIN: '0', - SNOWLUMA_LOG_FILE: '0', + it('uses the constructor policy for total size, retention, and per-UIN instead of env', () => { + setEnv({ + SNOWLUMA_LOG_MAX_TOTAL_MB: '8', + SNOWLUMA_LOG_RETAIN_DAYS: '14', + SNOWLUMA_LOG_PER_UIN: '0', + SNOWLUMA_LOG_FILE: '0', + }); + + expect( + createTransport({ + maxTotalMb: 3, + retainDays: 0, + perUinEnabled: true, + }).getStorageStatus(), + ).toEqual({ + state: 'disabled', + directory: tmpDir, + totalBytes: 0, + maxTotalBytes: 3_145_728, + retainDays: 0, + perUinEnabled: true, + fileCount: 0, + activeFileCount: 0, + droppedLines: 0, + }); }); - expect(createTransport({ - maxTotalMb: 3, - retainDays: 0, - perUinEnabled: true, - }).getStorageStatus()).toEqual({ - state: 'disabled', - directory: tmpDir, - totalBytes: 0, - maxTotalBytes: 3_145_728, - retainDays: 0, - perUinEnabled: true, - fileCount: 0, - activeFileCount: 0, - droppedLines: 0, - }); - }); + it('falls back to defaults when optional log env vars are blank', () => { + setEnv({ + SNOWLUMA_LOG_FILE: '0', + SNOWLUMA_LOG_MAX_MB: ' ', + SNOWLUMA_LOG_MAX_TOTAL_MB: '', + SNOWLUMA_LOG_RETAIN_DAYS: ' ', + SNOWLUMA_LOG_PER_UIN: '', + }); - it('falls back to defaults when optional log env vars are blank', () => { - setEnv({ - SNOWLUMA_LOG_FILE: '0', - SNOWLUMA_LOG_MAX_MB: ' ', - SNOWLUMA_LOG_MAX_TOTAL_MB: '', - SNOWLUMA_LOG_RETAIN_DAYS: ' ', - SNOWLUMA_LOG_PER_UIN: '', + expect(createTransport().getStorageStatus()).toMatchObject({ + state: 'disabled', + maxTotalBytes: 1_073_741_824, + retainDays: 7, + perUinEnabled: false, + }); }); - expect(createTransport().getStorageStatus()).toMatchObject({ - state: 'disabled', - maxTotalBytes: 1_073_741_824, - retainDays: 7, - perUinEnabled: false, + it('resolves an unset SNOWLUMA_LOG_DIR to the process-relative logs folder', () => { + setEnv({ SNOWLUMA_LOG_DIR: undefined, SNOWLUMA_LOG_FILE: '0' }); + + expect(createTransport().getStorageStatus().directory).toBe(path.resolve('logs')); }); - }); - it('resolves an unset SNOWLUMA_LOG_DIR to the process-relative logs folder', () => { - setEnv({ SNOWLUMA_LOG_DIR: undefined, SNOWLUMA_LOG_FILE: '0' }); + it('treats only the exact string 0 as a file-output disable switch', () => { + setEnv({ SNOWLUMA_LOG_FILE: 'false' }); + expect(createTransport().isDisabled).toBe(false); - expect(createTransport().getStorageStatus().directory).toBe(path.resolve('logs')); - }); + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + expect(createTransport().isDisabled).toBe(true); + }); - it('treats only the exact string 0 as a file-output disable switch', () => { - setEnv({ SNOWLUMA_LOG_FILE: 'false' }); - expect(createTransport().isDisabled).toBe(false); + it.each([ + ['1', true], + ['TRUE', true], + [' yes ', true], + ['On', true], + ['0', false], + ['FALSE', false], + [' no ', false], + ['Off', false], + ] as const)('parses SNOWLUMA_LOG_PER_UIN=%j as %s', (value, expected) => { + setEnv({ SNOWLUMA_LOG_PER_UIN: value, SNOWLUMA_LOG_FILE: '0' }); + expect(createTransport().getStorageStatus().perUinEnabled).toBe(expected); + }); - setEnv({ SNOWLUMA_LOG_FILE: '0' }); - expect(createTransport().isDisabled).toBe(true); - }); + it.each([ + ['0', 'SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591'], + ['1.5', 'SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591'], + ['abc', 'SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591'], + ] as const)('rejects SNOWLUMA_LOG_MAX_MB=%j', (value, message) => { + setEnv({ SNOWLUMA_LOG_MAX_MB: value }); + expect(() => new FileTransport()).toThrow(new RangeError(message)); + }); - it.each([ - ['1', true], - ['TRUE', true], - [' yes ', true], - ['On', true], - ['0', false], - ['FALSE', false], - [' no ', false], - ['Off', false], - ] as const)('parses SNOWLUMA_LOG_PER_UIN=%j as %s', (value, expected) => { - setEnv({ SNOWLUMA_LOG_PER_UIN: value, SNOWLUMA_LOG_FILE: '0' }); - expect(createTransport().getStorageStatus().perUinEnabled).toBe(expected); - }); + it('rejects invalid total-size, retain-day, and per-UIN environment values', () => { + setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '0' }); + expect(() => new FileTransport()).toThrow( + new RangeError('SNOWLUMA_LOG_MAX_TOTAL_MB must be an integer in 1..8589934591'), + ); - it.each([ - ['0', 'SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591'], - ['1.5', 'SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591'], - ['abc', 'SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591'], - ] as const)('rejects SNOWLUMA_LOG_MAX_MB=%j', (value, message) => { - setEnv({ SNOWLUMA_LOG_MAX_MB: value }); - expect(() => new FileTransport()).toThrow(new RangeError(message)); - }); + setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '2', SNOWLUMA_LOG_RETAIN_DAYS: '-1' }); + expect(() => new FileTransport()).toThrow( + new RangeError('SNOWLUMA_LOG_RETAIN_DAYS must be an integer in 0..104249991'), + ); - it('rejects invalid total-size, retain-day, and per-UIN environment values', () => { - setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '0' }); - expect(() => new FileTransport()).toThrow( - new RangeError('SNOWLUMA_LOG_MAX_TOTAL_MB must be an integer in 1..8589934591'), - ); + setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '7', SNOWLUMA_LOG_PER_UIN: 'maybe' }); + expect(() => new FileTransport()).toThrow( + new TypeError('SNOWLUMA_LOG_PER_UIN must be a boolean'), + ); + }); - setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '2', SNOWLUMA_LOG_RETAIN_DAYS: '-1' }); - expect(() => new FileTransport()).toThrow( - new RangeError('SNOWLUMA_LOG_RETAIN_DAYS must be an integer in 0..104249991'), - ); + it('still validates SNOWLUMA_LOG_MAX_MB when a storage policy is supplied', () => { + setEnv({ SNOWLUMA_LOG_MAX_MB: '0' }); + expect( + () => + new FileTransport({ + maxTotalMb: 2, + retainDays: 7, + perUinEnabled: false, + }), + ).toThrow(new RangeError('SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591')); + }); - setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '7', SNOWLUMA_LOG_PER_UIN: 'maybe' }); - expect(() => new FileTransport()).toThrow( - new TypeError('SNOWLUMA_LOG_PER_UIN must be a boolean'), - ); - }); - - it('still validates SNOWLUMA_LOG_MAX_MB when a storage policy is supplied', () => { - setEnv({ SNOWLUMA_LOG_MAX_MB: '0' }); - expect(() => new FileTransport({ - maxTotalMb: 2, - retainDays: 7, - perUinEnabled: false, - })).toThrow(new RangeError('SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591')); - }); - - it('rejects constructor policies before touching the log directory', () => { - expect(() => new FileTransport({ - maxTotalMb: 0, - retainDays: 7, - perUinEnabled: false, - })).toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591')); - expect(() => new FileTransport({ - maxTotalMb: 2, - retainDays: -1, - perUinEnabled: false, - })).toThrow(new RangeError('retainDays must be an integer in 0..104249991')); - expect(() => new FileTransport({ - maxTotalMb: 2, - retainDays: 7, - perUinEnabled: 'yes' as unknown as boolean, - })).toThrow(new TypeError('perUinEnabled must be a boolean')); - expect(fs.readdirSync(tmpDir)).toEqual([]); - }); + it('rejects constructor policies before touching the log directory', () => { + expect( + () => + new FileTransport({ + maxTotalMb: 0, + retainDays: 7, + perUinEnabled: false, + }), + ).toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591')); + expect( + () => + new FileTransport({ + maxTotalMb: 2, + retainDays: -1, + perUinEnabled: false, + }), + ).toThrow(new RangeError('retainDays must be an integer in 0..104249991')); + expect( + () => + new FileTransport({ + maxTotalMb: 2, + retainDays: 7, + perUinEnabled: 'yes' as unknown as boolean, + }), + ).toThrow(new TypeError('perUinEnabled must be a boolean')); + expect(fs.readdirSync(tmpDir)).toEqual([]); + }); }); describe('FileTransport write, rotation, and paths', () => { - it('creates today\'s shared file, appends a newline, and reports an exact healthy snapshot', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 15, 4, 5)); - const transport = createTransport(); + it("creates today's shared file, appends a newline, and reports an exact healthy snapshot", async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 15, 4, 5)); + const transport = createTransport(); - expect(transport.isDisabled).toBe(false); - expect(transport.currentPath).toBeNull(); - expect(transport.perUinPath(12345)).toBeNull(); + expect(transport.isDisabled).toBe(false); + expect(transport.currentPath).toBeNull(); + expect(transport.perUinPath(12345)).toBeNull(); - transport.write('hello'); + transport.write('hello'); - const activePath = path.join(tmpDir, 'snowluma-2026-07-24.log'); - expect(transport.currentPath).toBe(activePath); - expect(transport.getStorageStatus()).toEqual({ - state: 'healthy', - directory: tmpDir, - totalBytes: 6, - maxTotalBytes: 2_097_152, - retainDays: 7, - perUinEnabled: false, - fileCount: 1, - activeFileCount: 1, - droppedLines: 0, + const activePath = path.join(tmpDir, 'snowluma-2026-07-24.log'); + expect(transport.currentPath).toBe(activePath); + expect(transport.getStorageStatus()).toEqual({ + state: 'healthy', + directory: tmpDir, + totalBytes: 6, + maxTotalBytes: 2_097_152, + retainDays: 7, + perUinEnabled: false, + fileCount: 1, + activeFileCount: 1, + droppedLines: 0, + }); + + await transport.close(); + expect(transport.isDisabled).toBe(true); + expect(transport.currentPath).toBeNull(); + expect(transport.getStorageStatus()).toMatchObject({ + state: 'healthy', + fileCount: 1, + activeFileCount: 0, + }); + expect(fs.readFileSync(activePath, 'utf8')).toBe('hello\n'); }); - await transport.close(); - expect(transport.isDisabled).toBe(true); - expect(transport.currentPath).toBeNull(); - expect(transport.getStorageStatus()).toMatchObject({ - state: 'healthy', - fileCount: 1, - activeFileCount: 0, + it('sanitizes control sequences and counts UTF-8 bytes including the trailing newline', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + const transport = createTransport(); + transport.write('\x1b[31m你好\x1b[0m'); + await transport.close(); + + const filePath = path.join(tmpDir, 'snowluma-2026-07-24.log'); + expect(fs.readFileSync(filePath, 'utf8')).toBe('你好\n'); + expect(fs.statSync(filePath).size).toBe(7); }); - expect(fs.readFileSync(activePath, 'utf8')).toBe('hello\n'); - }); - it('sanitizes control sequences and counts UTF-8 bytes including the trailing newline', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - const transport = createTransport(); - transport.write('\x1b[31m你好\x1b[0m'); - await transport.close(); + it('does not write when file output is disabled', async () => { + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + const transport = createTransport(); + transport.write('should not persist'); + await transport.close(); - const filePath = path.join(tmpDir, 'snowluma-2026-07-24.log'); - expect(fs.readFileSync(filePath, 'utf8')).toBe('你好\n'); - expect(fs.statSync(filePath).size).toBe(7); - }); + expect(transport.isDisabled).toBe(true); + expect(listLogFiles(tmpDir)).toEqual([]); + }); - it('does not write when file output is disabled', async () => { - setEnv({ SNOWLUMA_LOG_FILE: '0' }); - const transport = createTransport(); - transport.write('should not persist'); - await transport.close(); + it('appends to the existing today file and tracks the on-disk size after a restart', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), '0123456789'); - expect(transport.isDisabled).toBe(true); - expect(listLogFiles(tmpDir)).toEqual([]); - }); + const first = createTransport(); + first.write('hello'); + expect(first.getStorageStatus().totalBytes).toBe(16); + await first.close(); - it('appends to the existing today file and tracks the on-disk size after a restart', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), '0123456789'); + const second = createTransport(); + second.write('z'); + await second.close(); - const first = createTransport(); - first.write('hello'); - expect(first.getStorageStatus().totalBytes).toBe(16); - await first.close(); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe( + '0123456789hello\nz\n', + ); + }); - const second = createTransport(); - second.write('z'); - await second.close(); + it('resumes the highest existing split index for the current day', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'base\n'); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'one\n'); - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')) - .toBe('0123456789hello\nz\n'); - }); + const transport = createTransport(); + transport.write('two'); + await transport.close(); - it('resumes the highest existing split index for the current day', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'base\n'); - fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'one\n'); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe( + 'base\n', + ); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'utf8')).toBe( + 'one\ntwo\n', + ); + }); - const transport = createTransport(); - transport.write('two'); - await transport.close(); + it('skips an already-present next split when rotating by size', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + // Leave the base file just under the 1 MiB cap so the first write opens + // split 0. ensureForToday resumes at the highest existing split, so + // planting `.1` before that open would append there instead of rotating. + fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), Buffer.alloc(1_048_570)); - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe('base\n'); - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'utf8')).toBe('one\ntwo\n'); - }); + const transport = createTransport(); + transport.write('open'); + await waitForLogFiles(tmpDir, ['snowluma-2026-07-24.log']); + expect(transport.currentPath).toBe(path.join(tmpDir, 'snowluma-2026-07-24.log')); - it('skips an already-present next split when rotating by size', async () => { - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - // Leave the base file just under the 1 MiB cap so the first write opens - // split 0. ensureForToday resumes at the highest existing split, so - // planting `.1` before that open would append there instead of rotating. - fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), Buffer.alloc(1_048_570)); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'taken\n'); + transport.write('overflow'); + await transport.close(); - const transport = createTransport(); - transport.write('open'); - await waitForLogFiles(tmpDir, ['snowluma-2026-07-24.log']); - expect(transport.currentPath).toBe(path.join(tmpDir, 'snowluma-2026-07-24.log')); + expect(listLogFiles(tmpDir)).toEqual([ + 'snowluma-2026-07-24.1.log', + 'snowluma-2026-07-24.2.log', + 'snowluma-2026-07-24.log', + ]); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.2.log'), 'utf8')).toBe( + 'overflow\n', + ); + }); - fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'taken\n'); - transport.write('overflow'); - await transport.close(); + it('lets a first line exceed the per-file cap and only rotates on the next write', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + const transport = createTransport(); + const oversized = 'a'.repeat(1_048_580); + transport.write(oversized); + await waitForLogFiles(tmpDir, ['snowluma-2026-07-24.log']); - expect(listLogFiles(tmpDir)).toEqual([ - 'snowluma-2026-07-24.1.log', - 'snowluma-2026-07-24.2.log', - 'snowluma-2026-07-24.log', - ]); - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.2.log'), 'utf8')) - .toBe('overflow\n'); - }); + transport.write('b'); + await transport.close(); - it('lets a first line exceed the per-file cap and only rotates on the next write', async () => { - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - const transport = createTransport(); - const oversized = 'a'.repeat(1_048_580); - transport.write(oversized); - await waitForLogFiles(tmpDir, ['snowluma-2026-07-24.log']); + expect(listLogFiles(tmpDir)).toEqual([ + 'snowluma-2026-07-24.1.log', + 'snowluma-2026-07-24.log', + ]); + expect(fs.statSync(path.join(tmpDir, 'snowluma-2026-07-24.log')).size).toBe(1_048_581); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'utf8')).toBe('b\n'); + }); - transport.write('b'); - await transport.close(); + it('opens a new dated file when the calendar day changes', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 4, 18, 23, 59, 0)); + const transport = createTransport(); + transport.write('day-one'); + vi.setSystemTime(new Date(2026, 4, 19, 0, 0, 1)); + transport.write('day-two'); + await transport.close(); - expect(listLogFiles(tmpDir)).toEqual([ - 'snowluma-2026-07-24.1.log', - 'snowluma-2026-07-24.log', - ]); - expect(fs.statSync(path.join(tmpDir, 'snowluma-2026-07-24.log')).size).toBe(1_048_581); - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'utf8')).toBe('b\n'); - }); - - it('opens a new dated file when the calendar day changes', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 4, 18, 23, 59, 0)); - const transport = createTransport(); - transport.write('day-one'); - vi.setSystemTime(new Date(2026, 4, 19, 0, 0, 1)); - transport.write('day-two'); - await transport.close(); - - expect(listLogFiles(tmpDir)).toEqual([ - 'snowluma-2026-05-18.log', - 'snowluma-2026-05-19.log', - ]); - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-18.log'), 'utf8')).toBe('day-one\n'); - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-19.log'), 'utf8')).toBe('day-two\n'); - }); + expect(listLogFiles(tmpDir)).toEqual([ + 'snowluma-2026-05-18.log', + 'snowluma-2026-05-19.log', + ]); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-18.log'), 'utf8')).toBe( + 'day-one\n', + ); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-19.log'), 'utf8')).toBe( + 'day-two\n', + ); + }); }); describe('FileTransport retention, listing, and quota', () => { - it('deletes expired managed files in the root and numeric account directories only', async () => { - fs.writeFileSync(path.join(tmpDir, 'keep.txt'), 'keep\n'); - fs.writeFileSync(path.join(tmpDir, 'snowluma-nope.log'), 'unmanaged\n'); - fs.mkdirSync(path.join(tmpDir, 'not-an-account')); - fs.writeFileSync( - path.join(tmpDir, 'not-an-account', 'snowluma-2020-01-01.log'), - 'ignored\n', - ); - fs.mkdirSync(path.join(tmpDir, '10001')); - fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'stale-root\n'); - fs.writeFileSync(path.join(tmpDir, '10001', 'snowluma-2020-01-01.2.log'), 'stale-account\n'); + it('deletes expired managed files in the root and numeric account directories only', async () => { + fs.writeFileSync(path.join(tmpDir, 'keep.txt'), 'keep\n'); + fs.writeFileSync(path.join(tmpDir, 'snowluma-nope.log'), 'unmanaged\n'); + fs.mkdirSync(path.join(tmpDir, 'not-an-account')); + fs.writeFileSync( + path.join(tmpDir, 'not-an-account', 'snowluma-2020-01-01.log'), + 'ignored\n', + ); + fs.mkdirSync(path.join(tmpDir, '10001')); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'stale-root\n'); + fs.writeFileSync( + path.join(tmpDir, '10001', 'snowluma-2020-01-01.2.log'), + 'stale-account\n', + ); - const transport = createTransport(); - await transport.close(); + const transport = createTransport(); + await transport.close(); - expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); - expect(fs.existsSync(path.join(tmpDir, '10001', 'snowluma-2020-01-01.2.log'))).toBe(false); - expect(fs.readFileSync(path.join(tmpDir, 'keep.txt'), 'utf8')).toBe('keep\n'); - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-nope.log'), 'utf8')).toBe('unmanaged\n'); - expect(fs.readFileSync( - path.join(tmpDir, 'not-an-account', 'snowluma-2020-01-01.log'), - 'utf8', - )).toBe('ignored\n'); - }); - - it('keeps files inside the retention window and skips date cleanup when retainDays is 0', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - const recentPath = path.join(tmpDir, 'snowluma-2026-07-22.log'); - const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log'); - fs.writeFileSync(recentPath, 'recent\n'); - fs.writeFileSync(stalePath, 'stale\n'); - - const kept = createTransport(); - await kept.close(); - expect(fs.existsSync(recentPath)).toBe(true); - expect(fs.existsSync(stalePath)).toBe(false); - - fs.writeFileSync(stalePath, 'stale-again\n'); - setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '0' }); - const noDateCleanup = createTransport(); - await noDateCleanup.close(); - expect(fs.existsSync(stalePath)).toBe(true); - expect(noDateCleanup.getStorageStatus().retainDays).toBe(0); - }); - - it('runs retention again after the active writer closes', async () => { - const transport = createTransport(); - transport.write('keep the writer open'); - const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log'); - fs.writeFileSync(stalePath, 'stale\n'); - expect(fs.existsSync(stalePath)).toBe(true); - - await transport.close(); - expect(fs.existsSync(stalePath)).toBe(false); - }); - - it('never deletes the active file when a later retention policy makes its date stale', async () => { - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(new Date(2026, 0, 1, 12, 0, 0)); - const activePath = path.join(tmpDir, 'snowluma-2026-01-01.log'); - const transport = createTransport(); - transport.write('still-active'); - await vi.waitFor(() => { - expect(fs.existsSync(activePath)).toBe(true); + expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); + expect(fs.existsSync(path.join(tmpDir, '10001', 'snowluma-2020-01-01.2.log'))).toBe(false); + expect(fs.readFileSync(path.join(tmpDir, 'keep.txt'), 'utf8')).toBe('keep\n'); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-nope.log'), 'utf8')).toBe('unmanaged\n'); + expect( + fs.readFileSync(path.join(tmpDir, 'not-an-account', 'snowluma-2020-01-01.log'), 'utf8'), + ).toBe('ignored\n'); }); - vi.setSystemTime(new Date(2026, 0, 3, 12, 0, 0)); - await transport.updatePolicy({ - maxTotalMb: 2, - retainDays: 1, - perUinEnabled: false, + it('keeps files inside the retention window and skips date cleanup when retainDays is 0', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + const recentPath = path.join(tmpDir, 'snowluma-2026-07-22.log'); + const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log'); + fs.writeFileSync(recentPath, 'recent\n'); + fs.writeFileSync(stalePath, 'stale\n'); + + const kept = createTransport(); + await kept.close(); + expect(fs.existsSync(recentPath)).toBe(true); + expect(fs.existsSync(stalePath)).toBe(false); + + fs.writeFileSync(stalePath, 'stale-again\n'); + setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '0' }); + const noDateCleanup = createTransport(); + await noDateCleanup.close(); + expect(fs.existsSync(stalePath)).toBe(true); + expect(noDateCleanup.getStorageStatus().retainDays).toBe(0); }); - expect(fs.existsSync(activePath)).toBe(true); - expect(transport.getStorageStatus().activeFileCount).toBe(1); - }); + it('runs retention again after the active writer closes', async () => { + const transport = createTransport(); + transport.write('keep the writer open'); + const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log'); + fs.writeFileSync(stalePath, 'stale\n'); + expect(fs.existsSync(stalePath)).toBe(true); - it('reclaims the oldest closed files first when applying a lower aggregate limit', async () => { - setEnv({ - SNOWLUMA_LOG_MAX_TOTAL_MB: '4', - SNOWLUMA_LOG_RETAIN_DAYS: '0', + await transport.close(); + expect(fs.existsSync(stalePath)).toBe(false); }); - const older = path.join(tmpDir, 'snowluma-2026-07-24.log'); - const accountDir = path.join(tmpDir, '12345'); - const newer = path.join(accountDir, 'snowluma-2026-07-24.log'); - fs.mkdirSync(accountDir); - fs.writeFileSync(older, Buffer.alloc(700 * 1024)); - fs.writeFileSync(newer, Buffer.alloc(700 * 1024)); - fs.utimesSync(older, new Date('2026-07-24T01:00:00Z'), new Date('2026-07-24T01:00:00Z')); - fs.utimesSync(newer, new Date('2026-07-24T02:00:00Z'), new Date('2026-07-24T02:00:00Z')); - const transport = createTransport(); - expect(await transport.updatePolicy({ - maxTotalMb: 1, - retainDays: 0, - perUinEnabled: false, - })).toMatchObject({ - state: 'healthy', - maxTotalBytes: 1_048_576, - totalBytes: 716_800, - fileCount: 1, + it('never deletes the active file when a later retention policy makes its date stale', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(2026, 0, 1, 12, 0, 0)); + const activePath = path.join(tmpDir, 'snowluma-2026-01-01.log'); + const transport = createTransport(); + transport.write('still-active'); + await vi.waitFor(() => { + expect(fs.existsSync(activePath)).toBe(true); + }); + + vi.setSystemTime(new Date(2026, 0, 3, 12, 0, 0)); + await transport.updatePolicy({ + maxTotalMb: 2, + retainDays: 1, + perUinEnabled: false, + }); + + expect(fs.existsSync(activePath)).toBe(true); + expect(transport.getStorageStatus().activeFileCount).toBe(1); }); - expect(fs.existsSync(older)).toBe(false); - expect(fs.existsSync(newer)).toBe(true); - }); - it('enters one degraded quota state and counts later lines as dropped', async () => { - setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '1' }); - const stderr = silenceStderr(); - const transport = createTransport(); - const kib = 'x'.repeat(1023); - for (let i = 0; i < 1024; i += 1) transport.write(kib); - for (let i = 0; i < 10; i += 1) transport.write('dropped'); + it('reclaims the oldest closed files first when applying a lower aggregate limit', async () => { + setEnv({ + SNOWLUMA_LOG_MAX_TOTAL_MB: '4', + SNOWLUMA_LOG_RETAIN_DAYS: '0', + }); + const older = path.join(tmpDir, 'snowluma-2026-07-24.log'); + const accountDir = path.join(tmpDir, '12345'); + const newer = path.join(accountDir, 'snowluma-2026-07-24.log'); + fs.mkdirSync(accountDir); + fs.writeFileSync(older, Buffer.alloc(700 * 1024)); + fs.writeFileSync(newer, Buffer.alloc(700 * 1024)); + fs.utimesSync(older, new Date('2026-07-24T01:00:00Z'), new Date('2026-07-24T01:00:00Z')); + fs.utimesSync(newer, new Date('2026-07-24T02:00:00Z'), new Date('2026-07-24T02:00:00Z')); - expect(transport.getStorageStatus()).toMatchObject({ - state: 'degraded', - maxTotalBytes: 1_048_576, - droppedLines: 10, + const transport = createTransport(); + expect( + await transport.updatePolicy({ + maxTotalMb: 1, + retainDays: 0, + perUinEnabled: false, + }), + ).toMatchObject({ + state: 'healthy', + maxTotalBytes: 1_048_576, + totalBytes: 716_800, + fileCount: 1, + }); + expect(fs.existsSync(older)).toBe(false); + expect(fs.existsSync(newer)).toBe(true); }); - expect( - stderr.mock.calls - .map(([message]) => String(message)) - .filter((message) => message.includes('no closed log can be reclaimed')), - ).toHaveLength(1); - expect(stderr.mock.calls[0]![0]).toMatch(/^\[logger\.storage] /); - }); - it('does not fan out a dropped shared line to a per-UIN writer', async () => { - setEnv({ - SNOWLUMA_LOG_MAX_TOTAL_MB: '1', - SNOWLUMA_LOG_PER_UIN: '1', + it('enters one degraded quota state and counts later lines as dropped', async () => { + setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '1' }); + const stderr = silenceStderr(); + const transport = createTransport(); + const kib = 'x'.repeat(1023); + + for (let i = 0; i < 1024; i += 1) { + transport.write(kib); + } + + for (let i = 0; i < 10; i += 1) { + transport.write('dropped'); + } + + expect(transport.getStorageStatus()).toMatchObject({ + state: 'degraded', + maxTotalBytes: 1_048_576, + droppedLines: 10, + }); + expect( + stderr.mock.calls + .map(([message]) => String(message)) + .filter((message) => message.includes('no closed log can be reclaimed')), + ).toHaveLength(1); + expect(stderr.mock.calls[0]![0]).toMatch(/^\[logger\.storage] /); }); - silenceStderr(); - const transport = createTransport(); - const kib = 'x'.repeat(1023); - for (let i = 0; i < 1024; i += 1) transport.write(kib); - transport.write('overflow', 12345); - expect(transport.perUinPath(12345)).toBeNull(); - expect(fs.existsSync(path.join(tmpDir, '12345'))).toBe(false); - expect(transport.getStorageStatus().droppedLines).toBe(1); - }); + it('does not fan out a dropped shared line to a per-UIN writer', async () => { + setEnv({ + SNOWLUMA_LOG_MAX_TOTAL_MB: '1', + SNOWLUMA_LOG_PER_UIN: '1', + }); + silenceStderr(); + const transport = createTransport(); + const kib = 'x'.repeat(1023); - it('reports a warning when retention cannot unlink an expired closed file', async () => { - const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log'); - fs.writeFileSync(stalePath, 'stale\n'); - const realUnlink = fs.unlinkSync.bind(fs); - vi.spyOn(fs, 'unlinkSync').mockImplementation((filePath) => { - if (path.resolve(String(filePath)) === stalePath) { - throw new Error('permission denied'); - } - realUnlink(filePath); + for (let i = 0; i < 1024; i += 1) { + transport.write(kib); + } + + transport.write('overflow', 12345); + + expect(transport.perUinPath(12345)).toBeNull(); + expect(fs.existsSync(path.join(tmpDir, '12345'))).toBe(false); + expect(transport.getStorageStatus().droppedLines).toBe(1); }); - silenceStderr(); - const transport = createTransport(); - expect(transport.getStorageStatus()).toMatchObject({ - state: 'warning', - lastError: `retention cleanup failed for ${stalePath}: permission denied`, - fileCount: 1, + it('reports a warning when retention cannot unlink an expired closed file', async () => { + const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log'); + fs.writeFileSync(stalePath, 'stale\n'); + const realUnlink = fs.unlinkSync.bind(fs); + vi.spyOn(fs, 'unlinkSync').mockImplementation((filePath) => { + if (path.resolve(String(filePath)) === stalePath) { + throw new Error('permission denied'); + } + + realUnlink(filePath); + }); + silenceStderr(); + + const transport = createTransport(); + expect(transport.getStorageStatus()).toMatchObject({ + state: 'warning', + lastError: `retention cleanup failed for ${stalePath}: permission denied`, + fileCount: 1, + }); + expect(fs.existsSync(stalePath)).toBe(true); }); - expect(fs.existsSync(stalePath)).toBe(true); - }); }); describe('FileTransport per-UIN writers', () => { - it('duplicates a UIN-scoped line into logs// and leaves unscoped lines in the shared file only', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); - const transport = createTransport(); - transport.write('shared-only'); - transport.write('both', 12345); - await transport.close(); + it('duplicates a UIN-scoped line into logs// and leaves unscoped lines in the shared file only', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + const transport = createTransport(); + transport.write('shared-only'); + transport.write('both', 12345); + await transport.close(); - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')) - .toBe('shared-only\nboth\n'); - expect(fs.readFileSync(path.join(tmpDir, '12345', 'snowluma-2026-07-24.log'), 'utf8')) - .toBe('both\n'); - }); - - it('does not create an account directory when the account path is already a file', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); - fs.writeFileSync(path.join(tmpDir, '12345'), 'occupied'); - silenceStderr(); - const transport = createTransport(); - transport.write('shared-ok', 12345); - await transport.close(); - - expect(transport.perUinPath(12345)).toBeNull(); - expect(fs.statSync(path.join(tmpDir, '12345')).isFile()).toBe(true); - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe('shared-ok\n'); - }); - - it('rolls per-UIN files on day change and stops creating them after the policy turns off', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 23, 59, 0)); - setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); - const transport = createTransport(); - transport.write('day-one', 99); - expect(transport.perUinPath(99)).toBe(path.join(tmpDir, '99', 'snowluma-2026-07-24.log')); - - const updating = transport.updatePolicy({ - maxTotalMb: 2, - retainDays: 7, - perUinEnabled: false, + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe( + 'shared-only\nboth\n', + ); + expect(fs.readFileSync(path.join(tmpDir, '12345', 'snowluma-2026-07-24.log'), 'utf8')).toBe( + 'both\n', + ); }); - transport.write('during-disable', 99); - expect(transport.perUinPath(99)).toBeNull(); - await updating; - vi.setSystemTime(new Date(2026, 6, 25, 0, 0, 1)); - transport.write('day-two', 99); - await transport.close(); + it('does not create an account directory when the account path is already a file', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + fs.writeFileSync(path.join(tmpDir, '12345'), 'occupied'); + silenceStderr(); + const transport = createTransport(); + transport.write('shared-ok', 12345); + await transport.close(); - expect(fs.existsSync(path.join(tmpDir, '99', 'snowluma-2026-07-25.log'))).toBe(false); - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-25.log'), 'utf8')) - .toBe('day-two\n'); - expect(transport.getStorageStatus().perUinEnabled).toBe(false); - }); - - it('creates account writers only after a policy enables per-UIN output', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - const transport = createTransport(); - transport.write('before', 55); - expect(fs.existsSync(path.join(tmpDir, '55'))).toBe(false); - - await transport.updatePolicy({ - maxTotalMb: 2, - retainDays: 7, - perUinEnabled: true, + expect(transport.perUinPath(12345)).toBeNull(); + expect(fs.statSync(path.join(tmpDir, '12345')).isFile()).toBe(true); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe( + 'shared-ok\n', + ); }); - transport.write('after', 55); - await transport.close(); - expect(fs.readFileSync(path.join(tmpDir, '55', 'snowluma-2026-07-24.log'), 'utf8')) - .toBe('after\n'); - }); + it('rolls per-UIN files on day change and stops creating them after the policy turns off', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 23, 59, 0)); + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + const transport = createTransport(); + transport.write('day-one', 99); + expect(transport.perUinPath(99)).toBe(path.join(tmpDir, '99', 'snowluma-2026-07-24.log')); - it('replaces a disabled per-UIN writer on the next line for that account', async () => { - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); - const realCreate = fs.createWriteStream.bind(fs); - const accountStreams: fs.WriteStream[] = []; - vi.spyOn(fs, 'createWriteStream').mockImplementation((file, options) => { - const stream = realCreate(file, options); - if (String(file).startsWith(path.join(tmpDir, '77') + path.sep)) { - accountStreams.push(stream); - } - return stream; + const updating = transport.updatePolicy({ + maxTotalMb: 2, + retainDays: 7, + perUinEnabled: false, + }); + transport.write('during-disable', 99); + expect(transport.perUinPath(99)).toBeNull(); + await updating; + + vi.setSystemTime(new Date(2026, 6, 25, 0, 0, 1)); + transport.write('day-two', 99); + await transport.close(); + + expect(fs.existsSync(path.join(tmpDir, '99', 'snowluma-2026-07-25.log'))).toBe(false); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-25.log'), 'utf8')).toBe( + 'day-two\n', + ); + expect(transport.getStorageStatus().perUinEnabled).toBe(false); }); - silenceStderr(); - const transport = createTransport(); - transport.write('one', 77); - const accountFile = path.join(tmpDir, '77', 'snowluma-2026-07-24.log'); - await vi.waitFor(() => { - expect(fs.readFileSync(accountFile, 'utf8')).toBe('one\n'); + it('creates account writers only after a policy enables per-UIN output', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + const transport = createTransport(); + transport.write('before', 55); + expect(fs.existsSync(path.join(tmpDir, '55'))).toBe(false); + + await transport.updatePolicy({ + maxTotalMb: 2, + retainDays: 7, + perUinEnabled: true, + }); + transport.write('after', 55); + await transport.close(); + + expect(fs.readFileSync(path.join(tmpDir, '55', 'snowluma-2026-07-24.log'), 'utf8')).toBe( + 'after\n', + ); }); - accountStreams[0]!.emit('error', Object.assign(new Error('account eio'), { code: 'EIO' })); - vi.setSystemTime(Date.now() + 5_000); - transport.write('two', 77); - await transport.close(); - expect(fs.readFileSync(accountFile, 'utf8')).toBe('one\ntwo\n'); - }); + it('replaces a disabled per-UIN writer on the next line for that account', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + const realCreate = fs.createWriteStream.bind(fs); + const accountStreams: fs.WriteStream[] = []; + vi.spyOn(fs, 'createWriteStream').mockImplementation((file, options) => { + const stream = realCreate(file, options); + + if (String(file).startsWith(path.join(tmpDir, '77') + path.sep)) { + accountStreams.push(stream); + } + + return stream; + }); + silenceStderr(); + + const transport = createTransport(); + transport.write('one', 77); + const accountFile = path.join(tmpDir, '77', 'snowluma-2026-07-24.log'); + await vi.waitFor(() => { + expect(fs.readFileSync(accountFile, 'utf8')).toBe('one\n'); + }); + accountStreams[0]!.emit('error', Object.assign(new Error('account eio'), { code: 'EIO' })); + vi.setSystemTime(Date.now() + 5_000); + transport.write('two', 77); + await transport.close(); + + expect(fs.readFileSync(accountFile, 'utf8')).toBe('one\ntwo\n'); + }); }); describe('FileTransport initialization, recovery, and policy updates', () => { - it('surfaces a failed log-root mkdir as a disabled status with lastError', async () => { - const blocked = path.join(tmpDir, 'blocked-root'); - fs.writeFileSync(blocked, 'occupied'); - setEnv({ SNOWLUMA_LOG_DIR: blocked }); - const stderr = silenceStderr(); + it('surfaces a failed log-root mkdir as a disabled status with lastError', async () => { + const blocked = path.join(tmpDir, 'blocked-root'); + fs.writeFileSync(blocked, 'occupied'); + setEnv({ SNOWLUMA_LOG_DIR: blocked }); + const stderr = silenceStderr(); - const transport = createTransport(); - expect(transport.isDisabled).toBe(true); - expect(transport.getStorageStatus()).toMatchObject({ - state: 'disabled', - directory: blocked, - totalBytes: 0, - fileCount: 0, - droppedLines: 0, - }); - expect(transport.getStorageStatus().lastError) - .toMatch(/^failed to initialize log storage /); - expect(String(stderr.mock.calls[0]![0])).toContain('[logger.storage]'); - await transport.close(); - }); - - it('treats a non-ENOENT readdir of an account directory as an initialization failure', async () => { - fs.mkdirSync(path.join(tmpDir, '12345')); - const realReaddir = fs.readdirSync.bind(fs); - vi.spyOn(fs, 'readdirSync').mockImplementation((dir, options) => { - if (path.resolve(String(dir)) === path.join(tmpDir, '12345')) { - throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }); - } - return realReaddir(dir, options as Parameters[1]); - }); - silenceStderr(); - - const transport = createTransport(); - expect(transport.getStorageStatus()).toMatchObject({ - state: 'disabled', - lastError: expect.stringContaining('failed to read managed log directory'), - }); - }); - - it('retries a failed shared-writer open after the 5s backoff', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - silenceStderr(); - vi.spyOn(fs, 'createWriteStream').mockImplementationOnce(() => { - throw Object.assign(new Error('open failed'), { code: 'EIO' }); + const transport = createTransport(); + expect(transport.isDisabled).toBe(true); + expect(transport.getStorageStatus()).toMatchObject({ + state: 'disabled', + directory: blocked, + totalBytes: 0, + fileCount: 0, + droppedLines: 0, + }); + expect(transport.getStorageStatus().lastError).toMatch( + /^failed to initialize log storage /, + ); + expect(String(stderr.mock.calls[0]![0])).toContain('[logger.storage]'); + await transport.close(); }); - const transport = createTransport(); - transport.write('dropped-while-opening'); - expect(transport.getStorageStatus().state).toBe('degraded'); - expect(listLogFiles(tmpDir)).toEqual([]); + it('treats a non-ENOENT readdir of an account directory as an initialization failure', async () => { + fs.mkdirSync(path.join(tmpDir, '12345')); + const realReaddir = fs.readdirSync.bind(fs); + vi.spyOn(fs, 'readdirSync').mockImplementation((dir, options) => { + if (path.resolve(String(dir)) === path.join(tmpDir, '12345')) { + throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }); + } - vi.advanceTimersByTime(4_999); - transport.write('still-waiting'); - expect(listLogFiles(tmpDir)).toEqual([]); + return realReaddir(dir, options as Parameters[1]); + }); + silenceStderr(); - vi.advanceTimersByTime(1); - transport.write('recovered'); - await transport.close(); - - expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')) - .toBe('recovered\n'); - }); - - it('does not persist lines during the quota retry window after a stream error', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - silenceStderr(); - const realCreate = fs.createWriteStream.bind(fs); - const streams: fs.WriteStream[] = []; - vi.spyOn(fs, 'createWriteStream').mockImplementation((file, options) => { - const stream = realCreate(file, options); - streams.push(stream); - return stream; + const transport = createTransport(); + expect(transport.getStorageStatus()).toMatchObject({ + state: 'disabled', + lastError: expect.stringContaining('failed to read managed log directory'), + }); }); - const transport = createTransport(); - transport.write('before-error'); - streams[0]!.emit('error', Object.assign(new Error('EIO write'), { code: 'EIO' })); - expect(transport.getStorageStatus().state).toBe('degraded'); + it('retries a failed shared-writer open after the 5s backoff', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + silenceStderr(); + vi.spyOn(fs, 'createWriteStream').mockImplementationOnce(() => { + throw Object.assign(new Error('open failed'), { code: 'EIO' }); + }); - transport.write('during-backoff'); - expect(transport.getStorageStatus().droppedLines).toBe(1); + const transport = createTransport(); + transport.write('dropped-while-opening'); + expect(transport.getStorageStatus().state).toBe('degraded'); + expect(listLogFiles(tmpDir)).toEqual([]); - vi.advanceTimersByTime(5_000); - transport.write('after-backoff'); - await transport.close(); + vi.advanceTimersByTime(4_999); + transport.write('still-waiting'); + expect(listLogFiles(tmpDir)).toEqual([]); - const body = fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8'); - expect(body).toContain('after-backoff\n'); - expect(body).not.toContain('during-backoff'); - }); + vi.advanceTimersByTime(1); + transport.write('recovered'); + await transport.close(); - it('recovers a previously unwritable root when updatePolicy forces a reopen', async () => { - const blocked = path.join(tmpDir, 'blocked-root'); - fs.writeFileSync(blocked, 'occupied'); - setEnv({ SNOWLUMA_LOG_DIR: blocked }); - silenceStderr(); - const transport = createTransport(); - expect(transport.getStorageStatus().state).toBe('disabled'); - - fs.unlinkSync(blocked); - fs.mkdirSync(blocked); - const status = await transport.updatePolicy({ - maxTotalMb: 2, - retainDays: 3, - perUinEnabled: false, + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe( + 'recovered\n', + ); }); - expect(status).toMatchObject({ - state: 'healthy', - directory: blocked, - maxTotalBytes: 2_097_152, - retainDays: 3, - }); - transport.write('via-policy'); - await transport.close(); - expect(listLogFiles(blocked)).toHaveLength(1); - }); + it('does not persist lines during the quota retry window after a stream error', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + silenceStderr(); + const realCreate = fs.createWriteStream.bind(fs); + const streams: fs.WriteStream[] = []; + vi.spyOn(fs, 'createWriteStream').mockImplementation((file, options) => { + const stream = realCreate(file, options); + streams.push(stream); + return stream; + }); - it('updates stored policy fields even when applying the quota policy throws', async () => { - const transport = createTransport(); - vi.spyOn(fs, 'readdirSync').mockImplementation(() => { - throw Object.assign(new Error('EIO readdir'), { code: 'EIO' }); - }); - silenceStderr(); + const transport = createTransport(); + transport.write('before-error'); + streams[0]!.emit('error', Object.assign(new Error('EIO write'), { code: 'EIO' })); + expect(transport.getStorageStatus().state).toBe('degraded'); - await expect(transport.updatePolicy({ - maxTotalMb: 4, - retainDays: 1, - perUinEnabled: true, - })).rejects.toThrow(/failed to read managed log directory/); + transport.write('during-backoff'); + expect(transport.getStorageStatus().droppedLines).toBe(1); - expect(transport.getStorageStatus()).toMatchObject({ - state: 'degraded', - maxTotalBytes: 4_194_304, - retainDays: 1, - perUinEnabled: true, - lastError: expect.stringContaining('failed to apply log storage policy'), - }); - }); + vi.advanceTimersByTime(5_000); + transport.write('after-backoff'); + await transport.close(); - it('applies a policy to a disabled transport without creating files', async () => { - setEnv({ SNOWLUMA_LOG_FILE: '0' }); - const transport = createTransport(); - const status = await transport.updatePolicy({ - maxTotalMb: 5, - retainDays: 2, - perUinEnabled: true, + const body = fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8'); + expect(body).toContain('after-backoff\n'); + expect(body).not.toContain('during-backoff'); }); - expect(status).toEqual({ - state: 'disabled', - directory: tmpDir, - totalBytes: 0, - maxTotalBytes: 5_242_880, - retainDays: 2, - perUinEnabled: true, - fileCount: 0, - activeFileCount: 0, - droppedLines: 0, - }); - expect(listLogFiles(tmpDir)).toEqual([]); - }); + it('recovers a previously unwritable root when updatePolicy forces a reopen', async () => { + const blocked = path.join(tmpDir, 'blocked-root'); + fs.writeFileSync(blocked, 'occupied'); + setEnv({ SNOWLUMA_LOG_DIR: blocked }); + silenceStderr(); + const transport = createTransport(); + expect(transport.getStorageStatus().state).toBe('disabled'); - it('rejects an unsafe updatePolicy without changing the live limits', async () => { - const transport = createTransport(); - await expect(transport.updatePolicy({ - maxTotalMb: 9_007_199_254_740_991, - retainDays: 7, - perUinEnabled: false, - })).rejects.toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591')); - await expect(transport.updatePolicy({ - maxTotalMb: 2, - retainDays: 9_007_199_254_740_991, - perUinEnabled: false, - })).rejects.toThrow(new RangeError('retainDays must be an integer in 0..104249991')); - expect(transport.getStorageStatus()).toMatchObject({ - maxTotalBytes: 2_097_152, - retainDays: 7, + fs.unlinkSync(blocked); + fs.mkdirSync(blocked); + const status = await transport.updatePolicy({ + maxTotalMb: 2, + retainDays: 3, + perUinEnabled: false, + }); + + expect(status).toMatchObject({ + state: 'healthy', + directory: blocked, + maxTotalBytes: 2_097_152, + retainDays: 3, + }); + transport.write('via-policy'); + await transport.close(); + expect(listLogFiles(blocked)).toHaveLength(1); + }); + + it('updates stored policy fields even when applying the quota policy throws', async () => { + const transport = createTransport(); + vi.spyOn(fs, 'readdirSync').mockImplementation(() => { + throw Object.assign(new Error('EIO readdir'), { code: 'EIO' }); + }); + silenceStderr(); + + await expect( + transport.updatePolicy({ + maxTotalMb: 4, + retainDays: 1, + perUinEnabled: true, + }), + ).rejects.toThrow(/failed to read managed log directory/); + + expect(transport.getStorageStatus()).toMatchObject({ + state: 'degraded', + maxTotalBytes: 4_194_304, + retainDays: 1, + perUinEnabled: true, + lastError: expect.stringContaining('failed to apply log storage policy'), + }); + }); + + it('applies a policy to a disabled transport without creating files', async () => { + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + const transport = createTransport(); + const status = await transport.updatePolicy({ + maxTotalMb: 5, + retainDays: 2, + perUinEnabled: true, + }); + + expect(status).toEqual({ + state: 'disabled', + directory: tmpDir, + totalBytes: 0, + maxTotalBytes: 5_242_880, + retainDays: 2, + perUinEnabled: true, + fileCount: 0, + activeFileCount: 0, + droppedLines: 0, + }); + expect(listLogFiles(tmpDir)).toEqual([]); + }); + + it('rejects an unsafe updatePolicy without changing the live limits', async () => { + const transport = createTransport(); + await expect( + transport.updatePolicy({ + maxTotalMb: 9_007_199_254_740_991, + retainDays: 7, + perUinEnabled: false, + }), + ).rejects.toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591')); + await expect( + transport.updatePolicy({ + maxTotalMb: 2, + retainDays: 9_007_199_254_740_991, + perUinEnabled: false, + }), + ).rejects.toThrow(new RangeError('retainDays must be an integer in 0..104249991')); + expect(transport.getStorageStatus()).toMatchObject({ + maxTotalBytes: 2_097_152, + retainDays: 7, + }); }); - }); }); describe('FileTransport.clearManagedLogs', () => { - it('deletes closed shared and account files and reopens empty writers', async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); - setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); - const transport = createTransport(); - transport.write('shared and account', 12345); + it('deletes closed shared and account files and reopens empty writers', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + const transport = createTransport(); + transport.write('shared and account', 12345); - const result = await transport.clearManagedLogs(); + const result = await transport.clearManagedLogs(); - expect(result.deletedFiles).toBe(2); - expect(result.freedBytes).toBeGreaterThan(0); - expect(result.failures).toEqual([]); - expect(fs.statSync(transport.currentPath!).size).toBe(0); - expect(fs.statSync(transport.perUinPath(12345)!).size).toBe(0); - expect(result.status.activeFileCount).toBe(2); - }); - - it('clears managed files while file output is disabled and leaves unrelated files', async () => { - fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'managed\n'); - fs.writeFileSync(path.join(tmpDir, 'keep.txt'), 'unrelated\n'); - setEnv({ SNOWLUMA_LOG_FILE: '0' }); - const transport = createTransport(); - - expect(await transport.clearManagedLogs()).toEqual({ - deletedFiles: 1, - freedBytes: 8, - failures: [], - status: { - state: 'disabled', - directory: tmpDir, - totalBytes: 0, - maxTotalBytes: 2_097_152, - retainDays: 7, - perUinEnabled: false, - fileCount: 0, - activeFileCount: 0, - droppedLines: 0, - }, + expect(result.deletedFiles).toBe(2); + expect(result.freedBytes).toBeGreaterThan(0); + expect(result.failures).toEqual([]); + expect(fs.statSync(transport.currentPath!).size).toBe(0); + expect(fs.statSync(transport.perUinPath(12345)!).size).toBe(0); + expect(result.status.activeFileCount).toBe(2); }); - expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); - expect(fs.readFileSync(path.join(tmpDir, 'keep.txt'), 'utf8')).toBe('unrelated\n'); - }); - it('reports a disabled clear failure when the log root cannot be read', async () => { - const blocked = path.join(tmpDir, 'not-a-dir'); - fs.writeFileSync(blocked, 'occupied'); - setEnv({ SNOWLUMA_LOG_DIR: blocked, SNOWLUMA_LOG_FILE: '0' }); - silenceStderr(); - const transport = createTransport(); + it('clears managed files while file output is disabled and leaves unrelated files', async () => { + fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'managed\n'); + fs.writeFileSync(path.join(tmpDir, 'keep.txt'), 'unrelated\n'); + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + const transport = createTransport(); - const result = await transport.clearManagedLogs(); - expect(result.deletedFiles).toBe(0); - expect(result.freedBytes).toBe(0); - expect(result.failures).toEqual([{ - file: '.', - message: expect.stringContaining(`failed to clear disabled log storage ${blocked}`), - }]); - expect(result.status).toMatchObject({ - state: 'disabled', - directory: blocked, - lastError: result.failures[0]!.message, + expect(await transport.clearManagedLogs()).toEqual({ + deletedFiles: 1, + freedBytes: 8, + failures: [], + status: { + state: 'disabled', + directory: tmpDir, + totalBytes: 0, + maxTotalBytes: 2_097_152, + retainDays: 7, + perUinEnabled: false, + fileCount: 0, + activeFileCount: 0, + droppedLines: 0, + }, + }); + expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); + expect(fs.readFileSync(path.join(tmpDir, 'keep.txt'), 'utf8')).toBe('unrelated\n'); }); - }); - it('can clear and reopen writers before the failed-open retry delay expires', async () => { - silenceStderr(); - vi.spyOn(fs, 'createWriteStream').mockImplementationOnce(() => { - throw Object.assign(new Error('open failed'), { code: 'EIO' }); + it('reports a disabled clear failure when the log root cannot be read', async () => { + const blocked = path.join(tmpDir, 'not-a-dir'); + fs.writeFileSync(blocked, 'occupied'); + setEnv({ SNOWLUMA_LOG_DIR: blocked, SNOWLUMA_LOG_FILE: '0' }); + silenceStderr(); + const transport = createTransport(); + + const result = await transport.clearManagedLogs(); + expect(result.deletedFiles).toBe(0); + expect(result.freedBytes).toBe(0); + expect(result.failures).toEqual([ + { + file: '.', + message: expect.stringContaining(`failed to clear disabled log storage ${blocked}`), + }, + ]); + expect(result.status).toMatchObject({ + state: 'disabled', + directory: blocked, + lastError: result.failures[0]!.message, + }); }); - const transport = createTransport(); - transport.write('dropped-while-opening'); - fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'stale\n'); - const result = await transport.clearManagedLogs(); + it('can clear and reopen writers before the failed-open retry delay expires', async () => { + silenceStderr(); + vi.spyOn(fs, 'createWriteStream').mockImplementationOnce(() => { + throw Object.assign(new Error('open failed'), { code: 'EIO' }); + }); + const transport = createTransport(); + transport.write('dropped-while-opening'); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'stale\n'); - expect(result.failures).toEqual([]); - expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); - expect(transport.currentPath).not.toBeNull(); - }); + const result = await transport.clearManagedLogs(); - it('records a shared reopen failure after a successful cleanup', async () => { - const transport = createTransport(); - transport.write('to-clear'); - vi.spyOn(fs, 'createWriteStream').mockImplementation(() => { - throw Object.assign(new Error('reopen failed'), { code: 'EIO' }); + expect(result.failures).toEqual([]); + expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); + expect(transport.currentPath).not.toBeNull(); }); - silenceStderr(); - const result = await transport.clearManagedLogs(); - expect(result.deletedFiles).toBe(1); - expect(result.failures).toEqual([{ - file: '.', - message: expect.stringMatching(/^failed to initialize log storage /), - }]); - expect(transport.currentPath).toBeNull(); - }); + it('records a shared reopen failure after a successful cleanup', async () => { + const transport = createTransport(); + transport.write('to-clear'); + vi.spyOn(fs, 'createWriteStream').mockImplementation(() => { + throw Object.assign(new Error('reopen failed'), { code: 'EIO' }); + }); + silenceStderr(); - it('records an account reopen failure without losing the shared writer', async () => { - setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); - const transport = createTransport(); - transport.write('both', 12345); - const realCreate = fs.createWriteStream.bind(fs); - const accountPrefix = path.join(tmpDir, '12345') + path.sep; - vi.spyOn(fs, 'createWriteStream').mockImplementation((file, options) => { - if (String(file).startsWith(accountPrefix)) { - throw new Error('account reopen failed'); - } - return realCreate(file, options); + const result = await transport.clearManagedLogs(); + expect(result.deletedFiles).toBe(1); + expect(result.failures).toEqual([ + { + file: '.', + message: expect.stringMatching(/^failed to initialize log storage /), + }, + ]); + expect(transport.currentPath).toBeNull(); }); - silenceStderr(); - const result = await transport.clearManagedLogs(); - expect(result.failures).toEqual([{ - file: '12345', - message: `failed to reopen account log writer: failed to prepare log writer in ${path.join(tmpDir, '12345')}`, - }]); - expect(transport.currentPath).not.toBeNull(); - expect(transport.perUinPath(12345)).toBeNull(); - }); + it('records an account reopen failure without losing the shared writer', async () => { + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + const transport = createTransport(); + transport.write('both', 12345); + const realCreate = fs.createWriteStream.bind(fs); + const accountPrefix = path.join(tmpDir, '12345') + path.sep; + vi.spyOn(fs, 'createWriteStream').mockImplementation((file, options) => { + if (String(file).startsWith(accountPrefix)) { + throw new Error('account reopen failed'); + } - it('returns the initialization error when a disabled root still cannot build a quota', async () => { - const blocked = path.join(tmpDir, 'blocked-root'); - fs.writeFileSync(blocked, 'occupied'); - setEnv({ SNOWLUMA_LOG_DIR: blocked }); - silenceStderr(); - const transport = createTransport(); + return realCreate(file, options); + }); + silenceStderr(); - const result = await transport.clearManagedLogs(); - expect(result).toMatchObject({ - deletedFiles: 0, - freedBytes: 0, - failures: [{ - file: '.', - message: expect.stringMatching(/^failed to initialize log storage /), - }], - status: { state: 'disabled', directory: blocked }, + const result = await transport.clearManagedLogs(); + expect(result.failures).toEqual([ + { + file: '12345', + message: `failed to reopen account log writer: failed to prepare log writer in ${path.join(tmpDir, '12345')}`, + }, + ]); + expect(transport.currentPath).not.toBeNull(); + expect(transport.perUinPath(12345)).toBeNull(); + }); + + it('returns the initialization error when a disabled root still cannot build a quota', async () => { + const blocked = path.join(tmpDir, 'blocked-root'); + fs.writeFileSync(blocked, 'occupied'); + setEnv({ SNOWLUMA_LOG_DIR: blocked }); + silenceStderr(); + const transport = createTransport(); + + const result = await transport.clearManagedLogs(); + expect(result).toMatchObject({ + deletedFiles: 0, + freedBytes: 0, + failures: [ + { + file: '.', + message: expect.stringMatching(/^failed to initialize log storage /), + }, + ], + status: { state: 'disabled', directory: blocked }, + }); }); - }); }); describe('file-transport singleton', () => { - it('reuses one FileTransport until _resetFileTransportForTesting closes it', async () => { - const first = getFileTransport(); - expect(getFileTransport()).toBe(first); - first.write('singleton-line'); + it('reuses one FileTransport until _resetFileTransportForTesting closes it', async () => { + const first = getFileTransport(); + expect(getFileTransport()).toBe(first); + first.write('singleton-line'); - await _resetFileTransportForTesting(); - const second = getFileTransport(); - expect(second).not.toBe(first); - expect(first.isDisabled).toBe(true); - expect(second.isDisabled).toBe(false); - }); - - it('configureFileTransport creates the singleton with a copied policy', async () => { - const policy: LogStoragePolicy = { - maxTotalMb: 3, - retainDays: 1, - perUinEnabled: true, - }; - const status = await configureFileTransport(policy); - policy.retainDays = 9; - policy.perUinEnabled = false; - - expect(status).toMatchObject({ - maxTotalBytes: 3_145_728, - retainDays: 1, - perUinEnabled: true, - }); - expect(getFileTransport().getStorageStatus()).toMatchObject({ - retainDays: 1, - perUinEnabled: true, - }); - expect(getLogStorageStatus()).toEqual(getFileTransport().getStorageStatus()); - }); - - it('configureFileTransport updates the existing singleton and rejects invalid policies first', async () => { - const created = getFileTransport(); - const updated = await configureFileTransport({ - maxTotalMb: 5, - retainDays: 2, - perUinEnabled: true, - }); - expect(getFileTransport()).toBe(created); - expect(updated).toMatchObject({ - maxTotalBytes: 5_242_880, - retainDays: 2, - perUinEnabled: true, + await _resetFileTransportForTesting(); + const second = getFileTransport(); + expect(second).not.toBe(first); + expect(first.isDisabled).toBe(true); + expect(second.isDisabled).toBe(false); }); - await expect(configureFileTransport({ - maxTotalMb: 0, - retainDays: 2, - perUinEnabled: true, - })).rejects.toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591')); - expect(getLogStorageStatus().maxTotalBytes).toBe(5_242_880); - }); + it('configureFileTransport creates the singleton with a copied policy', async () => { + const policy: LogStoragePolicy = { + maxTotalMb: 3, + retainDays: 1, + perUinEnabled: true, + }; + const status = await configureFileTransport(policy); + policy.retainDays = 9; + policy.perUinEnabled = false; - it('forgets a configured policy after reset so the next singleton reads env', async () => { - await configureFileTransport({ - maxTotalMb: 3, - retainDays: 1, - perUinEnabled: true, + expect(status).toMatchObject({ + maxTotalBytes: 3_145_728, + retainDays: 1, + perUinEnabled: true, + }); + expect(getFileTransport().getStorageStatus()).toMatchObject({ + retainDays: 1, + perUinEnabled: true, + }); + expect(getLogStorageStatus()).toEqual(getFileTransport().getStorageStatus()); }); - expect(getLogStorageStatus().retainDays).toBe(1); - await _resetFileTransportForTesting(); - expect(getLogStorageStatus()).toMatchObject({ - maxTotalBytes: 2_097_152, - retainDays: 7, - perUinEnabled: false, + it('configureFileTransport updates the existing singleton and rejects invalid policies first', async () => { + const created = getFileTransport(); + const updated = await configureFileTransport({ + maxTotalMb: 5, + retainDays: 2, + perUinEnabled: true, + }); + expect(getFileTransport()).toBe(created); + expect(updated).toMatchObject({ + maxTotalBytes: 5_242_880, + retainDays: 2, + perUinEnabled: true, + }); + + await expect( + configureFileTransport({ + maxTotalMb: 0, + retainDays: 2, + perUinEnabled: true, + }), + ).rejects.toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591')); + expect(getLogStorageStatus().maxTotalBytes).toBe(5_242_880); }); - }); - it('clearManagedLogs delegates to the singleton', async () => { - setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '0' }); - fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'stale\n'); - getFileTransport(); + it('forgets a configured policy after reset so the next singleton reads env', async () => { + await configureFileTransport({ + maxTotalMb: 3, + retainDays: 1, + perUinEnabled: true, + }); + expect(getLogStorageStatus().retainDays).toBe(1); - const result = await clearManagedLogs(); - expect(result.deletedFiles).toBe(1); - expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); - expect(result.status.directory).toBe(tmpDir); - }); + await _resetFileTransportForTesting(); + expect(getLogStorageStatus()).toMatchObject({ + maxTotalBytes: 2_097_152, + retainDays: 7, + perUinEnabled: false, + }); + }); - it('is a no-op reset when no singleton was created', async () => { - await expect(_resetFileTransportForTesting()).resolves.toBeUndefined(); - await expect(_resetFileTransportForTesting()).resolves.toBeUndefined(); - }); + it('clearManagedLogs delegates to the singleton', async () => { + setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '0' }); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'stale\n'); + getFileTransport(); + + const result = await clearManagedLogs(); + expect(result.deletedFiles).toBe(1); + expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); + expect(result.status.directory).toBe(tmpDir); + }); + + it('is a no-op reset when no singleton was created', async () => { + await expect(_resetFileTransportForTesting()).resolves.toBeUndefined(); + await expect(_resetFileTransportForTesting()).resolves.toBeUndefined(); + }); }); diff --git a/packages/common/tests/log-sanitize.test.ts b/packages/common/tests/log-sanitize.test.ts index bee296d6..c0d71bcb 100644 --- a/packages/common/tests/log-sanitize.test.ts +++ b/packages/common/tests/log-sanitize.test.ts @@ -2,25 +2,25 @@ import { describe, expect, it } from 'vitest'; import { sanitizeLogLine } from '../src/log-sanitize'; describe('sanitizeLogLine', () => { - it('removes SGR styling in seven-bit and eight-bit forms', () => { - expect(sanitizeLogLine('\x1b[31mred\x1b[0m / \u009b32mgreen\u009b0m')).toBe('red / green'); - }); + it('removes SGR styling in seven-bit and eight-bit forms', () => { + expect(sanitizeLogLine('\x1b[31mred\x1b[0m / \u009b32mgreen\u009b0m')).toBe('red / green'); + }); - it('removes OSC hyperlinks without removing their visible label', () => { - expect( - sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07'), - ).toBe('visible'); - }); + it('removes OSC hyperlinks without removing their visible label', () => { + expect(sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07')).toBe( + 'visible', + ); + }); - it('removes terminal control-string payloads', () => { - expect(sanitizeLogLine('before\x1bPprivate payload\x1b\\after')).toBe('beforeafter'); - }); + it('removes terminal control-string payloads', () => { + expect(sanitizeLogLine('before\x1bPprivate payload\x1b\\after')).toBe('beforeafter'); + }); - it('preserves tabs and newlines while removing other controls', () => { - expect(sanitizeLogLine('one\ttwo\nthree\r\x00')).toBe('one\ttwo\nthree'); - }); + it('preserves tabs and newlines while removing other controls', () => { + expect(sanitizeLogLine('one\ttwo\nthree\r\x00')).toBe('one\ttwo\nthree'); + }); - it('does not leak unterminated terminal strings', () => { - expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible'); - }); + it('does not leak unterminated terminal strings', () => { + expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible'); + }); }); diff --git a/packages/common/tests/log-summary.test.ts b/packages/common/tests/log-summary.test.ts index 702ff2ca..7fb99832 100644 --- a/packages/common/tests/log-summary.test.ts +++ b/packages/common/tests/log-summary.test.ts @@ -1,234 +1,230 @@ import { describe, expect, it } from 'vitest'; -import { - redactLogMessage, - renderParamsVerbose, - summarizeParams, -} from '../src/log-summary'; +import { redactLogMessage, renderParamsVerbose, summarizeParams } from '../src/log-summary'; describe('summarizeParams', () => { - it('renders null/undefined as {}', () => { - expect(summarizeParams(null)).toBe('{}'); - expect(summarizeParams(undefined)).toBe('{}'); - }); - - it('renders a top-level non-object via String() WITHOUT quotes', () => { - // The reported change-request: a top-level primitive is NOT JSON-quoted. - expect(summarizeParams('hello')).toBe('hello'); - expect(summarizeParams(123)).toBe('123'); - }); - - it('collapses a top-level array to [len=N]', () => { - expect(summarizeParams([1, 2, 3])).toBe('[len=3]'); - }); - - it('quotes string fields, collapses nested values, truncates long strings', () => { - expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] })) - .toBe('a=1 b="x" c={...} e=[len=2]'); - expect(summarizeParams({ s: 'x'.repeat(50) })) - .toBe(`s="${'x'.repeat(40)}..."`); - }); - - it('redacts authentication fields without exposing their values', () => { - const out = summarizeParams({ - token: 'token-value', - Cookie: 'cookie-value', - Authorization: 'Bearer authorization-value', - user_password: 'password-value', - apiKey: 'key-value', - group_id: 12345, + it('renders null/undefined as {}', () => { + expect(summarizeParams(null)).toBe('{}'); + expect(summarizeParams(undefined)).toBe('{}'); }); - expect(out).toContain('token="***"'); - expect(out).toContain('Cookie="***"'); - expect(out).toContain('Authorization="***"'); - expect(out).toContain('user_password="***"'); - expect(out).toContain('apiKey="***"'); - expect(out).toContain('group_id=12345'); - expect(out).not.toMatch( - /token-value|cookie-value|authorization-value|password-value|key-value/, - ); - }); + it('renders a top-level non-object via String() WITHOUT quotes', () => { + // The reported change-request: a top-level primitive is NOT JSON-quoted. + expect(summarizeParams('hello')).toBe('hello'); + expect(summarizeParams(123)).toBe('123'); + }); - it('does not treat sensitive substrings inside ordinary keys as credentials', () => { - expect(summarizeParams({ - retoken: 'visible', - cookietown: 'visible', - myauthorization: 'visible', - })).toBe( - 'retoken="visible" cookietown="visible" myauthorization="visible"', - ); - }); + it('collapses a top-level array to [len=N]', () => { + expect(summarizeParams([1, 2, 3])).toBe('[len=3]'); + }); - it('caps total output and appends "..." on overflow', () => { - const big: Record = {}; - for (let i = 0; i < 60; i++) big['key' + i] = i; - const out = summarizeParams(big); - expect(out.startsWith('key0=0')).toBe(true); - expect(out.endsWith('...')).toBe(true); - expect(out.length).toBeLessThanOrEqual(200); - }); + it('quotes string fields, collapses nested values, truncates long strings', () => { + expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] })).toBe( + 'a=1 b="x" c={...} e=[len=2]', + ); + expect(summarizeParams({ s: 'x'.repeat(50) })).toBe(`s="${'x'.repeat(40)}..."`); + }); - it('caps a single oversized first key and top-level primitive', () => { - const oversizedKey = 'k'.repeat(300); + it('redacts authentication fields without exposing their values', () => { + const out = summarizeParams({ + token: 'token-value', + Cookie: 'cookie-value', + Authorization: 'Bearer authorization-value', + user_password: 'password-value', + apiKey: 'key-value', + group_id: 12345, + }); - const objectOut = summarizeParams({ [oversizedKey]: 'value' }); - const primitiveOut = summarizeParams('x'.repeat(300)); + expect(out).toContain('token="***"'); + expect(out).toContain('Cookie="***"'); + expect(out).toContain('Authorization="***"'); + expect(out).toContain('user_password="***"'); + expect(out).toContain('apiKey="***"'); + expect(out).toContain('group_id=12345'); + expect(out).not.toMatch( + /token-value|cookie-value|authorization-value|password-value|key-value/, + ); + }); - expect(objectOut).toHaveLength(200); - expect(objectOut.endsWith('...')).toBe(true); - expect(primitiveOut).toHaveLength(200); - expect(primitiveOut.endsWith('...')).toBe(true); - }); + it('does not treat sensitive substrings inside ordinary keys as credentials', () => { + expect( + summarizeParams({ + retoken: 'visible', + cookietown: 'visible', + myauthorization: 'visible', + }), + ).toBe('retoken="visible" cookietown="visible" myauthorization="visible"'); + }); + + it('caps total output and appends "..." on overflow', () => { + const big: Record = {}; + + for (let i = 0; i < 60; i++) { + big['key' + i] = i; + } + + const out = summarizeParams(big); + expect(out.startsWith('key0=0')).toBe(true); + expect(out.endsWith('...')).toBe(true); + expect(out.length).toBeLessThanOrEqual(200); + }); + + it('caps a single oversized first key and top-level primitive', () => { + const oversizedKey = 'k'.repeat(300); + + const objectOut = summarizeParams({ [oversizedKey]: 'value' }); + const primitiveOut = summarizeParams('x'.repeat(300)); + + expect(objectOut).toHaveLength(200); + expect(objectOut.endsWith('...')).toBe(true); + expect(primitiveOut).toHaveLength(200); + expect(primitiveOut.endsWith('...')).toBe(true); + }); }); describe('redactLogMessage', () => { - it('redacts explicit authentication assignments without changing prose', () => { - const out = redactLogMessage( - 'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required', - ); + it('redacts explicit authentication assignments without changing prose', () => { + const out = redactLogMessage( + 'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required', + ); - expect(out).toBe( - 'password=*** Authorization: *** cookie=*** password change required', - ); - }); + expect(out).toBe('password=*** Authorization: *** cookie=*** password change required'); + }); - it('redacts quoted object keys, Basic auth, and complete Cookie values', () => { - const out = redactLogMessage( - `json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`, - ); - const expires = redactLogMessage( - 'Cookie=session=expires-secret; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Path=/; HttpOnly safe=visible', - ); + it('redacts quoted object keys, Basic auth, and complete Cookie values', () => { + const out = redactLogMessage( + `json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`, + ); + const expires = redactLogMessage( + 'Cookie=session=expires-secret; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Path=/; HttpOnly safe=visible', + ); - expect(out).toContain('json={"authorization":***}'); - expect(out).toContain("object={ 'api-key': *** }"); - expect(out).toContain('Authorization: *** Cookie=***'); - expect(expires).toBe('Cookie=*** safe=visible'); - expect(out).not.toMatch(/json-auth|api-secret|header-auth|cookie-secret|Path=|HttpOnly/); - expect(expires).not.toMatch(/expires-secret|Expires|21 Oct|Path=|HttpOnly/); - }); + expect(out).toContain('json={"authorization":***}'); + expect(out).toContain("object={ 'api-key': *** }"); + expect(out).toContain('Authorization: *** Cookie=***'); + expect(expires).toBe('Cookie=*** safe=visible'); + expect(out).not.toMatch(/json-auth|api-secret|header-auth|cookie-secret|Path=|HttpOnly/); + expect(expires).not.toMatch(/expires-secret|Expires|21 Oct|Path=|HttpOnly/); + }); - it('redacts complete multi-parameter Authorization values', () => { - const out = redactLogMessage( - 'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n' - + 'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, ' - + 'SignedHeaders=host;x-date, Signature=aws-secret\n' - + 'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/', - ); + it('redacts complete multi-parameter Authorization values', () => { + const out = redactLogMessage( + 'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n' + + 'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, ' + + 'SignedHeaders=host;x-date, Signature=aws-secret\n' + + 'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/', + ); - expect(out).toBe( - 'Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***', - ); - expect(out).not.toMatch( - /alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/, - ); - }); + expect(out).toBe('Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***'); + expect(out).not.toMatch( + /alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/, + ); + }); - it('redacts camelCase authentication keys without matching larger words', () => { - const out = redactLogMessage( - `authToken=auth-secret idToken=id-secret clientSecret=client-secret {"userPassword":"password-secret"}`, - ); + it('redacts camelCase authentication keys without matching larger words', () => { + const out = redactLogMessage( + `authToken=auth-secret idToken=id-secret clientSecret=client-secret {"userPassword":"password-secret"}`, + ); - expect(out).toBe( - `authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`, - ); - expect(out).not.toMatch( - /auth-secret|id-secret|client-secret|password-secret/, - ); - expect(redactLogMessage( - 'retoken=value cookietown=value myauthorization=value', - )).toBe('retoken=value cookietown=value myauthorization=value'); - }); + expect(out).toBe(`authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`); + expect(out).not.toMatch(/auth-secret|id-secret|client-secret|password-secret/); + expect(redactLogMessage('retoken=value cookietown=value myauthorization=value')).toBe( + 'retoken=value cookietown=value myauthorization=value', + ); + }); - it('redacts leading separator and numeric authentication keys without matching larger words', () => { - expect(redactLogMessage( - '_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible', - )).toBe('_token=*** --password=*** 2faToken=*** retoken=visible'); - }); + it('redacts leading separator and numeric authentication keys without matching larger words', () => { + expect( + redactLogMessage( + '_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible', + ), + ).toBe('_token=*** --password=*** 2faToken=*** retoken=visible'); + }); - it('redacts nested assignments inside non-sensitive wrapper values', () => { - expect(redactLogMessage( - 'params=authToken=auth-secret params=cookie="cookie-secret"', - )).toBe('params=authToken=*** params=cookie=***'); - }); + it('redacts nested assignments inside non-sensitive wrapper values', () => { + expect(redactLogMessage('params=authToken=auth-secret params=cookie="cookie-secret"')).toBe( + 'params=authToken=*** params=cookie=***', + ); + }); - it('redacts the entire Authorization value when it starts with a marker', () => { - expect(redactLogMessage('Authorization: *** secret-value')) - .toBe('Authorization: ***'); - }); + it('redacts the entire Authorization value when it starts with a marker', () => { + expect(redactLogMessage('Authorization: *** secret-value')).toBe('Authorization: ***'); + }); - it('redacts property paths and URL query authentication values', () => { - const out = redactLogMessage( - 'headers.authorization=Basic dXNlcjpwYXNz ' - + 'request.token=plain-token ' - + 'GET /callback?access_token=query-secret&x=1 ' - + 'url=https://host/?api_key=url-secret', - ); + it('redacts property paths and URL query authentication values', () => { + const out = redactLogMessage( + 'headers.authorization=Basic dXNlcjpwYXNz ' + + 'request.token=plain-token ' + + 'GET /callback?access_token=query-secret&x=1 ' + + 'url=https://host/?api_key=url-secret', + ); - expect(out).toContain('headers.authorization=***'); - expect(out).toContain('request.token=***'); - expect(out).toContain('/callback?access_token=***&x=1'); - expect(out).toContain('https://host/?api_key=***'); - expect(out).not.toMatch(/dXNlcjpwYXNz|plain-token|query-secret|url-secret/); - }); + expect(out).toContain('headers.authorization=***'); + expect(out).toContain('request.token=***'); + expect(out).toContain('/callback?access_token=***&x=1'); + expect(out).toContain('https://host/?api_key=***'); + expect(out).not.toMatch(/dXNlcjpwYXNz|plain-token|query-secret|url-secret/); + }); - it('redacts prefixed authentication keys without matching larger words', () => { - const redacted = redactLogMessage( - 'x-api-key=api-secret user_password=password-secret ' - + 'headers.authorization=Basic auth-secret ' - + 'x-cookie="session=cookie-secret"; Path=/; HttpOnly', - ); + it('redacts prefixed authentication keys without matching larger words', () => { + const redacted = redactLogMessage( + 'x-api-key=api-secret user_password=password-secret ' + + 'headers.authorization=Basic auth-secret ' + + 'x-cookie="session=cookie-secret"; Path=/; HttpOnly', + ); - expect(redacted).toContain('x-api-key=***'); - expect(redacted).toContain('user_password=***'); - expect(redacted).toContain('headers.authorization=***'); - expect(redacted).toContain('x-cookie=***'); - expect(redacted).not.toMatch(/api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/); - expect(redactLogMessage( - 'retoken=value cookietown=value myauthorization=value', - )).toBe('retoken=value cookietown=value myauthorization=value'); - }); + expect(redacted).toContain('x-api-key=***'); + expect(redacted).toContain('user_password=***'); + expect(redacted).toContain('headers.authorization=***'); + expect(redacted).toContain('x-cookie=***'); + expect(redacted).not.toMatch( + /api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/, + ); + expect(redactLogMessage('retoken=value cookietown=value myauthorization=value')).toBe( + 'retoken=value cookietown=value myauthorization=value', + ); + }); }); describe('renderParamsVerbose', () => { - it('keeps authentication fields unredacted for complete TRACE diagnostics', () => { - const out = renderParamsVerbose({ - token: 'token-value', - Cookie: 'cookie-value', - password: 'password-value', - apiKey: 'key-value', + it('keeps authentication fields unredacted for complete TRACE diagnostics', () => { + const out = renderParamsVerbose({ + token: 'token-value', + Cookie: 'cookie-value', + password: 'password-value', + apiKey: 'key-value', + }); + + expect(out).toContain('token:"token-value"'); + expect(out).toContain('Cookie:"cookie-value"'); + expect(out).toContain('password:"password-value"'); + expect(out).toContain('apiKey:"key-value"'); + expect(out).not.toContain('"***"'); }); - expect(out).toContain('token:"token-value"'); - expect(out).toContain('Cookie:"cookie-value"'); - expect(out).toContain('password:"password-value"'); - expect(out).toContain('apiKey:"key-value"'); - expect(out).not.toContain('"***"'); - }); + it('does not truncate TRACE values or their enclosing object', () => { + const unicodeValue = '雪'.repeat(800); + const out = renderParamsVerbose({ blob: unicodeValue, tail: 'complete' }); - it('does not truncate TRACE values or their enclosing object', () => { - const unicodeValue = '雪'.repeat(800); - const out = renderParamsVerbose({ blob: unicodeValue, tail: 'complete' }); + expect(out).toContain(`blob:${JSON.stringify(unicodeValue)}`); + expect(out).toContain('tail:"complete"'); + expect(out).not.toMatch(/…<\d+B>|\.\.\./); + }); - expect(out).toContain(`blob:${JSON.stringify(unicodeValue)}`); - expect(out).toContain('tail:"complete"'); - expect(out).not.toMatch(/…<\d+B>|\.\.\./); - }); + it('guards against circular references', () => { + const o: Record = { a: 1 }; + o.self = o; + expect(renderParamsVerbose(o)).toContain('"[circular]"'); + }); - it('guards against circular references', () => { - const o: Record = { a: 1 }; - o.self = o; - expect(renderParamsVerbose(o)).toContain('"[circular]"'); - }); + it('renders shared non-cyclic references in every branch', () => { + const shared = { value: 1 }; - it('renders shared non-cyclic references in every branch', () => { - const shared = { value: 1 }; + expect(renderParamsVerbose({ left: shared, right: shared })).toBe( + '{left:{value:1},right:{value:1}}', + ); + }); - expect(renderParamsVerbose({ left: shared, right: shared })) - .toBe('{left:{value:1},right:{value:1}}'); - }); - - it('renders nested structure with primitives intact', () => { - expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}'); - }); + it('renders nested structure with primitives intact', () => { + expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}'); + }); }); diff --git a/packages/common/tests/logger.test.ts b/packages/common/tests/logger.test.ts index a536bc24..7ca9639a 100644 --- a/packages/common/tests/logger.test.ts +++ b/packages/common/tests/logger.test.ts @@ -1,83 +1,84 @@ import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const { externalFileLevel, externalLogLevel, fileWriteSpy } = vi.hoisted(() => { - const savedFileLevel = process.env.SNOWLUMA_LOG_FILE_LEVEL; - const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL; - delete process.env.SNOWLUMA_LOG_FILE_LEVEL; - delete process.env.SNOWLUMA_LOG_LEVEL; - return { - externalFileLevel: savedFileLevel, - externalLogLevel: savedLogLevel, - fileWriteSpy: vi.fn(), - }; + const savedFileLevel = process.env.SNOWLUMA_LOG_FILE_LEVEL; + const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL; + delete process.env.SNOWLUMA_LOG_FILE_LEVEL; + delete process.env.SNOWLUMA_LOG_LEVEL; + return { + externalFileLevel: savedFileLevel, + externalLogLevel: savedLogLevel, + fileWriteSpy: vi.fn(), + }; }); // Capture file transport writes via a spy so tests can assert on what reaches // the file. vi.mock('../src/log-file-transport', () => ({ - getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }), + getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }), })); -import { - createLogger, - subscribeLogs, - type LogEntry, -} from '../src/logger'; +import { createLogger, subscribeLogs, type LogEntry } from '../src/logger'; // Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp // shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored // render path did `' '.repeat(slot - tagLen)` → RangeError: Invalid count value // → uncaughtException. The padding must clamp at zero. describe('logger UIN slot padding', () => { - let prevTTY: boolean | undefined; - let prevNoColor: string | undefined; + let prevTTY: boolean | undefined; + let prevNoColor: string | undefined; - beforeEach(() => { - prevTTY = process.stdout.isTTY; - prevNoColor = process.env.NO_COLOR; - // Force the colored render path (the only one that used .repeat()). - (process.stdout as unknown as { isTTY: boolean }).isTTY = true; - delete process.env.NO_COLOR; - vi.spyOn(process.stdout, 'write').mockReturnValue(true); - vi.spyOn(process.stderr, 'write').mockReturnValue(true); - }); - - afterEach(() => { - (process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY; - if (prevNoColor === undefined) delete process.env.NO_COLOR; - else process.env.NO_COLOR = prevNoColor; - vi.restoreAllMocks(); - }); - - it('does not throw when the UIN tag exceeds the slot width', () => { - const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars - expect(() => log.info('phantom account line')).not.toThrow(); - expect(() => log.error('phantom error line')).not.toThrow(); - }); - - it('still renders a normal-width UIN and a no-UIN logger', () => { - expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow(); - expect(() => createLogger('Test').info('no uin')).not.toThrow(); - }); - - it('does not throw when the console stream cannot accept the line', () => { - vi.mocked(process.stderr.write).mockImplementation(() => { - throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }); + beforeEach(() => { + prevTTY = process.stdout.isTTY; + prevNoColor = process.env.NO_COLOR; + // Force the colored render path (the only one that used .repeat()). + (process.stdout as unknown as { isTTY: boolean }).isTTY = true; + delete process.env.NO_COLOR; + vi.spyOn(process.stdout, 'write').mockReturnValue(true); + vi.spyOn(process.stderr, 'write').mockReturnValue(true); }); - expect(() => createLogger('Test').error('disk is full')).not.toThrow(); - }); - it('keeps structured subscriber lines plain while terminal output stays colored', () => { - const captured: LogEntry[] = []; - const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + afterEach(() => { + (process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY; - createLogger('WebUI.Export').info('download me'); - unsubscribe(); + if (prevNoColor === undefined) { + delete process.env.NO_COLOR; + } else { + process.env.NO_COLOR = prevNoColor; + } - expect(captured).toHaveLength(1); - expect(captured[0]!.line).toMatch(/INFO\s+\[WebUI\.Export\] download me$/); - expect(process.stdout.write).toHaveBeenCalledWith(expect.stringContaining('\x1b[')); - }); + vi.restoreAllMocks(); + }); + + it('does not throw when the UIN tag exceeds the slot width', () => { + const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars + expect(() => log.info('phantom account line')).not.toThrow(); + expect(() => log.error('phantom error line')).not.toThrow(); + }); + + it('still renders a normal-width UIN and a no-UIN logger', () => { + expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow(); + expect(() => createLogger('Test').info('no uin')).not.toThrow(); + }); + + it('does not throw when the console stream cannot accept the line', () => { + vi.mocked(process.stderr.write).mockImplementation(() => { + throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }); + }); + expect(() => createLogger('Test').error('disk is full')).not.toThrow(); + }); + + it('keeps structured subscriber lines plain while terminal output stays colored', () => { + const captured: LogEntry[] = []; + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + + createLogger('WebUI.Export').info('download me'); + unsubscribe(); + + expect(captured).toHaveLength(1); + expect(captured[0]!.line).toMatch(/INFO\s+\[WebUI\.Export\] download me$/); + expect(process.stdout.write).toHaveBeenCalledWith(expect.stringContaining('\x1b[')); + }); }); // ─── Independent file-level filtering ───────────────────────────────────── @@ -85,237 +86,253 @@ describe('logger UIN slot padding', () => { const SAVED_FILE_LEVEL = externalFileLevel; async function loadLoggerForFileLevel(level?: string) { - if (level === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL; - else process.env.SNOWLUMA_LOG_FILE_LEVEL = level; - vi.resetModules(); - fileWriteSpy.mockClear(); - return import('../src/logger'); + if (level === undefined) { + delete process.env.SNOWLUMA_LOG_FILE_LEVEL; + } else { + process.env.SNOWLUMA_LOG_FILE_LEVEL = level; + } + + vi.resetModules(); + fileWriteSpy.mockClear(); + return import('../src/logger'); } afterEach(() => { - if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL; - else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL; - vi.resetModules(); - fileWriteSpy.mockClear(); + if (SAVED_FILE_LEVEL === undefined) { + delete process.env.SNOWLUMA_LOG_FILE_LEVEL; + } else { + process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL; + } + + vi.resetModules(); + fileWriteSpy.mockClear(); }); afterAll(() => { - if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL; - else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL; - if (externalLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL; - else process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel; + if (SAVED_FILE_LEVEL === undefined) { + delete process.env.SNOWLUMA_LOG_FILE_LEVEL; + } else { + process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL; + } + + if (externalLogLevel === undefined) { + delete process.env.SNOWLUMA_LOG_LEVEL; + } else { + process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel; + } }); describe('file output gating', () => { - const cases = [ - { level: undefined, expected: ['debug', 'info', 'success', 'warn', 'error'] }, - { level: 'debug', expected: ['debug', 'info', 'success', 'warn', 'error'] }, - { level: 'info', expected: ['info', 'success', 'warn', 'error'] }, - { level: 'success', expected: ['success', 'warn', 'error'] }, - { level: 'warn', expected: ['warn', 'error'] }, - { level: 'error', expected: ['error'] }, - ] as const; + const cases = [ + { level: undefined, expected: ['debug', 'info', 'success', 'warn', 'error'] }, + { level: 'debug', expected: ['debug', 'info', 'success', 'warn', 'error'] }, + { level: 'info', expected: ['info', 'success', 'warn', 'error'] }, + { level: 'success', expected: ['success', 'warn', 'error'] }, + { level: 'warn', expected: ['warn', 'error'] }, + { level: 'error', expected: ['error'] }, + ] as const; - for (const testCase of cases) { - it(`writes exactly the enabled levels for ${testCase.level ?? 'the default'}`, async () => { - const fresh = await loadLoggerForFileLevel(testCase.level); - const log = fresh.createLogger('Test'); + for (const testCase of cases) { + it(`writes exactly the enabled levels for ${testCase.level ?? 'the default'}`, async () => { + const fresh = await loadLoggerForFileLevel(testCase.level); + const log = fresh.createLogger('Test'); - fresh.setLogLevel('trace'); - log.trace('trace'); - log.debug('debug'); - log.info('info'); - log.success('success'); - log.warn('warn'); - log.error('error'); + fresh.setLogLevel('trace'); + log.trace('trace'); + log.debug('debug'); + log.info('info'); + log.success('success'); + log.warn('warn'); + log.error('error'); - const messages = fileWriteSpy.mock.calls.map(([line]) => String(line).split('] ').at(-1)); - expect(messages).toEqual(testCase.expected); - }); - } - - it('accepts surrounding whitespace and mixed case', async () => { - const fresh = await loadLoggerForFileLevel(' INFO '); - const log = fresh.createLogger('Test'); - - log.debug('debug'); - log.info('info'); - - expect(fileWriteSpy).toHaveBeenCalledTimes(1); - expect(fileWriteSpy).toHaveBeenCalledWith(expect.stringContaining('info'), undefined); - }); - - it.each(['trace', 'verbose', 'erorr'])( - 'rejects unsupported file level %s at startup', - async (level) => { - await expect(loadLoggerForFileLevel(level)).rejects.toThrow( - 'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error', - ); - expect(fileWriteSpy).not.toHaveBeenCalled(); - }, - ); - - it('does not let the runtime console level change file output', async () => { - const fresh = await loadLoggerForFileLevel('info'); - const log = fresh.createLogger('Test'); - - fresh.setLogLevel('error'); - log.info('persisted-info'); - fresh.setLogLevel('trace'); - log.debug('filtered-debug'); - - expect(fileWriteSpy).toHaveBeenCalledTimes(1); - expect(fileWriteSpy).toHaveBeenCalledWith( - expect.stringContaining('persisted-info'), - undefined, - ); - }); - - it('skips rendering when both console and file filters reject a record', async () => { - const fresh = await loadLoggerForFileLevel('error'); - fresh.setLogLevel('error'); - const rendered = vi.fn(() => 'expensive'); - const value = { [Symbol.toPrimitive]: rendered }; - - fresh.createLogger('Test').debug('value=%s', value); - - expect(rendered).not.toHaveBeenCalled(); - expect(fileWriteSpy).not.toHaveBeenCalled(); - }); - - it('keeps trace out of files in an explicit file-threshold check', async () => { - const fresh = await loadLoggerForFileLevel('debug'); - fresh.setLogLevel('trace'); - - fresh.createLogger('Test').trace('full chain'); - - expect(fileWriteSpy).not.toHaveBeenCalled(); - }); - - it('redacts authentication assignments from ordinary logs but not TRACE', async () => { - const fresh = await loadLoggerForFileLevel('debug'); - fresh.setLogLevel('trace'); - const entries: LogEntry[] = []; - const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry)); - const log = fresh.createLogger('Test'); - - log.info( - 'password=%s Authorization: Bearer %s Cookie=%s token=%s safe=%s', - 'ordinary-password', - 'ordinary-authorization', - 'ordinary-cookie', - 'ordinary-token', - 'visible', - ); - log.trace( - 'password=%s Authorization: Bearer %s Cookie=%s token=%s', - 'trace-password', - 'trace-authorization', - 'trace-cookie', - 'trace-token', - ); - log.info( - `json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`, - ); - log.info( - 'headers.authorization=Basic dotted-auth request.token=dotted-token ' - + 'GET /callback?access_token=query-secret&x=1 ' - + 'url=https://host/?api_key=url-secret', - ); - log.info( - 'Authorization: Digest username="alice", response="digest-secret"\n' - + 'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret', - ); - log.info( - 'authToken=camel-auth idToken=camel-id clientSecret=camel-client ' - + `json={"userPassword":"camel-password"}`, - ); - log.info('_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret'); - log.info('Authorization: *** marker-secret'); - log.trace( - `json={"authorization":"Basic trace-json-auth"} Authorization: Basic trace-header-auth Cookie=session=trace-cookie; Path=/`, - ); - unsubscribe(); - - const ordinaryEntries = entries.filter((entry) => entry.level === 'info'); - const ordinary = ordinaryEntries.map((entry) => entry.message).join('\n'); - expect(ordinary).toContain('password=***'); - expect(ordinary).toContain('Authorization: ***'); - expect(ordinary).toContain('Cookie=***'); - expect(ordinary).toContain('token=***'); - expect(ordinary).toContain('headers.authorization=***'); - expect(ordinary).toContain('request.token=***'); - expect(ordinary).toContain('/callback?access_token=***&x=1'); - expect(ordinary).toContain('https://host/?api_key=***'); - expect(ordinary).toContain('Authorization: ***\nauthorization=***'); - expect(ordinary).toContain('authToken=***'); - expect(ordinary).toContain('idToken=***'); - expect(ordinary).toContain('clientSecret=***'); - expect(ordinary).toContain(`json={"userPassword":***}`); - expect(ordinary).toContain('_token=***'); - expect(ordinary).toContain('--password=***'); - expect(ordinary).toContain('2faToken=***'); - expect(ordinary).toContain('Authorization: ***'); - expect(ordinary).toContain('safe=visible'); - expect(ordinary).not.toMatch( - /ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|camel-auth|camel-id|camel-client|camel-password|underscore-secret|cli-secret|two-factor-secret|marker-secret/, - ); - - const trace = entries.filter((entry) => entry.level === 'trace') - .map((entry) => entry.message) - .join('\n'); - expect(trace).toContain('trace-password'); - expect(trace).toContain('trace-authorization'); - expect(trace).toContain('trace-cookie'); - expect(trace).toContain('trace-token'); - expect(trace).toContain('trace-json-auth'); - expect(trace).toContain('trace-header-auth'); - - const persisted = fileWriteSpy.mock.calls.map(([line]) => String(line)).join('\n'); - expect(persisted).not.toMatch( - /ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|trace-password|trace-json-auth/, - ); - }); - - it('returns the complete retained normal and TRACE snapshot in record order', async () => { - const fresh = await loadLoggerForFileLevel('debug'); - const log = fresh.createLogger('Export'); - fresh.setLogLevel('trace'); - - log.info('normal-before'); - log.trace('trace-hex=001122aabbcc'); - log.warn('normal-after'); - - expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual([ - 'normal-after', - ]); - expect(fresh.getLogSnapshot().map((entry) => entry.message)).toEqual([ - 'normal-before', - 'trace-hex=001122aabbcc', - 'normal-after', - ]); - }); - - it('prints bootstrap credentials only to the current process terminal', async () => { - const fresh = await loadLoggerForFileLevel('error'); - fresh.setLogLevel('error'); - const entries: LogEntry[] = []; - const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry)); - const snapshotBefore = fresh.getLogSnapshot(); - const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); - - try { - fresh.logInitialWebuiCredentials('secret'); - - expect(stdout).toHaveBeenCalledWith( - expect.stringContaining('initial credentials: user=admin password=secret'), - ); - expect(entries).toEqual([]); - expect(fresh.getLogSnapshot()).toEqual(snapshotBefore); - expect(fileWriteSpy).not.toHaveBeenCalled(); - } finally { - unsubscribe(); - stdout.mockRestore(); + const messages = fileWriteSpy.mock.calls.map(([line]) => + String(line).split('] ').at(-1), + ); + expect(messages).toEqual(testCase.expected); + }); } - }); + + it('accepts surrounding whitespace and mixed case', async () => { + const fresh = await loadLoggerForFileLevel(' INFO '); + const log = fresh.createLogger('Test'); + + log.debug('debug'); + log.info('info'); + + expect(fileWriteSpy).toHaveBeenCalledTimes(1); + expect(fileWriteSpy).toHaveBeenCalledWith(expect.stringContaining('info'), undefined); + }); + + it.each(['trace', 'verbose', 'erorr'])( + 'rejects unsupported file level %s at startup', + async (level) => { + await expect(loadLoggerForFileLevel(level)).rejects.toThrow( + 'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error', + ); + expect(fileWriteSpy).not.toHaveBeenCalled(); + }, + ); + + it('does not let the runtime console level change file output', async () => { + const fresh = await loadLoggerForFileLevel('info'); + const log = fresh.createLogger('Test'); + + fresh.setLogLevel('error'); + log.info('persisted-info'); + fresh.setLogLevel('trace'); + log.debug('filtered-debug'); + + expect(fileWriteSpy).toHaveBeenCalledTimes(1); + expect(fileWriteSpy).toHaveBeenCalledWith( + expect.stringContaining('persisted-info'), + undefined, + ); + }); + + it('skips rendering when both console and file filters reject a record', async () => { + const fresh = await loadLoggerForFileLevel('error'); + fresh.setLogLevel('error'); + const rendered = vi.fn(() => 'expensive'); + const value = { [Symbol.toPrimitive]: rendered }; + + fresh.createLogger('Test').debug('value=%s', value); + + expect(rendered).not.toHaveBeenCalled(); + expect(fileWriteSpy).not.toHaveBeenCalled(); + }); + + it('keeps trace out of files in an explicit file-threshold check', async () => { + const fresh = await loadLoggerForFileLevel('debug'); + fresh.setLogLevel('trace'); + + fresh.createLogger('Test').trace('full chain'); + + expect(fileWriteSpy).not.toHaveBeenCalled(); + }); + + it('redacts authentication assignments from ordinary logs but not TRACE', async () => { + const fresh = await loadLoggerForFileLevel('debug'); + fresh.setLogLevel('trace'); + const entries: LogEntry[] = []; + const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry)); + const log = fresh.createLogger('Test'); + + log.info( + 'password=%s Authorization: Bearer %s Cookie=%s token=%s safe=%s', + 'ordinary-password', + 'ordinary-authorization', + 'ordinary-cookie', + 'ordinary-token', + 'visible', + ); + log.trace( + 'password=%s Authorization: Bearer %s Cookie=%s token=%s', + 'trace-password', + 'trace-authorization', + 'trace-cookie', + 'trace-token', + ); + log.info( + `json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`, + ); + log.info( + 'headers.authorization=Basic dotted-auth request.token=dotted-token ' + + 'GET /callback?access_token=query-secret&x=1 ' + + 'url=https://host/?api_key=url-secret', + ); + log.info( + 'Authorization: Digest username="alice", response="digest-secret"\n' + + 'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret', + ); + log.info( + 'authToken=camel-auth idToken=camel-id clientSecret=camel-client ' + + `json={"userPassword":"camel-password"}`, + ); + log.info('_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret'); + log.info('Authorization: *** marker-secret'); + log.trace( + `json={"authorization":"Basic trace-json-auth"} Authorization: Basic trace-header-auth Cookie=session=trace-cookie; Path=/`, + ); + unsubscribe(); + + const ordinaryEntries = entries.filter((entry) => entry.level === 'info'); + const ordinary = ordinaryEntries.map((entry) => entry.message).join('\n'); + expect(ordinary).toContain('password=***'); + expect(ordinary).toContain('Authorization: ***'); + expect(ordinary).toContain('Cookie=***'); + expect(ordinary).toContain('token=***'); + expect(ordinary).toContain('headers.authorization=***'); + expect(ordinary).toContain('request.token=***'); + expect(ordinary).toContain('/callback?access_token=***&x=1'); + expect(ordinary).toContain('https://host/?api_key=***'); + expect(ordinary).toContain('Authorization: ***\nauthorization=***'); + expect(ordinary).toContain('authToken=***'); + expect(ordinary).toContain('idToken=***'); + expect(ordinary).toContain('clientSecret=***'); + expect(ordinary).toContain(`json={"userPassword":***}`); + expect(ordinary).toContain('_token=***'); + expect(ordinary).toContain('--password=***'); + expect(ordinary).toContain('2faToken=***'); + expect(ordinary).toContain('Authorization: ***'); + expect(ordinary).toContain('safe=visible'); + expect(ordinary).not.toMatch( + /ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|camel-auth|camel-id|camel-client|camel-password|underscore-secret|cli-secret|two-factor-secret|marker-secret/, + ); + + const trace = entries + .filter((entry) => entry.level === 'trace') + .map((entry) => entry.message) + .join('\n'); + expect(trace).toContain('trace-password'); + expect(trace).toContain('trace-authorization'); + expect(trace).toContain('trace-cookie'); + expect(trace).toContain('trace-token'); + expect(trace).toContain('trace-json-auth'); + expect(trace).toContain('trace-header-auth'); + + const persisted = fileWriteSpy.mock.calls.map(([line]) => String(line)).join('\n'); + expect(persisted).not.toMatch( + /ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|trace-password|trace-json-auth/, + ); + }); + + it('returns the complete retained normal and TRACE snapshot in record order', async () => { + const fresh = await loadLoggerForFileLevel('debug'); + const log = fresh.createLogger('Export'); + fresh.setLogLevel('trace'); + + log.info('normal-before'); + log.trace('trace-hex=001122aabbcc'); + log.warn('normal-after'); + + expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual(['normal-after']); + expect(fresh.getLogSnapshot().map((entry) => entry.message)).toEqual([ + 'normal-before', + 'trace-hex=001122aabbcc', + 'normal-after', + ]); + }); + + it('prints bootstrap credentials only to the current process terminal', async () => { + const fresh = await loadLoggerForFileLevel('error'); + fresh.setLogLevel('error'); + const entries: LogEntry[] = []; + const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry)); + const snapshotBefore = fresh.getLogSnapshot(); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + + try { + fresh.logInitialWebuiCredentials('secret'); + + expect(stdout).toHaveBeenCalledWith( + expect.stringContaining('initial credentials: user=admin password=secret'), + ); + expect(entries).toEqual([]); + expect(fresh.getLogSnapshot()).toEqual(snapshotBefore); + expect(fileWriteSpy).not.toHaveBeenCalled(); + } finally { + unsubscribe(); + stdout.mockRestore(); + } + }); }); diff --git a/packages/common/tests/request-context.test.ts b/packages/common/tests/request-context.test.ts index 1b4fc8f5..98b4839f 100644 --- a/packages/common/tests/request-context.test.ts +++ b/packages/common/tests/request-context.test.ts @@ -2,33 +2,33 @@ import { describe, expect, it } from 'vitest'; import { currentRequestId, nextRequestId, runWithRequestId } from '../src/request-context'; describe('request-context', () => { - it('nextRequestId increments monotonically and stays a positive integer', () => { - const a = nextRequestId(); - const b = nextRequestId(); - expect(a).toBeGreaterThan(0); - expect(b).toBe(a + 1); - }); - - it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => { - expect(currentRequestId()).toBeUndefined(); - - runWithRequestId(42, () => { - expect(currentRequestId()).toBe(42); - runWithRequestId(99, () => { - expect(currentRequestId()).toBe(99); - }); - expect(currentRequestId()).toBe(42); // outer scope restored after the nested one + it('nextRequestId increments monotonically and stays a positive integer', () => { + const a = nextRequestId(); + const b = nextRequestId(); + expect(a).toBeGreaterThan(0); + expect(b).toBe(a + 1); }); - expect(currentRequestId()).toBeUndefined(); // cleared outside any scope + it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => { + expect(currentRequestId()).toBeUndefined(); - await runWithRequestId(7, async () => { - await Promise.resolve(); - expect(currentRequestId()).toBe(7); // survives awaits in the same async chain + runWithRequestId(42, () => { + expect(currentRequestId()).toBe(42); + runWithRequestId(99, () => { + expect(currentRequestId()).toBe(99); + }); + expect(currentRequestId()).toBe(42); // outer scope restored after the nested one + }); + + expect(currentRequestId()).toBeUndefined(); // cleared outside any scope + + await runWithRequestId(7, async () => { + await Promise.resolve(); + expect(currentRequestId()).toBe(7); // survives awaits in the same async chain + }); }); - }); - it('returns the callback result', () => { - expect(runWithRequestId(1, () => 'value')).toBe('value'); - }); + it('returns the callback result', () => { + expect(runWithRequestId(1, () => 'value')).toBe('value'); + }); }); diff --git a/packages/common/tests/runtime.test.ts b/packages/common/tests/runtime.test.ts index 878fc3a8..c53413e0 100644 --- a/packages/common/tests/runtime.test.ts +++ b/packages/common/tests/runtime.test.ts @@ -4,199 +4,226 @@ import { describe, it, expect, beforeEach, afterEach, vi } 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: '127.0.0.1', - webuiTls: { enabled: false }, - trustProxy: '', - logMaxTotalMb: 1024, - logRetainDays: 7, - logPerUin: false, + it('applies all defaults for an empty object', () => { + expect(normalizeRuntimeConfig({})).toEqual({ + webuiPort: 5099, + hookAutoLoad: false, + webuiHost: '127.0.0.1', + webuiTls: { enabled: false }, + trustProxy: '', + logMaxTotalMb: 1024, + logRetainDays: 7, + logPerUin: false, + }); }); - }); - it('passes through valid values', () => { - expect(normalizeRuntimeConfig({ - webuiPort: 8080, - hookAutoLoad: true, - webuiHost: '127.0.0.1', - webuiTls: { enabled: true }, - trustProxy: '1', - logMaxTotalMb: 2048, - logRetainDays: 0, - logPerUin: true, - })).toEqual({ - webuiPort: 8080, - hookAutoLoad: true, - webuiHost: '127.0.0.1', - webuiTls: { enabled: true }, - trustProxy: '1', - logMaxTotalMb: 2048, - logRetainDays: 0, - logPerUin: true, + it('passes through valid values', () => { + expect( + normalizeRuntimeConfig({ + webuiPort: 8080, + hookAutoLoad: true, + webuiHost: '127.0.0.1', + webuiTls: { enabled: true }, + trustProxy: '1', + logMaxTotalMb: 2048, + logRetainDays: 0, + logPerUin: true, + }), + ).toEqual({ + webuiPort: 8080, + hookAutoLoad: true, + webuiHost: '127.0.0.1', + webuiTls: { enabled: true }, + trustProxy: '1', + logMaxTotalMb: 2048, + logRetainDays: 0, + logPerUin: true, + }); }); - }); - 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 + 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('127.0.0.1'); + expect(out.webuiTls).toEqual({ enabled: false }); + expect(out.trustProxy).toBe(''); }); - expect(out.webuiPort).toBe(5099); - expect(out.webuiHost).toBe('127.0.0.1'); - expect(out.webuiTls).toEqual({ enabled: false }); - expect(out.trustProxy).toBe(''); - }); - it('fails fast on invalid persisted log settings', () => { - expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 })) - .toThrow(/logMaxTotalMb/); - expect(() => normalizeRuntimeConfig({ logRetainDays: -1 })) - .toThrow(/logRetainDays/); - expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' })) - .toThrow(/logPerUin/); - expect(() => normalizeRuntimeConfig({ logPerUin: '' })) - .toThrow(/logPerUin/); - expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER })) - .toThrow(/logMaxTotalMb/); - expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER })) - .toThrow(/logRetainDays/); - }); + it('fails fast on invalid persisted log settings', () => { + expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 })).toThrow(/logMaxTotalMb/); + expect(() => normalizeRuntimeConfig({ logRetainDays: -1 })).toThrow(/logRetainDays/); + expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' })).toThrow(/logPerUin/); + expect(() => normalizeRuntimeConfig({ logPerUin: '' })).toThrow(/logPerUin/); + expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER })).toThrow( + /logMaxTotalMb/, + ); + expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER })).toThrow( + /logRetainDays/, + ); + }); - 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('127.0.0.1'); - }); + 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('127.0.0.1'); + }); - it('rejects a non-object input back to full defaults', () => { - expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099); - expect(normalizeRuntimeConfig('nope').webuiHost).toBe('127.0.0.1'); - }); + it('rejects a non-object input back to full defaults', () => { + expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099); + expect(normalizeRuntimeConfig('nope').webuiHost).toBe('127.0.0.1'); + }); }); 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('parses log storage overrides including retainDays=0', () => { - expect(resolveRuntimeEnvOverrides({ - SNOWLUMA_LOG_MAX_TOTAL_MB: '4096', - SNOWLUMA_LOG_RETAIN_DAYS: '0', - SNOWLUMA_LOG_PER_UIN: '1', - })).toEqual({ - logMaxTotalMb: 4096, - logRetainDays: 0, - logPerUin: true, + it('returns empty when no SNOWLUMA_* vars are set', () => { + expect(resolveRuntimeEnvOverrides({})).toEqual({}); }); - }); - it('fails fast on invalid log storage overrides', () => { - expect(() => resolveRuntimeEnvOverrides({ - SNOWLUMA_LOG_MAX_TOTAL_MB: '0', - })).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/); - expect(() => resolveRuntimeEnvOverrides({ - SNOWLUMA_LOG_RETAIN_DAYS: '-1', - })).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/); - expect(() => resolveRuntimeEnvOverrides({ - SNOWLUMA_LOG_PER_UIN: 'maybe', - })).toThrow(/SNOWLUMA_LOG_PER_UIN/); - }); - - it('fails fast when converted log storage overrides would be unsafe', () => { - expect(() => resolveRuntimeEnvOverrides({ - SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER), - })).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/); - expect(() => resolveRuntimeEnvOverrides({ - SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER), - })).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/); - }); - - it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => { - expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '1' })).toEqual({ - webuiTls: { enabled: true }, + 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' }); }); - expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({ - webuiTls: { enabled: false }, + + it('parses log storage overrides including retainDays=0', () => { + expect( + resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_MAX_TOTAL_MB: '4096', + SNOWLUMA_LOG_RETAIN_DAYS: '0', + SNOWLUMA_LOG_PER_UIN: '1', + }), + ).toEqual({ + logMaxTotalMb: 4096, + logRetainDays: 0, + logPerUin: true, + }); }); - expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' })) - .toThrow(/SNOWLUMA_WEBUI_TLS/); - }); - 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('fails fast on invalid log storage overrides', () => { + expect(() => + resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_MAX_TOTAL_MB: '0', + }), + ).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/); + expect(() => + resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_RETAIN_DAYS: '-1', + }), + ).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/); + expect(() => + resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_PER_UIN: 'maybe', + }), + ).toThrow(/SNOWLUMA_LOG_PER_UIN/); + }); - it('treats trustProxy="0"/"off" as a real override (not absent)', () => { - expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' }); - }); + it('fails fast when converted log storage overrides would be unsafe', () => { + expect(() => + resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER), + }), + ).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/); + expect(() => + resolveRuntimeEnvOverrides({ + SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER), + }), + ).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/); + }); + + it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => { + expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '1' })).toEqual({ + webuiTls: { enabled: true }, + }); + expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({ + webuiTls: { enabled: false }, + }); + expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' })).toThrow( + /SNOWLUMA_WEBUI_TLS/, + ); + }); + + 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 () => { - 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 }); - vi.restoreAllMocks(); - }); + 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 () => { + process.chdir(prevCwd); - 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 }); - }); + if (prevPortEnv === undefined) { + delete process.env.SNOWLUMA_WEBUI_PORT; + } else { + process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv; + } - 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 - }); - - it('keeps the previous runtime file intact when atomic replacement fails', async () => { - const { updateRuntimeConfig } = await import('../src/runtime'); - updateRuntimeConfig({ logRetainDays: 7 }); - const runtimePath = path.join('config', 'runtime.json'); - const before = fs.readFileSync(runtimePath, 'utf8'); - vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => { - throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' }); + fs.rmSync(dir, { recursive: true, force: true }); + vi.restoreAllMocks(); }); - expect(() => updateRuntimeConfig({ logRetainDays: 0 })) - .toThrow(/disk replacement failed/); - expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before); - expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]); - }); + 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 + }); + + it('keeps the previous runtime file intact when atomic replacement fails', async () => { + const { updateRuntimeConfig } = await import('../src/runtime'); + updateRuntimeConfig({ logRetainDays: 7 }); + const runtimePath = path.join('config', 'runtime.json'); + const before = fs.readFileSync(runtimePath, 'utf8'); + vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => { + throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' }); + }); + + expect(() => updateRuntimeConfig({ logRetainDays: 0 })).toThrow(/disk replacement failed/); + expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before); + expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]); + }); }); diff --git a/packages/common/tests/single-flight-cache.test.ts b/packages/common/tests/single-flight-cache.test.ts index 77233282..8037f751 100644 --- a/packages/common/tests/single-flight-cache.test.ts +++ b/packages/common/tests/single-flight-cache.test.ts @@ -3,129 +3,148 @@ import { createSingleFlightCache } from '../src/single-flight-cache'; /** A promise whose resolve/reject is exposed, for driving single-flight races. */ function deferred() { - let resolve!: (v: T) => void; - let reject!: (e: unknown) => void; - const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); - return { promise, resolve, reject }; + let resolve!: (v: T) => void; + let reject!: (e: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; } describe('SingleFlightCache', () => { - it('caches within the TTL and reloads once expired', async () => { - let clock = 1000; - const load = vi.fn(async (k: string) => `${k}@${clock}`); - const cache = createSingleFlightCache({ ttlMs: 100, load, now: () => clock }); + it('caches within the TTL and reloads once expired', async () => { + let clock = 1000; + const load = vi.fn(async (k: string) => `${k}@${clock}`); + const cache = createSingleFlightCache({ + ttlMs: 100, + load, + now: () => clock, + }); - expect(await cache.get('a')).toBe('a@1000'); - clock = 1050; // still fresh (< 100) - expect(await cache.get('a')).toBe('a@1000'); - expect(load).toHaveBeenCalledTimes(1); + expect(await cache.get('a')).toBe('a@1000'); + clock = 1050; // still fresh (< 100) + expect(await cache.get('a')).toBe('a@1000'); + expect(load).toHaveBeenCalledTimes(1); - clock = 1101; // 101ms since store → expired - expect(await cache.get('a')).toBe('a@1101'); - expect(load).toHaveBeenCalledTimes(2); - }); - - it('de-dupes concurrent callers onto a single load (single-flight)', async () => { - const d = deferred(); - const load = vi.fn(() => d.promise); - const cache = createSingleFlightCache({ ttlMs: 1000, load }); - - const p1 = cache.get('k'); - const p2 = cache.get('k'); - const p3 = cache.get('k'); - expect(load).toHaveBeenCalledTimes(1); // only one load in flight - - d.resolve('v'); - expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']); - expect(load).toHaveBeenCalledTimes(1); - }); - - it('keys independently — different keys load separately', async () => { - const load = vi.fn(async (k: number) => k * 2); - const cache = createSingleFlightCache({ ttlMs: 1000, load }); - expect(await cache.get(1)).toBe(2); - expect(await cache.get(2)).toBe(4); - expect(load).toHaveBeenCalledTimes(2); - }); - - it('force bypasses the freshness check but still joins an in-flight load', async () => { - let clock = 0; - const load = vi.fn(async (k: string) => `${k}@${clock}`); - const cache = createSingleFlightCache({ ttlMs: 10_000, load, now: () => clock }); - - expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh - clock = 5; // still fresh - expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh - expect(load).toHaveBeenCalledTimes(2); - - // force still single-flights: two concurrent forced gets share one load. - const d = deferred(); - load.mockImplementationOnce(() => d.promise); - const p1 = cache.get('a', { force: true }); - const p2 = cache.get('a', { force: true }); - expect(load).toHaveBeenCalledTimes(3); // not 4 - d.resolve('shared'); - expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']); - }); - - it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => { - let n = 0; - const load = vi.fn(async () => ({ error: true as boolean, n: ++n })); - const cache = createSingleFlightCache({ ttlMs: 10_000, load, shouldCache: (v) => !v.error }); - - // concurrent callers still share one load... - const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]); - expect(a).toEqual({ error: true, n: 1 }); - expect(b).toEqual({ error: true, n: 1 }); - expect(load).toHaveBeenCalledTimes(1); - - // ...but nothing was cached, so the next call reloads. - expect(await cache.get('k')).toEqual({ error: true, n: 2 }); - expect(load).toHaveBeenCalledTimes(2); - - // a good result IS cached. - load.mockImplementationOnce(async () => ({ error: false, n: ++n })); - const good = await cache.get('k'); - expect(good).toEqual({ error: false, n: 3 }); - expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache - expect(load).toHaveBeenCalledTimes(3); - }); - - it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => { - let attempt = 0; - const load = vi.fn(async () => { - attempt++; - if (attempt === 1) throw new Error('boom'); - return 'ok'; + clock = 1101; // 101ms since store → expired + expect(await cache.get('a')).toBe('a@1101'); + expect(load).toHaveBeenCalledTimes(2); }); - const cache = createSingleFlightCache({ ttlMs: 10_000, load }); - const p1 = cache.get('k'); - const p2 = cache.get('k'); - await expect(p1).rejects.toThrow('boom'); - await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection - expect(load).toHaveBeenCalledTimes(1); + it('de-dupes concurrent callers onto a single load (single-flight)', async () => { + const d = deferred(); + const load = vi.fn(() => d.promise); + const cache = createSingleFlightCache({ ttlMs: 1000, load }); - // in-flight cleared + not cached → next call retries and succeeds. - expect(await cache.get('k')).toBe('ok'); - expect(load).toHaveBeenCalledTimes(2); - }); + const p1 = cache.get('k'); + const p2 = cache.get('k'); + const p3 = cache.get('k'); + expect(load).toHaveBeenCalledTimes(1); // only one load in flight - it('invalidate drops a cached entry; clear drops all', async () => { - const load = vi.fn(async (k: string) => k.toUpperCase()); - const cache = createSingleFlightCache({ ttlMs: 10_000, load }); - await cache.get('a'); - await cache.get('b'); - expect(load).toHaveBeenCalledTimes(2); + d.resolve('v'); + expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']); + expect(load).toHaveBeenCalledTimes(1); + }); - cache.invalidate('a'); - await cache.get('a'); // reloads - await cache.get('b'); // still cached - expect(load).toHaveBeenCalledTimes(3); + it('keys independently — different keys load separately', async () => { + const load = vi.fn(async (k: number) => k * 2); + const cache = createSingleFlightCache({ ttlMs: 1000, load }); + expect(await cache.get(1)).toBe(2); + expect(await cache.get(2)).toBe(4); + expect(load).toHaveBeenCalledTimes(2); + }); - cache.clear(); - await cache.get('a'); - await cache.get('b'); - expect(load).toHaveBeenCalledTimes(5); - }); + it('force bypasses the freshness check but still joins an in-flight load', async () => { + let clock = 0; + const load = vi.fn(async (k: string) => `${k}@${clock}`); + const cache = createSingleFlightCache({ + ttlMs: 10_000, + load, + now: () => clock, + }); + + expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh + clock = 5; // still fresh + expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh + expect(load).toHaveBeenCalledTimes(2); + + // force still single-flights: two concurrent forced gets share one load. + const d = deferred(); + load.mockImplementationOnce(() => d.promise); + const p1 = cache.get('a', { force: true }); + const p2 = cache.get('a', { force: true }); + expect(load).toHaveBeenCalledTimes(3); // not 4 + d.resolve('shared'); + expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']); + }); + + it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => { + let n = 0; + const load = vi.fn(async () => ({ error: true as boolean, n: ++n })); + const cache = createSingleFlightCache({ + ttlMs: 10_000, + load, + shouldCache: (v) => !v.error, + }); + + // concurrent callers still share one load... + const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]); + expect(a).toEqual({ error: true, n: 1 }); + expect(b).toEqual({ error: true, n: 1 }); + expect(load).toHaveBeenCalledTimes(1); + + // ...but nothing was cached, so the next call reloads. + expect(await cache.get('k')).toEqual({ error: true, n: 2 }); + expect(load).toHaveBeenCalledTimes(2); + + // a good result IS cached. + load.mockImplementationOnce(async () => ({ error: false, n: ++n })); + const good = await cache.get('k'); + expect(good).toEqual({ error: false, n: 3 }); + expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache + expect(load).toHaveBeenCalledTimes(3); + }); + + it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => { + let attempt = 0; + const load = vi.fn(async () => { + attempt++; + + if (attempt === 1) { + throw new Error('boom'); + } + + return 'ok'; + }); + const cache = createSingleFlightCache({ ttlMs: 10_000, load }); + + const p1 = cache.get('k'); + const p2 = cache.get('k'); + await expect(p1).rejects.toThrow('boom'); + await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection + expect(load).toHaveBeenCalledTimes(1); + + // in-flight cleared + not cached → next call retries and succeeds. + expect(await cache.get('k')).toBe('ok'); + expect(load).toHaveBeenCalledTimes(2); + }); + + it('invalidate drops a cached entry; clear drops all', async () => { + const load = vi.fn(async (k: string) => k.toUpperCase()); + const cache = createSingleFlightCache({ ttlMs: 10_000, load }); + await cache.get('a'); + await cache.get('b'); + expect(load).toHaveBeenCalledTimes(2); + + cache.invalidate('a'); + await cache.get('a'); // reloads + await cache.get('b'); // still cached + expect(load).toHaveBeenCalledTimes(3); + + cache.clear(); + await cache.get('a'); + await cache.get('b'); + expect(load).toHaveBeenCalledTimes(5); + }); }); diff --git a/packages/common/tests/trace-contract.test.ts b/packages/common/tests/trace-contract.test.ts index acf0c883..074c37aa 100644 --- a/packages/common/tests/trace-contract.test.ts +++ b/packages/common/tests/trace-contract.test.ts @@ -1,117 +1,117 @@ import { afterEach, describe, expect, it } from 'vitest'; import { - createLogger, - currentRequestId, - getLogLevel, - nextRequestId, - renderTraceBytes, - runWithoutRequestContext, - runWithRequestId, - runWithTraceRequest, - setLogLevel, + createLogger, + currentRequestId, + getLogLevel, + nextRequestId, + renderTraceBytes, + runWithoutRequestContext, + runWithRequestId, + runWithTraceRequest, + setLogLevel, } from '../src/logger'; const originalLevel = getLogLevel(); afterEach(() => { - setLogLevel(originalLevel); + setLogLevel(originalLevel); }); describe('TRACE diagnostics contract', () => { - it('renders every byte as continuous lowercase hexadecimal', () => { - expect(renderTraceBytes(new Uint8Array())).toBe(''); - expect(renderTraceBytes(new Uint8Array([0x00, 0x01, 0x0f, 0x10, 0xff]))) - .toBe('00010f10ff'); - }); - - it('renders only the addressed Uint8Array view', () => { - const backing = new Uint8Array([0xaa, 0x00, 0x0f, 0xff, 0xbb]); - - expect(renderTraceBytes(backing.subarray(1, 4))).toBe('000fff'); - expect(renderTraceBytes(Buffer.from(backing.buffer).subarray(2, 4))).toBe('0fff'); - }); - - it('does not render bytes while TRACE is disabled', () => { - setLogLevel('info'); - let rendered = false; - - createLogger('Trace.Contract').trace(() => { - rendered = true; - return ['body=%s', renderTraceBytes(new Uint8Array([0xff]))]; + it('renders every byte as continuous lowercase hexadecimal', () => { + expect(renderTraceBytes(new Uint8Array())).toBe(''); + expect(renderTraceBytes(new Uint8Array([0x00, 0x01, 0x0f, 0x10, 0xff]))).toBe('00010f10ff'); }); - expect(rendered).toBe(false); - }); + it('renders only the addressed Uint8Array view', () => { + const backing = new Uint8Array([0xaa, 0x00, 0x0f, 0xff, 0xbb]); - it('creates distinct request contexts that survive asynchronous work', async () => { - setLogLevel('info'); - const beforeDisabled = nextRequestId(); - expect(runWithTraceRequest(() => currentRequestId())).toBeUndefined(); - const afterDisabled = nextRequestId(); - expect(afterDisabled).toBe(beforeDisabled + 1); - - setLogLevel('trace'); - const observeContext = () => runWithTraceRequest(async () => { - const before = currentRequestId(); - await Promise.resolve(); - const after = currentRequestId(); - expect(after).toBe(before); - return after; + expect(renderTraceBytes(backing.subarray(1, 4))).toBe('000fff'); + expect(renderTraceBytes(Buffer.from(backing.buffer).subarray(2, 4))).toBe('0fff'); }); - const first = await observeContext(); - expect(currentRequestId()).toBeUndefined(); - const second = await observeContext(); - expect(currentRequestId()).toBeUndefined(); + it('does not render bytes while TRACE is disabled', () => { + setLogLevel('info'); + let rendered = false; - expect(first).toEqual(expect.any(Number)); - expect(first).toBeGreaterThan(0); - expect(second).toEqual(expect.any(Number)); - expect(second).toBeGreaterThan(0); - expect(second).not.toBe(first); - }); + createLogger('Trace.Contract').trace(() => { + rendered = true; + return ['body=%s', renderTraceBytes(new Uint8Array([0xff]))]; + }); - it('allocates once for nested TRACE contexts and reuses the request id', () => { - setLogLevel('trace'); - const before = nextRequestId(); - - const observed = runWithTraceRequest(() => { - const outer = currentRequestId(); - const inner = runWithTraceRequest(() => currentRequestId()); - return { outer, inner }; + expect(rendered).toBe(false); }); - const after = nextRequestId(); - expect(observed.outer).toEqual(expect.any(Number)); - expect(observed.inner).toBe(observed.outer); - expect(observed.outer).toBe(before + 1); - expect(after).toBe(before + 2); - expect(currentRequestId()).toBeUndefined(); - }); + it('creates distinct request contexts that survive asynchronous work', async () => { + setLogLevel('info'); + const beforeDisabled = nextRequestId(); + expect(runWithTraceRequest(() => currentRequestId())).toBeUndefined(); + const afterDisabled = nextRequestId(); + expect(afterDisabled).toBe(beforeDisabled + 1); - it('detaches long-lived resources from the current request context', async () => { - await runWithRequestId(4243, async () => { - expect(currentRequestId()).toBe(4243); - const detached = await runWithoutRequestContext(async () => { + setLogLevel('trace'); + const observeContext = () => + runWithTraceRequest(async () => { + const before = currentRequestId(); + await Promise.resolve(); + const after = currentRequestId(); + expect(after).toBe(before); + return after; + }); + + const first = await observeContext(); + expect(currentRequestId()).toBeUndefined(); + const second = await observeContext(); expect(currentRequestId()).toBeUndefined(); - await Promise.resolve(); - return currentRequestId(); - }); - expect(detached).toBeUndefined(); - expect(currentRequestId()).toBe(4243); - }); - expect(currentRequestId()).toBeUndefined(); - }); - it('reuses an existing request context even while TRACE is disabled', async () => { - setLogLevel('info'); - - await runWithRequestId(4242, async () => { - const observed = await runWithTraceRequest(async () => { - await Promise.resolve(); - return currentRequestId(); - }); - expect(observed).toBe(4242); + expect(first).toEqual(expect.any(Number)); + expect(first).toBeGreaterThan(0); + expect(second).toEqual(expect.any(Number)); + expect(second).toBeGreaterThan(0); + expect(second).not.toBe(first); + }); + + it('allocates once for nested TRACE contexts and reuses the request id', () => { + setLogLevel('trace'); + const before = nextRequestId(); + + const observed = runWithTraceRequest(() => { + const outer = currentRequestId(); + const inner = runWithTraceRequest(() => currentRequestId()); + return { outer, inner }; + }); + + const after = nextRequestId(); + expect(observed.outer).toEqual(expect.any(Number)); + expect(observed.inner).toBe(observed.outer); + expect(observed.outer).toBe(before + 1); + expect(after).toBe(before + 2); + expect(currentRequestId()).toBeUndefined(); + }); + + it('detaches long-lived resources from the current request context', async () => { + await runWithRequestId(4243, async () => { + expect(currentRequestId()).toBe(4243); + const detached = await runWithoutRequestContext(async () => { + expect(currentRequestId()).toBeUndefined(); + await Promise.resolve(); + return currentRequestId(); + }); + expect(detached).toBeUndefined(); + expect(currentRequestId()).toBe(4243); + }); + expect(currentRequestId()).toBeUndefined(); + }); + + it('reuses an existing request context even while TRACE is disabled', async () => { + setLogLevel('info'); + + await runWithRequestId(4242, async () => { + const observed = await runWithTraceRequest(async () => { + await Promise.resolve(); + return currentRequestId(); + }); + expect(observed).toBe(4242); + }); }); - }); }); diff --git a/packages/common/tests/uin.test.ts b/packages/common/tests/uin.test.ts index 7e203076..85e089b9 100644 --- a/packages/common/tests/uin.test.ts +++ b/packages/common/tests/uin.test.ts @@ -2,39 +2,39 @@ import { describe, expect, it } from 'vitest'; import { isRealUin } from '../src/uin'; describe('isRealUin', () => { - it('accepts real QQ UINs (5..10 digits)', () => { - expect(isRealUin('10001')).toBe(true); // 5-digit floor - expect(isRealUin('123456789')).toBe(true); - expect(isRealUin('4294967295')).toBe(true); // uint32 max, 10 digits - }); + it('accepts real QQ UINs (5..10 digits)', () => { + expect(isRealUin('10001')).toBe(true); // 5-digit floor + expect(isRealUin('123456789')).toBe(true); + expect(isRealUin('4294967295')).toBe(true); // uint32 max, 10 digits + }); - it('rejects the empty string and "0"', () => { - expect(isRealUin('')).toBe(false); - expect(isRealUin('0')).toBe(false); - }); + it('rejects the empty string and "0"', () => { + expect(isRealUin('')).toBe(false); + expect(isRealUin('0')).toBe(false); + }); - it('rejects too-short UINs (< 5 digits)', () => { - expect(isRealUin('1')).toBe(false); - expect(isRealUin('1234')).toBe(false); - }); + it('rejects too-short UINs (< 5 digits)', () => { + expect(isRealUin('1')).toBe(false); + expect(isRealUin('1234')).toBe(false); + }); - it('rejects the garbage timestamp-shaped UINs from issue #162 (11+ digits)', () => { - expect(isRealUin('1701414379536')).toBe(false); // 13-digit ms timestamp - expect(isRealUin('1614019567632')).toBe(false); - expect(isRealUin('2014024115056')).toBe(false); - expect(isRealUin('12345678901')).toBe(false); // 11 digits — first rejected width - }); + it('rejects the garbage timestamp-shaped UINs from issue #162 (11+ digits)', () => { + expect(isRealUin('1701414379536')).toBe(false); // 13-digit ms timestamp + expect(isRealUin('1614019567632')).toBe(false); + expect(isRealUin('2014024115056')).toBe(false); + expect(isRealUin('12345678901')).toBe(false); // 11 digits — first rejected width + }); - it('rejects non-digit strings (path traversal / injection guards)', () => { - expect(isRealUin('12345a')).toBe(false); - expect(isRealUin('12 345')).toBe(false); - expect(isRealUin('../etc')).toBe(false); - expect(isRealUin('123456\n')).toBe(false); - }); + it('rejects non-digit strings (path traversal / injection guards)', () => { + expect(isRealUin('12345a')).toBe(false); + expect(isRealUin('12 345')).toBe(false); + expect(isRealUin('../etc')).toBe(false); + expect(isRealUin('123456\n')).toBe(false); + }); - it('guarantees a BigInt-safe pure-digit string on accept', () => { - const uin = '123456789'; - expect(isRealUin(uin)).toBe(true); - expect(() => BigInt(uin)).not.toThrow(); - }); + it('guarantees a BigInt-safe pure-digit string on accept', () => { + const uin = '123456789'; + expect(isRealUin(uin)).toBe(true); + expect(() => BigInt(uin)).not.toThrow(); + }); }); diff --git a/packages/common/vitest.config.ts b/packages/common/vitest.config.ts index d807e895..2a4a0dad 100644 --- a/packages/common/vitest.config.ts +++ b/packages/common/vitest.config.ts @@ -3,8 +3,8 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ - test: { - include: ['tests/**/*.test.ts'], - environment: 'node', - }, + test: { + include: ['tests/**/*.test.ts'], + environment: 'node', + }, }); diff --git a/packages/core/src/bridge/apis/collection.ts b/packages/core/src/bridge/apis/collection.ts index fa240f11..17c26d1f 100644 --- a/packages/core/src/bridge/apis/collection.ts +++ b/packages/core/src/bridge/apis/collection.ts @@ -1,28 +1,28 @@ import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey'; -import { - getCollectionList, - type CollectionListResult, -} from '@snowluma/protocol/web/collection'; +import { getCollectionList, type CollectionListResult } from '@snowluma/protocol/web/collection'; import type { BridgeContext } from '../bridge-context'; const COLLECTION_DOMAIN = 'weiyun.com'; /** Read-only access to the account's QQ collection list. */ export class CollectionApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) {} - async list(category = 0, count = 50): Promise { - const { domainPskeyMap } = await GetPskey.invoke(this.ctx, { - domainList: [COLLECTION_DOMAIN], - }); - const pskey = domainPskeyMap.get(COLLECTION_DOMAIN); - if (!pskey) throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`); + async list(category = 0, count = 50): Promise { + const { domainPskeyMap } = await GetPskey.invoke(this.ctx, { + domainList: [COLLECTION_DOMAIN], + }); + const pskey = domainPskeyMap.get(COLLECTION_DOMAIN); - return getCollectionList({ - uin: this.ctx.identity.uin, - pskey, - category, - count, - }); - } + if (!pskey) { + throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`); + } + + return getCollectionList({ + uin: this.ctx.identity.uin, + pskey, + category, + count, + }); + } } diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts index 22c371ab..047712fe 100644 --- a/packages/core/src/bridge/apis/contacts.ts +++ b/packages/core/src/bridge/apis/contacts.ts @@ -1,42 +1,48 @@ import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys'; import { - FetchFriendListPage, - type FriendListPageCategory, - type FriendListPageEntry, + FetchFriendListPage, + type FriendListPageCategory, + type FriendListPageEntry, } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page'; import { FetchGroupDetail } from '@snowluma/protocol/oidb-services/contacts/fetch-group-detail'; import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list'; import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page'; import { - FetchGroupRequests, - FetchGroupRequestsByUid, - groupRequestOperationType, + FetchGroupRequests, + FetchGroupRequestsByUid, + groupRequestOperationType, } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests'; import { - FetchRobotUinRanges, - type RobotUinRange, - type RobotUinRangeSnapshot, + FetchRobotUinRanges, + type RobotUinRange, + type RobotUinRangeSnapshot, } from '@snowluma/protocol/oidb-services/contacts/fetch-robot-uin-ranges'; import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile'; import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid'; import { - fetchQidianCorpInfo as fetchQidianCorpInfoWire, - type QidianCorpInfo, + fetchQidianCorpInfo as fetchQidianCorpInfoWire, + type QidianCorpInfo, } from '@snowluma/protocol/services/qidian/fetch-corp-info'; import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark'; import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark'; -import { SendTuwenArk, type SendTuwenArkParams } from '@snowluma/protocol/oidb-services/contacts/send-tuwen-ark'; +import { + SendTuwenArk, + type SendTuwenArkParams, +} from '@snowluma/protocol/oidb-services/contacts/send-tuwen-ark'; import { SetFriendCategory } from '@snowluma/protocol/oidb-services/contacts/set-friend-category'; import { toHex } from '@snowluma/common/hex'; import { createLogger } from '@snowluma/common/logger'; -import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache'; +import { + createSingleFlightCache, + type SingleFlightCache, +} from '@snowluma/common/single-flight-cache'; import type { - FriendCategoryInfo, - FriendInfo, - GroupMemberInfo, - GroupRequestInfo, - QQGroupInfo, - UserProfileInfo, + FriendCategoryInfo, + FriendInfo, + GroupMemberInfo, + GroupRequestInfo, + QQGroupInfo, + UserProfileInfo, } from '@snowluma/protocol/qq-info'; import type { DownloadRKeyInfo } from '../bridge'; import type { BridgeContext } from '../bridge-context'; @@ -47,491 +53,565 @@ const log = createLogger('Bridge.Contacts'); // JS groupShutupExpireTime): 0 = off, 0xFFFFFFFF = permanent, otherwise unix // seconds. `> 0` is wrong — a leftover past expire still looks "on". function isGroupAllMuted(expireTs?: number, nowSec = Math.floor(Date.now() / 1000)): boolean { - return (expireTs ?? 0) > nowSec; + return (expireTs ?? 0) > nowSec; } interface FriendRoster { - entries: FriendListPageEntry[]; - categories: FriendListPageCategory[]; + entries: FriendListPageEntry[]; + categories: FriendListPageCategory[]; } export interface SetFriendCategoryParams { - uin: number; - categoryId?: number; - categoryName?: string; + uin: number; + categoryId?: number; + categoryName?: string; } export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boolean { - return Number.isInteger(uin) - && uin > 0 - && ranges.some(({ minUin, maxUin }) => uin >= minUin && uin <= maxUin); + return ( + Number.isInteger(uin) && + uin > 0 && + ranges.some(({ minUin, maxUin }) => uin >= minUin && uin <= maxUin) + ); } function normalizeGroupRequestSequence( - rawSequence: bigint | number | undefined, - groupId: number, + rawSequence: bigint | number | undefined, + groupId: number, ): number { - const sequence = Number(rawSequence ?? 0); - if (!Number.isSafeInteger(sequence) || sequence <= 0) { - throw new Error( - `invalid group-request sequence: group=${groupId} sequence=${String(rawSequence ?? 0)}`, - ); - } - return sequence; + const sequence = Number(rawSequence ?? 0); + + if (!Number.isSafeInteger(sequence) || sequence <= 0) { + throw new Error( + `invalid group-request sequence: group=${groupId} sequence=${String(rawSequence ?? 0)}`, + ); + } + + return sequence; } const MEMBER_LIST_TTL_MS = 60_000; export class ContactsApi { - /** - * Per-group TTL + single-flight cache for `fetchGroupMemberList`, keyed by - * groupId, living for the lifetime of the Bridge. - * - * Without this, a busy OneBot client (e.g. MaiBot calling - * `get_group_member_info` once per inbound message) triggers one - * OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips - * Tencent risk-control and gets the account banned for 7 days. - */ - private readonly memberListCache: SingleFlightCache = - createSingleFlightCache({ - ttlMs: MEMBER_LIST_TTL_MS, - load: (groupId) => this.fetchGroupMemberListUncached(groupId), - }); - private robotUinRangesPromise_: Promise | null = null; - /** groupUin → approval msgseq from a private qun.invite card. Written - * only by IncomingPacketPipeline (and tests). OneBot reads get/find. */ - private readonly groupInviteCardSeqs_ = new Map(); - - constructor(private readonly ctx: BridgeContext) { } - - private fetchRobotUinRanges(groupId: number): Promise { - if (this.robotUinRangesPromise_) return this.robotUinRangesPromise_; - - const pending = FetchRobotUinRanges.invoke(this.ctx).then((snapshot) => { - log.info( - 'loaded robot UIN ranges uin=%s version=%d count=%d', - this.ctx.identity.uin, - snapshot.version, - snapshot.ranges.length, - ); - return snapshot; - }); - this.robotUinRangesPromise_ = pending; - - // A failed first load must be observable and retryable. Keep the rejection - // visible to the caller instead of converting every member to false. - void pending.catch((err: unknown) => { - if (this.robotUinRangesPromise_ === pending) this.robotUinRangesPromise_ = null; - log.error( - 'failed to load robot UIN ranges: uin=%s group=%d err=%s', - this.ctx.identity.uin, - groupId, - err instanceof Error ? (err.stack ?? err.message) : String(err), - ); - }); - return pending; - } - - /** Server-built ARK share card (JSON string) recommending a friend. */ - getBuddyRecommendArk(userId: number, phoneNumber = ''): Promise { - return GetBuddyRecommendArk.invoke(this.ctx, { userId, phoneNumber }); - } - - /** Server-built ARK share card (JSON string) recommending a group. */ - getGroupRecommendArk(groupId: number): Promise { - return GetGroupRecommendArk.invoke(this.ctx, { groupId }); - } - - /** Send a custom 图文 ark card to a C2C peer or group (0xdc2_34). */ - sendTuwenArk(params: SendTuwenArkParams): Promise { - return SendTuwenArk.invoke(this.ctx, params); - } - - private async fetchFriendRoster(): Promise { - const entries: FriendListPageEntry[] = []; - const categories = new Map(); - const seenCookies = new Set(); - let cookie: Uint8Array | undefined; - - for (;;) { - const page = await FetchFriendListPage.invoke(this.ctx, { cookie }); - entries.push(...page.entries); - for (const category of page.categories) { - categories.set(category.categoryId, category); - } - - const next = page.cookie; - if (!next?.length) break; - const key = toHex(next); - if (seenCookies.has(key)) { - throw new Error(`repeated friend-list cookie ${key}`); - } - seenCookies.add(key); - cookie = next; - } - - const friends = entries.map(entry => entry.friend); - this.ctx.identity.rememberFriends(friends); - return { entries, categories: [...categories.values()] }; - } - - async fetchFriendList(): Promise { - const roster = await this.fetchFriendRoster(); - return roster.entries.map(entry => entry.friend); - } - - async fetchFriendCategories(): Promise { - const roster = await this.fetchFriendRoster(); - const buckets = new Map( - roster.categories.map(category => [category.categoryId, [] as FriendInfo[]]), - ); - - for (const entry of roster.entries) { - const bucket = buckets.get(entry.categoryId); - if (!bucket) { - throw new Error( - `friend roster references missing category ${entry.categoryId} ` - + `(${roster.entries.length} friends total)`, - ); - } - bucket.push(entry.friend); - } - - return roster.categories.map(category => { - const friends = buckets.get(category.categoryId)!; - if (friends.length !== category.memberCount) { - log.warn( - 'friend category member count mismatch category=%d server=%d assembled=%d', - category.categoryId, - category.memberCount, - friends.length, - ); - } - return { ...category, friends }; - }); - } - - async setFriendCategory(params: SetFriendCategoryParams): Promise { - const selectorCount = Number(params.categoryId !== undefined) - + Number(params.categoryName !== undefined); - if (selectorCount !== 1) { - throw new Error('exactly one of categoryId or categoryName is required'); - } - const categories = await this.fetchFriendCategories(); - const friendCategory = categories.find(category => - category.friends.some(friend => friend.uin === params.uin)); - const friend = friendCategory?.friends.find(entry => entry.uin === params.uin); - if (!friend) { - throw new Error(`friend ${params.uin} is not in the live roster`); - } - if (!friend.uid) { - throw new Error(`friend ${params.uin} has no UID in the live roster`); - } - - let target: FriendCategoryInfo | undefined; - if (params.categoryId !== undefined) { - target = categories.find(category => category.categoryId === params.categoryId); - if (!target) { - throw new Error(`friend category ${params.categoryId} does not exist`); - } - } else { - const matches = categories.filter(category => category.categoryName === params.categoryName); - if (matches.length === 0) { - throw new Error(`friend category name "${params.categoryName}" does not exist`); - } - if (matches.length > 1) { - throw new Error(`friend category name "${params.categoryName}" is ambiguous`); - } - target = matches[0]!; - } - - await SetFriendCategory.invoke(this.ctx, { - uid: friend.uid, - categoryId: target.categoryId, - }); - log.info( - 'friend category updated: uin=%s friend=%d category=%d', - this.ctx.identity.uin, - params.uin, - target.categoryId, - ); - } - - async fetchGroupList(): Promise { - const resp = await FetchGroupList.invoke(this.ctx); - const groups: QQGroupInfo[] = []; - for (const raw of resp.groups ?? []) { - groups.push({ - groupId: raw.groupUin ?? 0, - groupName: raw.info?.groupName ?? '', - remark: raw.customInfo?.remark ?? '', - memberCount: raw.info?.memberCount ?? 0, - memberMax: raw.info?.memberMax ?? 0, - members: new Map(), - // #197: the list already carries these — no extra fetch needed. `level` - // is not in the list (0x88D_0 detail only), so it stays undefined here. - createTime: raw.info?.createdTime ?? 0, - memo: raw.info?.announcement || raw.info?.description || '', - // #490: expose the description alongside `memo`. QQ fills in either - // field alone, so folding both into `memo` made the description - // unreachable whenever an announcement was also set. - description: raw.info?.description ?? '', - allMuted: isGroupAllMuted(raw.info?.shutUpAllTimestamp), - }); - } - this.ctx.identity.rememberGroups(groups); - return groups; - } - - /** - * Fetch a single group's public detail by id via `0x88D_0` — works even for a - * group the bot hasn't joined (used to resolve a group-invite's name). Returns - * null when the server has no such group / denies the lookup. Deliberately - * does NOT `rememberGroups` it — a non-member group must not pollute the - * joined-groups roster / get_group_list. - */ - async fetchGroupDetail(groupId: number): Promise { - if (!(groupId > 0)) return null; - const resp = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }); - const r = resp.groupInfo?.results; - if (!r) return null; - return { - groupId, - groupName: r.name ?? '', - remark: '', - memberCount: Number(r.memberCount ?? 0n), - memberMax: Number(r.maxMemberCount ?? 0n), - members: new Map(), - // #197: the detail is the only source of `level`; it also carries - // createTime + the notice preview (memo). `description` is deliberately - // left unset — 0x88D_0 has no description tag, so for a group the bot - // hasn't joined there is nothing to report (#490). - createTime: Number(r.createTime ?? 0n), - level: Number(r.level ?? 0n), - memo: r.noticePreview ?? '', - allMuted: isGroupAllMuted(r.shutUpAllTimestamp), - }; - } - - fetchGroupMemberList( - groupId: number, - options: { force?: boolean } = {}, - ): Promise { - return this.memberListCache.get(groupId, { force: options.force }); - } - - private async fetchGroupMemberListUncached(groupId: number): Promise { - // QQ's native group service obtains the robot classification separately - // from 0xFE7_3. Start both reads together so the metadata adds no serial - // round trip to paginated member fetches. - const robotSnapshotPromise = this.fetchRobotUinRanges(groupId); - const members: GroupMemberInfo[] = []; - let token = ''; - do { - const page = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token }); - members.push(...page.members); - token = page.token; - } while (token); - - const robotSnapshot = await robotSnapshotPromise; - for (const member of members) { - member.isRobot = isRobotUin(member.uin, robotSnapshot.ranges); - } - - this.ctx.identity.rememberGroupMembers(groupId, members); - return members; - } - - async fetchUserProfile(uin: number): Promise { - const info = await FetchUserProfile.invoke(this.ctx, { uin }); - this.ctx.identity.rememberUserProfile(info); - return info; - } - - /** Look up a user profile by UID (string form). Used for strangers - * whose UIN we don't have yet — typically the requester on a - * group join request push. Mirrors Lagrange's `FetchUserInfoEvent - * .Create(targetUid)` path. */ - async fetchUserProfileByUid(uid: string): Promise { - const info = await FetchUserProfileByUid.invoke(this.ctx, { uid }); - if (info.uin > 0) this.ctx.identity.rememberUserProfile(info); - return info; - } - - /** 企点企业资料卡(#404 后续 PR)。仅在判断命中的是企点账号后再调用。 - * best-effort:非企点账号或拉取失败返回 null,不影响上层资料读取。 */ - async fetchQidianCorpInfo(uin: number): Promise { - return fetchQidianCorpInfoWire(this.ctx, uin); - } - - async fetchGroupRequests( - filtered = false, - count = 50, - cursor = 0n, - ): Promise { - const resp = await FetchGroupRequests.invoke(this.ctx, { filtered, count, cursor }); - const requests: GroupRequestInfo[] = []; - for (const raw of resp.requests ?? []) { - const groupId = raw.group?.groupUin ?? 0; - const targetUin = raw.target?.uin ?? 0; - const invitorUin = raw.invitor?.uin ?? 0; - const operatorUin = raw.operatorUser?.uin ?? 0; - const targetUid = raw.target?.uid - || this.ctx.identity.findUidByUin(targetUin, groupId) - || this.ctx.identity.findUidByUin(targetUin) - || ''; - const invitorUid = raw.invitor?.uid - || this.ctx.identity.findUidByUin(invitorUin, groupId) - || this.ctx.identity.findUidByUin(invitorUin) - || ''; - const operatorUid = raw.operatorUser?.uid - || this.ctx.identity.findUidByUin(operatorUin, groupId) - || this.ctx.identity.findUidByUin(operatorUin) - || ''; - const notifyType = raw.eventType ?? 0; - const operationType = groupRequestOperationType(notifyType); - const sequence = normalizeGroupRequestSequence(raw.sequence, groupId); - if (operationType === null) { - log.warn( - 'unsupported group-request notification type: group=%d sequence=%s type=%d', - groupId, - String(raw.sequence ?? 0n), - notifyType, - ); - } - requests.push({ - groupId, - groupName: raw.group?.groupName ?? '', - targetUid, - targetUin: targetUin - || this.ctx.identity.findUinByUid(targetUid, groupId) - || this.ctx.identity.findUinByUid(targetUid) - || 0, - targetName: raw.target?.name ?? '', - invitorUid, - invitorUin: invitorUin - || this.ctx.identity.findUinByUid(invitorUid, groupId) - || this.ctx.identity.findUinByUid(invitorUid) - || 0, - invitorName: raw.invitor?.name ?? '', - operatorUid, - operatorUin: operatorUin - || this.ctx.identity.findUinByUid(operatorUid, groupId) - || this.ctx.identity.findUinByUid(operatorUid) - || 0, - operatorName: raw.operatorUser?.name ?? '', - sequence, - state: raw.state ?? 0, - notifyType, - eventType: operationType ?? 0, - comment: raw.comment ?? '', - filtered, - operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0 - ? raw.operateTransInfo - : undefined, - }); - } - this.ctx.identity.rememberGroupRequests(requests); - return requests; - } - - /** UID-form request list retained for correlating incoming UID-only pushes. - * Explicit list/actions use fetchGroupRequests(), which matches QQ's native - * numeric-account path and does not need profile lookups. */ - async fetchGroupRequestsByUid( - filtered = false, - count = 50, - cursor = 0n, - ): Promise { - const resp = await FetchGroupRequestsByUid.invoke(this.ctx, { filtered, count, cursor }); - const requests: GroupRequestInfo[] = []; - for (const raw of resp.requests ?? []) { - const groupId = raw.group?.groupUin ?? 0; - const targetUid = raw.target?.uid ?? ''; - const invitorUid = raw.invitor?.uid ?? ''; - const operatorUid = raw.operatorUser?.uid ?? ''; - const notifyType = raw.eventType ?? 0; - const operationType = groupRequestOperationType(notifyType); - const sequence = normalizeGroupRequestSequence(raw.sequence, groupId); - if (operationType === null) { - log.warn( - 'unsupported group-request notification type: group=%d sequence=%s type=%d', - groupId, - String(raw.sequence ?? 0n), - notifyType, - ); - } - requests.push({ - groupId, - groupName: raw.group?.groupName ?? '', - targetUid, - targetUin: this.ctx.identity.findUinByUid(targetUid, groupId) - ?? this.ctx.identity.findUinByUid(targetUid) - ?? 0, - targetName: raw.target?.name ?? '', - invitorUid, - invitorUin: this.ctx.identity.findUinByUid(invitorUid, groupId) - ?? this.ctx.identity.findUinByUid(invitorUid) - ?? 0, - invitorName: raw.invitor?.name ?? '', - operatorUid, - operatorUin: this.ctx.identity.findUinByUid(operatorUid, groupId) - ?? this.ctx.identity.findUinByUid(operatorUid) - ?? 0, - operatorName: raw.operatorUser?.name ?? '', - sequence, - state: raw.state ?? 0, - notifyType, - eventType: operationType ?? 0, - comment: raw.comment ?? '', - filtered, - operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0 - ? raw.operateTransInfo - : undefined, - }); - } - this.ctx.identity.rememberGroupRequests(requests); - return requests; - } - - /** Live observation write. IncomingPacketPipeline and tests only. */ - rememberGroupInviteCardSequence(groupUin: number, sequence: number): void { - if (groupUin > 0 && sequence > 0) this.groupInviteCardSeqs_.set(groupUin, sequence); - } - - /** The approval msgseq captured from a private "qun.invite" card for this - * group, or undefined if none was seen. `set_group_add_request` uses it to - * approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */ - getGroupInviteCardSequence(groupId: number): number | undefined { - return this.groupInviteCardSeqs_.get(groupId); - } - - /** Resolve the group for a private invite-card msgseq. Numeric OneBot flags - * use this path because the card sequence is absent from 0x10C0. */ - findGroupInviteCardGroupBySequence(sequence: number): number | undefined { - for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) { - if (rememberedSequence === sequence) return groupUin; - } - return undefined; - } - - async fetchDownloadRKeys(): Promise { - const resp = await FetchDownloadRkeys.invoke(this.ctx); - - const result: DownloadRKeyInfo[] = []; - for (const entry of resp.downloadRkey?.rkeys ?? []) { - const rkey = entry.rkey ?? ''; - const type = entry.type ?? 0; - if (rkey && type) { - result.push({ - rkey, - ttlSeconds: Number(entry.rkeyTtlSec ?? 0), - storeId: entry.storeId ?? 0, - createTime: entry.rkeyCreateTime ?? 0, - type, + /** + * Per-group TTL + single-flight cache for `fetchGroupMemberList`, keyed by + * groupId, living for the lifetime of the Bridge. + * + * Without this, a busy OneBot client (e.g. MaiBot calling + * `get_group_member_info` once per inbound message) triggers one + * OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips + * Tencent risk-control and gets the account banned for 7 days. + */ + private readonly memberListCache: SingleFlightCache = + createSingleFlightCache({ + ttlMs: MEMBER_LIST_TTL_MS, + load: (groupId) => this.fetchGroupMemberListUncached(groupId), }); - } + private robotUinRangesPromise_: Promise | null = null; + /** groupUin → approval msgseq from a private qun.invite card. Written + * only by IncomingPacketPipeline (and tests). OneBot reads get/find. */ + private readonly groupInviteCardSeqs_ = new Map(); + + constructor(private readonly ctx: BridgeContext) {} + + private fetchRobotUinRanges(groupId: number): Promise { + if (this.robotUinRangesPromise_) { + return this.robotUinRangesPromise_; + } + + const pending = FetchRobotUinRanges.invoke(this.ctx).then((snapshot) => { + log.info( + 'loaded robot UIN ranges uin=%s version=%d count=%d', + this.ctx.identity.uin, + snapshot.version, + snapshot.ranges.length, + ); + return snapshot; + }); + this.robotUinRangesPromise_ = pending; + + // A failed first load must be observable and retryable. Keep the rejection + // visible to the caller instead of converting every member to false. + void pending.catch((err: unknown) => { + if (this.robotUinRangesPromise_ === pending) { + this.robotUinRangesPromise_ = null; + } + + log.error( + 'failed to load robot UIN ranges: uin=%s group=%d err=%s', + this.ctx.identity.uin, + groupId, + err instanceof Error ? (err.stack ?? err.message) : String(err), + ); + }); + return pending; + } + + /** Server-built ARK share card (JSON string) recommending a friend. */ + getBuddyRecommendArk(userId: number, phoneNumber = ''): Promise { + return GetBuddyRecommendArk.invoke(this.ctx, { userId, phoneNumber }); + } + + /** Server-built ARK share card (JSON string) recommending a group. */ + getGroupRecommendArk(groupId: number): Promise { + return GetGroupRecommendArk.invoke(this.ctx, { groupId }); + } + + /** Send a custom 图文 ark card to a C2C peer or group (0xdc2_34). */ + sendTuwenArk(params: SendTuwenArkParams): Promise { + return SendTuwenArk.invoke(this.ctx, params); + } + + private async fetchFriendRoster(): Promise { + const entries: FriendListPageEntry[] = []; + const categories = new Map(); + const seenCookies = new Set(); + let cookie: Uint8Array | undefined; + + for (;;) { + const page = await FetchFriendListPage.invoke(this.ctx, { cookie }); + entries.push(...page.entries); + + for (const category of page.categories) { + categories.set(category.categoryId, category); + } + + const next = page.cookie; + + if (!next?.length) { + break; + } + + const key = toHex(next); + + if (seenCookies.has(key)) { + throw new Error(`repeated friend-list cookie ${key}`); + } + + seenCookies.add(key); + cookie = next; + } + + const friends = entries.map((entry) => entry.friend); + this.ctx.identity.rememberFriends(friends); + return { entries, categories: [...categories.values()] }; + } + + async fetchFriendList(): Promise { + const roster = await this.fetchFriendRoster(); + return roster.entries.map((entry) => entry.friend); + } + + async fetchFriendCategories(): Promise { + const roster = await this.fetchFriendRoster(); + const buckets = new Map( + roster.categories.map((category) => [category.categoryId, [] as FriendInfo[]]), + ); + + for (const entry of roster.entries) { + const bucket = buckets.get(entry.categoryId); + + if (!bucket) { + throw new Error( + `friend roster references missing category ${entry.categoryId} ` + + `(${roster.entries.length} friends total)`, + ); + } + + bucket.push(entry.friend); + } + + return roster.categories.map((category) => { + const friends = buckets.get(category.categoryId)!; + + if (friends.length !== category.memberCount) { + log.warn( + 'friend category member count mismatch category=%d server=%d assembled=%d', + category.categoryId, + category.memberCount, + friends.length, + ); + } + + return { ...category, friends }; + }); + } + + async setFriendCategory(params: SetFriendCategoryParams): Promise { + const selectorCount = + Number(params.categoryId !== undefined) + Number(params.categoryName !== undefined); + + if (selectorCount !== 1) { + throw new Error('exactly one of categoryId or categoryName is required'); + } + + const categories = await this.fetchFriendCategories(); + const friendCategory = categories.find((category) => + category.friends.some((friend) => friend.uin === params.uin), + ); + const friend = friendCategory?.friends.find((entry) => entry.uin === params.uin); + + if (!friend) { + throw new Error(`friend ${params.uin} is not in the live roster`); + } + + if (!friend.uid) { + throw new Error(`friend ${params.uin} has no UID in the live roster`); + } + + let target: FriendCategoryInfo | undefined; + + if (params.categoryId !== undefined) { + target = categories.find((category) => category.categoryId === params.categoryId); + + if (!target) { + throw new Error(`friend category ${params.categoryId} does not exist`); + } + } else { + const matches = categories.filter( + (category) => category.categoryName === params.categoryName, + ); + + if (matches.length === 0) { + throw new Error(`friend category name "${params.categoryName}" does not exist`); + } + + if (matches.length > 1) { + throw new Error(`friend category name "${params.categoryName}" is ambiguous`); + } + + target = matches[0]!; + } + + await SetFriendCategory.invoke(this.ctx, { + uid: friend.uid, + categoryId: target.categoryId, + }); + log.info( + 'friend category updated: uin=%s friend=%d category=%d', + this.ctx.identity.uin, + params.uin, + target.categoryId, + ); + } + + async fetchGroupList(): Promise { + const resp = await FetchGroupList.invoke(this.ctx); + const groups: QQGroupInfo[] = []; + + for (const raw of resp.groups ?? []) { + groups.push({ + groupId: raw.groupUin ?? 0, + groupName: raw.info?.groupName ?? '', + remark: raw.customInfo?.remark ?? '', + memberCount: raw.info?.memberCount ?? 0, + memberMax: raw.info?.memberMax ?? 0, + members: new Map(), + // #197: the list already carries these — no extra fetch needed. `level` + // is not in the list (0x88D_0 detail only), so it stays undefined here. + createTime: raw.info?.createdTime ?? 0, + memo: raw.info?.announcement || raw.info?.description || '', + // #490: expose the description alongside `memo`. QQ fills in either + // field alone, so folding both into `memo` made the description + // unreachable whenever an announcement was also set. + description: raw.info?.description ?? '', + allMuted: isGroupAllMuted(raw.info?.shutUpAllTimestamp), + }); + } + + this.ctx.identity.rememberGroups(groups); + return groups; + } + + /** + * Fetch a single group's public detail by id via `0x88D_0` — works even for a + * group the bot hasn't joined (used to resolve a group-invite's name). Returns + * null when the server has no such group / denies the lookup. Deliberately + * does NOT `rememberGroups` it — a non-member group must not pollute the + * joined-groups roster / get_group_list. + */ + async fetchGroupDetail(groupId: number): Promise { + if (!(groupId > 0)) { + return null; + } + + const resp = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }); + const r = resp.groupInfo?.results; + + if (!r) { + return null; + } + + return { + groupId, + groupName: r.name ?? '', + remark: '', + memberCount: Number(r.memberCount ?? 0n), + memberMax: Number(r.maxMemberCount ?? 0n), + members: new Map(), + // #197: the detail is the only source of `level`; it also carries + // createTime + the notice preview (memo). `description` is deliberately + // left unset — 0x88D_0 has no description tag, so for a group the bot + // hasn't joined there is nothing to report (#490). + createTime: Number(r.createTime ?? 0n), + level: Number(r.level ?? 0n), + memo: r.noticePreview ?? '', + allMuted: isGroupAllMuted(r.shutUpAllTimestamp), + }; + } + + fetchGroupMemberList( + groupId: number, + options: { force?: boolean } = {}, + ): Promise { + return this.memberListCache.get(groupId, { force: options.force }); + } + + private async fetchGroupMemberListUncached(groupId: number): Promise { + // QQ's native group service obtains the robot classification separately + // from 0xFE7_3. Start both reads together so the metadata adds no serial + // round trip to paginated member fetches. + const robotSnapshotPromise = this.fetchRobotUinRanges(groupId); + const members: GroupMemberInfo[] = []; + let token = ''; + + do { + const page = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token }); + members.push(...page.members); + token = page.token; + } while (token); + + const robotSnapshot = await robotSnapshotPromise; + + for (const member of members) { + member.isRobot = isRobotUin(member.uin, robotSnapshot.ranges); + } + + this.ctx.identity.rememberGroupMembers(groupId, members); + return members; + } + + async fetchUserProfile(uin: number): Promise { + const info = await FetchUserProfile.invoke(this.ctx, { uin }); + this.ctx.identity.rememberUserProfile(info); + return info; + } + + /** Look up a user profile by UID (string form). Used for strangers + * whose UIN we don't have yet — typically the requester on a + * group join request push. Mirrors Lagrange's `FetchUserInfoEvent + * .Create(targetUid)` path. */ + async fetchUserProfileByUid(uid: string): Promise { + const info = await FetchUserProfileByUid.invoke(this.ctx, { uid }); + + if (info.uin > 0) { + this.ctx.identity.rememberUserProfile(info); + } + + return info; + } + + /** 企点企业资料卡(#404 后续 PR)。仅在判断命中的是企点账号后再调用。 + * best-effort:非企点账号或拉取失败返回 null,不影响上层资料读取。 */ + async fetchQidianCorpInfo(uin: number): Promise { + return fetchQidianCorpInfoWire(this.ctx, uin); + } + + async fetchGroupRequests( + filtered = false, + count = 50, + cursor = 0n, + ): Promise { + const resp = await FetchGroupRequests.invoke(this.ctx, { filtered, count, cursor }); + const requests: GroupRequestInfo[] = []; + + for (const raw of resp.requests ?? []) { + const groupId = raw.group?.groupUin ?? 0; + const targetUin = raw.target?.uin ?? 0; + const invitorUin = raw.invitor?.uin ?? 0; + const operatorUin = raw.operatorUser?.uin ?? 0; + const targetUid = + raw.target?.uid || + this.ctx.identity.findUidByUin(targetUin, groupId) || + this.ctx.identity.findUidByUin(targetUin) || + ''; + const invitorUid = + raw.invitor?.uid || + this.ctx.identity.findUidByUin(invitorUin, groupId) || + this.ctx.identity.findUidByUin(invitorUin) || + ''; + const operatorUid = + raw.operatorUser?.uid || + this.ctx.identity.findUidByUin(operatorUin, groupId) || + this.ctx.identity.findUidByUin(operatorUin) || + ''; + const notifyType = raw.eventType ?? 0; + const operationType = groupRequestOperationType(notifyType); + const sequence = normalizeGroupRequestSequence(raw.sequence, groupId); + + if (operationType === null) { + log.warn( + 'unsupported group-request notification type: group=%d sequence=%s type=%d', + groupId, + String(raw.sequence ?? 0n), + notifyType, + ); + } + + requests.push({ + groupId, + groupName: raw.group?.groupName ?? '', + targetUid, + targetUin: + targetUin || + this.ctx.identity.findUinByUid(targetUid, groupId) || + this.ctx.identity.findUinByUid(targetUid) || + 0, + targetName: raw.target?.name ?? '', + invitorUid, + invitorUin: + invitorUin || + this.ctx.identity.findUinByUid(invitorUid, groupId) || + this.ctx.identity.findUinByUid(invitorUid) || + 0, + invitorName: raw.invitor?.name ?? '', + operatorUid, + operatorUin: + operatorUin || + this.ctx.identity.findUinByUid(operatorUid, groupId) || + this.ctx.identity.findUinByUid(operatorUid) || + 0, + operatorName: raw.operatorUser?.name ?? '', + sequence, + state: raw.state ?? 0, + notifyType, + eventType: operationType ?? 0, + comment: raw.comment ?? '', + filtered, + operateTransInfo: + raw.operateTransInfo && raw.operateTransInfo.length > 0 + ? raw.operateTransInfo + : undefined, + }); + } + + this.ctx.identity.rememberGroupRequests(requests); + return requests; + } + + /** UID-form request list retained for correlating incoming UID-only pushes. + * Explicit list/actions use fetchGroupRequests(), which matches QQ's native + * numeric-account path and does not need profile lookups. */ + async fetchGroupRequestsByUid( + filtered = false, + count = 50, + cursor = 0n, + ): Promise { + const resp = await FetchGroupRequestsByUid.invoke(this.ctx, { filtered, count, cursor }); + const requests: GroupRequestInfo[] = []; + + for (const raw of resp.requests ?? []) { + const groupId = raw.group?.groupUin ?? 0; + const targetUid = raw.target?.uid ?? ''; + const invitorUid = raw.invitor?.uid ?? ''; + const operatorUid = raw.operatorUser?.uid ?? ''; + const notifyType = raw.eventType ?? 0; + const operationType = groupRequestOperationType(notifyType); + const sequence = normalizeGroupRequestSequence(raw.sequence, groupId); + + if (operationType === null) { + log.warn( + 'unsupported group-request notification type: group=%d sequence=%s type=%d', + groupId, + String(raw.sequence ?? 0n), + notifyType, + ); + } + + requests.push({ + groupId, + groupName: raw.group?.groupName ?? '', + targetUid, + targetUin: + this.ctx.identity.findUinByUid(targetUid, groupId) ?? + this.ctx.identity.findUinByUid(targetUid) ?? + 0, + targetName: raw.target?.name ?? '', + invitorUid, + invitorUin: + this.ctx.identity.findUinByUid(invitorUid, groupId) ?? + this.ctx.identity.findUinByUid(invitorUid) ?? + 0, + invitorName: raw.invitor?.name ?? '', + operatorUid, + operatorUin: + this.ctx.identity.findUinByUid(operatorUid, groupId) ?? + this.ctx.identity.findUinByUid(operatorUid) ?? + 0, + operatorName: raw.operatorUser?.name ?? '', + sequence, + state: raw.state ?? 0, + notifyType, + eventType: operationType ?? 0, + comment: raw.comment ?? '', + filtered, + operateTransInfo: + raw.operateTransInfo && raw.operateTransInfo.length > 0 + ? raw.operateTransInfo + : undefined, + }); + } + + this.ctx.identity.rememberGroupRequests(requests); + return requests; + } + + /** Live observation write. IncomingPacketPipeline and tests only. */ + rememberGroupInviteCardSequence(groupUin: number, sequence: number): void { + if (groupUin > 0 && sequence > 0) { + this.groupInviteCardSeqs_.set(groupUin, sequence); + } + } + + /** The approval msgseq captured from a private "qun.invite" card for this + * group, or undefined if none was seen. `set_group_add_request` uses it to + * approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */ + getGroupInviteCardSequence(groupId: number): number | undefined { + return this.groupInviteCardSeqs_.get(groupId); + } + + /** Resolve the group for a private invite-card msgseq. Numeric OneBot flags + * use this path because the card sequence is absent from 0x10C0. */ + findGroupInviteCardGroupBySequence(sequence: number): number | undefined { + for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) { + if (rememberedSequence === sequence) { + return groupUin; + } + } + + return undefined; + } + + async fetchDownloadRKeys(): Promise { + const resp = await FetchDownloadRkeys.invoke(this.ctx); + + const result: DownloadRKeyInfo[] = []; + + for (const entry of resp.downloadRkey?.rkeys ?? []) { + const rkey = entry.rkey ?? ''; + const type = entry.type ?? 0; + + if (rkey && type) { + result.push({ + rkey, + ttlSeconds: Number(entry.rkeyTtlSec ?? 0), + storeId: entry.storeId ?? 0, + createTime: entry.rkeyCreateTime ?? 0, + type, + }); + } + } + + return result; } - return result; - } } diff --git a/packages/core/src/bridge/apis/extras.ts b/packages/core/src/bridge/apis/extras.ts index 76da91fb..b4eddfa0 100644 --- a/packages/core/src/bridge/apis/extras.ts +++ b/packages/core/src/bridge/apis/extras.ts @@ -1,12 +1,15 @@ import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice'; import { - FetchAiVoiceList, - type AiVoiceCategory as NamespaceAiVoiceCategory, + FetchAiVoiceList, + type AiVoiceCategory as NamespaceAiVoiceCategory, } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list'; -import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status'; import { - GetGroupTodoList, - type GroupTodoListItem as NamespaceGroupTodoListItem, + GetStrangerStatus, + type StrangerStatus as NamespaceStrangerStatus, +} from '@snowluma/protocol/oidb-services/extras/get-stranger-status'; +import { + GetGroupTodoList, + type GroupTodoListItem as NamespaceGroupTodoListItem, } from '@snowluma/protocol/oidb-services/extras/get-group-todo-list'; import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo'; import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon'; @@ -22,18 +25,18 @@ import type { MediaIndexNode } from './shared'; * element + its message meta. `uuid`/`md5Hex` come from the cached record; * the uins + scene from the message meta. */ export interface PttTransInput { - isGroup: boolean; - msgId: number; - senderUin: number; - /** Receiver uin (c2c) or group uin (group). */ - peerUin: number; - uuid: string; - md5Hex: string; - duration: number; - size: number; - format: number; - /** Group ptt numeric file id (group only; optional). */ - fileId?: number; + isGroup: boolean; + msgId: number; + senderUin: number; + /** Receiver uin (c2c) or group uin (group). */ + peerUin: number; + uuid: string; + md5Hex: string; + duration: number; + size: number; + format: number; + /** Group ptt numeric file id (group only; optional). */ + fileId?: number; } // ─────────────── public types (re-exported from bridge.ts as before) ─── @@ -42,21 +45,21 @@ export type StrangerStatus = NamespaceStrangerStatus; export type GroupTodoListItem = NamespaceGroupTodoListItem; export const AiVoiceChatType = { - Unknown: 0, - Sound: 1, - Sing: 2, + Unknown: 0, + Sound: 1, + Sing: 2, } as const; -export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType]; +export type AiVoiceChatType = (typeof AiVoiceChatType)[keyof typeof AiVoiceChatType]; export type AiVoiceCategory = NamespaceAiVoiceCategory; export interface AiVoiceItem { - voiceId: string; - voiceDisplayName: string; - voiceExampleUrl: string; + voiceId: string; + voiceDisplayName: string; + voiceExampleUrl: string; } export interface AiVoiceSendReceipt { - sequence: number; + sequence: number; } const log = createLogger('Bridge.Extras'); @@ -67,280 +70,368 @@ const AI_VOICE_CLAIM_LIMIT = 256; type GroupMessageEvent = Extract; function normalizeMediaUuid(value: unknown): string { - return typeof value === 'string' ? value.trim() : ''; + return typeof value === 'string' ? value.trim() : ''; } function matchesAiVoiceEvent(node: MediaIndexNode, event: GroupMessageEvent): boolean { - const expectedUuid = normalizeMediaUuid(node.fileUuid); - if (!expectedUuid) return false; - for (const element of event.elements) { - if (element.type !== 'record') continue; - const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId); - if (actualUuid === expectedUuid) return true; - } - return false; + const expectedUuid = normalizeMediaUuid(node.fileUuid); + + if (!expectedUuid) { + return false; + } + + for (const element of event.elements) { + if (element.type !== 'record') { + continue; + } + + const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId); + + if (actualUuid === expectedUuid) { + return true; + } + } + + return false; } function describeAiVoiceFingerprint(node: MediaIndexNode): string { - const uuid = normalizeMediaUuid(node.fileUuid); - if (uuid) return `uuid:${uuid.slice(-12)}`; - return 'missing'; + const uuid = normalizeMediaUuid(node.fileUuid); + + if (uuid) { + return `uuid:${uuid.slice(-12)}`; + } + + return 'missing'; } export class ExtrasApi { - private readonly claimedAiVoiceReceiptKeys = new Set(); + private readonly claimedAiVoiceReceiptKeys = new Set(); - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - // ─────────────── Group todo query / mutations (0x9474 / 0xF90) ─────────────── + // ─────────────── Group todo query / mutations (0x9474 / 0xF90) ─────────────── - async getGroupTodoList(groupId: number): Promise { - const items = await GetGroupTodoList.invoke(this.ctx, { groupId }); - log.debug('group todo list fetched group=%d count=%d', groupId, items.length); - return items; - } - - setGroupTodo(groupId: number, msgSeq: bigint): Promise { - return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' }); - } - - completeGroupTodo(groupId: number, msgSeq: bigint): Promise { - return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' }); - } - - cancelGroupTodo(groupId: number, msgSeq: bigint): Promise { - return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' }); - } - - // ─────────────── Stranger online/ext status (0xFE1_2) ─────────────── - - /** - * Keeps the action response user-safe while retaining the underlying - * failure in the service log for diagnosis. - */ - async getStrangerStatus(uin: number): Promise { - try { - const status = await GetStrangerStatus.invoke(this.ctx, { uin }); - if (!status) log.warn('user status query returned no status target=%d', uin); - return status; - } catch (error) { - log.warn( - 'user status query failed target=%d: %s', - uin, - error instanceof Error ? error.message : String(error), - ); - return null; + async getGroupTodoList(groupId: number): Promise { + const items = await GetGroupTodoList.invoke(this.ctx, { groupId }); + log.debug('group todo list fetched group=%d count=%d', groupId, items.length); + return items; } - } - // ─────────────── AI voice (0x929D / 0x929B) ─────────────── - - fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise { - return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType }); - } - - /** - * Trigger AI voice synthesis. Server may return an empty msgInfo while - * the render is in-flight; we retry until a node materialises or the - * cap is hit. napcat uses the same 30-retry budget. - * - * The returned node plugs directly into - * `apis.groupFile.getPttUrl`, which already handles every other - * download-URL fetch in SnowLuma. The synthesis response does not contain a - * reliable message sequence; callers that need one must use `sendAiVoice`, - * which correlates the subsequent self-message receipt. - */ - async fetchAiVoice( - groupId: number, - voiceId: string, - text: string, - chatType: AiVoiceChatType | number, - maxRetries = 30, - ): Promise { - // Random 32-bit session id — server uses this to deduplicate polls. - const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0; - for (let i = 0; i < maxRetries; i++) { - const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId }); - if (node) { - log.debug( - 'AI voice synthesis completed group=%d media=%s polls=%d', - groupId, - describeAiVoiceFingerprint(node), - i + 1, - ); - return node as MediaIndexNode; - } + setGroupTodo(groupId: number, msgSeq: bigint): Promise { + return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' }); } - throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`); - } - /** - * Publish an AI voice and wait for QQ's canonical self-message receipt. - * - * The 0x929B completion response carries the media node but, on live QQ, - * omits the group message sequence. Subscribe before publishing so an echo - * that wins the response race is buffered, then correlate by the exact media - * UUID. Never guess from content hashes or "the next voice in the group": - * concurrent requests can legitimately render byte-identical audio. - */ - async sendAiVoice( - groupId: number, - voiceId: string, - text: string, - chatType: AiVoiceChatType | number, - receiptTimeoutMs = AI_VOICE_RECEIPT_TIMEOUT_MS, - ): Promise { - const candidates: GroupMessageEvent[] = []; - let candidatesOverflowed = false; - let expectedNode: MediaIndexNode | null = null; - let receiptSettled = false; - let resolveReceipt: ((event: GroupMessageEvent) => void) | null = null; - const receiptPromise = new Promise((resolve) => { - resolveReceipt = resolve; - }); - - const claim = (event: GroupMessageEvent): boolean => { - if (receiptSettled) return false; - const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`; - if (this.claimedAiVoiceReceiptKeys.has(key)) return false; - this.claimedAiVoiceReceiptKeys.add(key); - if (this.claimedAiVoiceReceiptKeys.size > AI_VOICE_CLAIM_LIMIT) { - const oldest = this.claimedAiVoiceReceiptKeys.values().next().value; - if (oldest !== undefined) this.claimedAiVoiceReceiptKeys.delete(oldest); - } - receiptSettled = true; - return true; - }; - - const accept = (event: GroupMessageEvent): void => { - if (event.groupId !== groupId || event.senderUin !== event.selfUin) return; - if (!event.elements.some(element => element.type === 'record')) return; - if (expectedNode && matchesAiVoiceEvent(expectedNode, event) && claim(event)) { - resolveReceipt?.(event); - return; - } - candidates.push(event); - if (candidates.length > AI_VOICE_CANDIDATE_LIMIT) { - candidates.shift(); - candidatesOverflowed = true; - } - }; - - const unsubscribe = this.ctx.events.on('group_message', accept); - let timeout: ReturnType | null = null; - try { - const node = await this.fetchAiVoice(groupId, voiceId, text, chatType); - expectedNode = node; - const fingerprint = describeAiVoiceFingerprint(node); - if (fingerprint === 'missing') { - throw new Error('AI voice was published but QQ returned no exact media identifier for receipt correlation'); - } - - const buffered = candidates.find(event => matchesAiVoiceEvent(node, event) && claim(event)); - if (!buffered && candidatesOverflowed) { - throw new Error( - `AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} ` - + `unmatched self voice messages (group=${groupId} media=${fingerprint})`, - ); - } - const event = buffered ?? await Promise.race([ - receiptPromise, - new Promise((_resolve, reject) => { - timeout = setTimeout(() => { - reject(new Error( - `AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms ` - + `(group=${groupId} media=${fingerprint})`, - )); - }, receiptTimeoutMs); - timeout.unref?.(); - }), - ]); - - if (!Number.isInteger(event.msgSeq) || event.msgSeq <= 0) { - throw new Error(`AI voice receipt carried invalid message sequence: ${event.msgSeq}`); - } - - log.debug( - 'AI voice receipt matched group=%d media=%s sequence=%d random=%d', - groupId, - fingerprint, - event.msgSeq, - event.msgId, - ); - return { - sequence: event.msgSeq, - }; - } finally { - if (timeout) clearTimeout(timeout); - unsubscribe(); + completeGroupTodo(groupId: number, msgSeq: bigint): Promise { + return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' }); } - } - // ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ─────────────── - - /** - * Send ONE `pttTrans.Trans{C2C,Group}PttReq` to trigger transcription and - * return the recognised text IF the response carries it inline (the - * already-transcribed case). For a freshly-received voice the response is an - * empty ack and the text is delivered later via the async Event 0x210 - * subType-61 push — callers should treat `''` as "pending" and wait for the - * `ptt_trans_result` event (correlated by msgId). - */ - async translatePttToText(input: PttTransInput): Promise { - // QQ NT sends the md5 as a 32-char lowercase HEX STRING, not the raw 16 - // bytes (RE'd from wrapper.linux.node EncodeTroopPtt/EncodeC2CPtt: the md5 - // field goes through a bytes→hex helper). Sending raw bytes → errCode -1079. - const md5 = input.md5Hex.toLowerCase(); - const req: PttTransReq = input.isGroup - ? { - type: 1, - groupItem: { - msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), groupUin: BigInt(input.peerUin), - fileId: input.fileId ?? 0, md5, duration: input.duration, size: input.size, - format: input.format, uuid: input.uuid, - }, - } - : { - type: 2, - c2cItem: { - msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), receiverUin: BigInt(input.peerUin), - uuid: input.uuid, duration: input.duration, size: input.size, format: input.format, md5, - }, - }; - const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq'; - - const result = await this.ctx.sendRawPacket(cmd, protobuf_encode(req)); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'ptt translate request failed'); + cancelGroupTodo(groupId: number, msgSeq: bigint): Promise { + return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' }); } - const resp = protobuf_decode(result.responseData); - const item = input.isGroup ? resp?.groupResult : resp?.c2cResult; - if (item?.errCode) { - // Diagnostic (#165 备选): correlate QQ's errCode with the request fields we - // sourced from cache, to tell a server-side ASR failure apart from our own - // missing/zero field (md5/format/uuid). Behaviour unchanged — still throws. - log.warn( - 'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d', - item.errCode, input.isGroup, - input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY', - input.format, input.uuid ? 'set' : 'EMPTY', input.duration, input.size, - ); - throw new Error(`ptt translate failed: error=${item.errCode}`); - } - return item?.text ?? ''; // '' = transcribing async; caller awaits the push - } - /** - * Transcode a voice record (`get_record out_format`, #165). `source` is a - * URL / local path / `base64://…` (the record's download URL in practice); - * it is loaded then transcoded to `format` via the bundled SILK-capable - * ffmpeg addon. Returns base64 + size. Throws on unsupported format or a - * failed conversion. - */ - async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> { - // Voices are tiny — cap the download well below loadBinarySource's 1 GiB - // default so a tampered/oversized source can't be pulled in. - const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024); - return convertAudioBytes(bytes, format); - } + // ─────────────── Stranger online/ext status (0xFE1_2) ─────────────── + + /** + * Keeps the action response user-safe while retaining the underlying + * failure in the service log for diagnosis. + */ + async getStrangerStatus(uin: number): Promise { + try { + const status = await GetStrangerStatus.invoke(this.ctx, { uin }); + + if (!status) { + log.warn('user status query returned no status target=%d', uin); + } + + return status; + } catch (error) { + log.warn( + 'user status query failed target=%d: %s', + uin, + error instanceof Error ? error.message : String(error), + ); + return null; + } + } + + // ─────────────── AI voice (0x929D / 0x929B) ─────────────── + + fetchAiVoiceList( + groupId: number, + chatType: AiVoiceChatType | number, + ): Promise { + return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType }); + } + + /** + * Trigger AI voice synthesis. Server may return an empty msgInfo while + * the render is in-flight; we retry until a node materialises or the + * cap is hit. napcat uses the same 30-retry budget. + * + * The returned node plugs directly into + * `apis.groupFile.getPttUrl`, which already handles every other + * download-URL fetch in SnowLuma. The synthesis response does not contain a + * reliable message sequence; callers that need one must use `sendAiVoice`, + * which correlates the subsequent self-message receipt. + */ + async fetchAiVoice( + groupId: number, + voiceId: string, + text: string, + chatType: AiVoiceChatType | number, + maxRetries = 30, + ): Promise { + // Random 32-bit session id — server uses this to deduplicate polls. + const sessionId = Math.floor(Math.random() * 0xffffffff) >>> 0; + + for (let i = 0; i < maxRetries; i++) { + const node = await FetchAiVoice.invoke(this.ctx, { + groupId, + voiceId, + text, + chatType, + sessionId, + }); + + if (node) { + log.debug( + 'AI voice synthesis completed group=%d media=%s polls=%d', + groupId, + describeAiVoiceFingerprint(node), + i + 1, + ); + return node as MediaIndexNode; + } + } + + throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`); + } + + /** + * Publish an AI voice and wait for QQ's canonical self-message receipt. + * + * The 0x929B completion response carries the media node but, on live QQ, + * omits the group message sequence. Subscribe before publishing so an echo + * that wins the response race is buffered, then correlate by the exact media + * UUID. Never guess from content hashes or "the next voice in the group": + * concurrent requests can legitimately render byte-identical audio. + */ + async sendAiVoice( + groupId: number, + voiceId: string, + text: string, + chatType: AiVoiceChatType | number, + receiptTimeoutMs = AI_VOICE_RECEIPT_TIMEOUT_MS, + ): Promise { + const candidates: GroupMessageEvent[] = []; + let candidatesOverflowed = false; + let expectedNode: MediaIndexNode | null = null; + let receiptSettled = false; + let resolveReceipt: ((event: GroupMessageEvent) => void) | null = null; + const receiptPromise = new Promise((resolve) => { + resolveReceipt = resolve; + }); + + const claim = (event: GroupMessageEvent): boolean => { + if (receiptSettled) { + return false; + } + + const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`; + + if (this.claimedAiVoiceReceiptKeys.has(key)) { + return false; + } + + this.claimedAiVoiceReceiptKeys.add(key); + + if (this.claimedAiVoiceReceiptKeys.size > AI_VOICE_CLAIM_LIMIT) { + const oldest = this.claimedAiVoiceReceiptKeys.values().next().value; + + if (oldest !== undefined) { + this.claimedAiVoiceReceiptKeys.delete(oldest); + } + } + + receiptSettled = true; + return true; + }; + + const accept = (event: GroupMessageEvent): void => { + if (event.groupId !== groupId || event.senderUin !== event.selfUin) { + return; + } + + if (!event.elements.some((element) => element.type === 'record')) { + return; + } + + if (expectedNode && matchesAiVoiceEvent(expectedNode, event) && claim(event)) { + resolveReceipt?.(event); + return; + } + + candidates.push(event); + + if (candidates.length > AI_VOICE_CANDIDATE_LIMIT) { + candidates.shift(); + candidatesOverflowed = true; + } + }; + + const unsubscribe = this.ctx.events.on('group_message', accept); + let timeout: ReturnType | null = null; + + try { + const node = await this.fetchAiVoice(groupId, voiceId, text, chatType); + expectedNode = node; + const fingerprint = describeAiVoiceFingerprint(node); + + if (fingerprint === 'missing') { + throw new Error( + 'AI voice was published but QQ returned no exact media identifier for receipt correlation', + ); + } + + const buffered = candidates.find( + (event) => matchesAiVoiceEvent(node, event) && claim(event), + ); + + if (!buffered && candidatesOverflowed) { + throw new Error( + `AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} ` + + `unmatched self voice messages (group=${groupId} media=${fingerprint})`, + ); + } + + const event = + buffered ?? + (await Promise.race([ + receiptPromise, + new Promise((_resolve, reject) => { + timeout = setTimeout(() => { + reject( + new Error( + `AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms ` + + `(group=${groupId} media=${fingerprint})`, + ), + ); + }, receiptTimeoutMs); + timeout.unref?.(); + }), + ])); + + if (!Number.isInteger(event.msgSeq) || event.msgSeq <= 0) { + throw new Error( + `AI voice receipt carried invalid message sequence: ${event.msgSeq}`, + ); + } + + log.debug( + 'AI voice receipt matched group=%d media=%s sequence=%d random=%d', + groupId, + fingerprint, + event.msgSeq, + event.msgId, + ); + return { + sequence: event.msgSeq, + }; + } finally { + if (timeout) { + clearTimeout(timeout); + } + + unsubscribe(); + } + } + + // ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ─────────────── + + /** + * Send ONE `pttTrans.Trans{C2C,Group}PttReq` to trigger transcription and + * return the recognised text IF the response carries it inline (the + * already-transcribed case). For a freshly-received voice the response is an + * empty ack and the text is delivered later via the async Event 0x210 + * subType-61 push — callers should treat `''` as "pending" and wait for the + * `ptt_trans_result` event (correlated by msgId). + */ + async translatePttToText(input: PttTransInput): Promise { + // QQ NT sends the md5 as a 32-char lowercase HEX STRING, not the raw 16 + // bytes (RE'd from wrapper.linux.node EncodeTroopPtt/EncodeC2CPtt: the md5 + // field goes through a bytes→hex helper). Sending raw bytes → errCode -1079. + const md5 = input.md5Hex.toLowerCase(); + const req: PttTransReq = input.isGroup + ? { + type: 1, + groupItem: { + msgId: BigInt(input.msgId), + senderUin: BigInt(input.senderUin), + groupUin: BigInt(input.peerUin), + fileId: input.fileId ?? 0, + md5, + duration: input.duration, + size: input.size, + format: input.format, + uuid: input.uuid, + }, + } + : { + type: 2, + c2cItem: { + msgId: BigInt(input.msgId), + senderUin: BigInt(input.senderUin), + receiverUin: BigInt(input.peerUin), + uuid: input.uuid, + duration: input.duration, + size: input.size, + format: input.format, + md5, + }, + }; + const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq'; + + const result = await this.ctx.sendRawPacket(cmd, protobuf_encode(req)); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'ptt translate request failed'); + } + + const resp = protobuf_decode(result.responseData); + const item = input.isGroup ? resp?.groupResult : resp?.c2cResult; + + if (item?.errCode) { + // Diagnostic (#165 备选): correlate QQ's errCode with the request fields we + // sourced from cache, to tell a server-side ASR failure apart from our own + // missing/zero field (md5/format/uuid). Behaviour unchanged — still throws. + log.warn( + 'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d', + item.errCode, + input.isGroup, + input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY', + input.format, + input.uuid ? 'set' : 'EMPTY', + input.duration, + input.size, + ); + throw new Error(`ptt translate failed: error=${item.errCode}`); + } + + return item?.text ?? ''; // '' = transcribing async; caller awaits the push + } + + /** + * Transcode a voice record (`get_record out_format`, #165). `source` is a + * URL / local path / `base64://…` (the record's download URL in practice); + * it is loaded then transcoded to `format` via the bundled SILK-capable + * ffmpeg addon. Returns base64 + size. Throws on unsupported format or a + * failed conversion. + */ + async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> { + // Voices are tiny — cap the download well below loadBinarySource's 1 GiB + // default so a tampered/oversized source can't be pulled in. + const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024); + return convertAudioBytes(bytes, format); + } } diff --git a/packages/core/src/bridge/apis/flash-transfer.ts b/packages/core/src/bridge/apis/flash-transfer.ts index afb663a3..d45fedcc 100644 --- a/packages/core/src/bridge/apis/flash-transfer.ts +++ b/packages/core/src/bridge/apis/flash-transfer.ts @@ -19,16 +19,20 @@ import { PrepareUpload } from '@snowluma/protocol/oidb-services/flash-transfer/p import { SendFlashMsg } from '@snowluma/protocol/oidb-services/flash-transfer/send-flash'; import { FileChunkSource } from '@snowluma/protocol/highway'; import { - computeHashes, - inlineBase64Payload, - FLASH_TRANSFER_MAX_BYTES, - FLASH_TRANSFER_INLINE_MAX_BYTES, + computeHashes, + inlineBase64Payload, + FLASH_TRANSFER_MAX_BYTES, + FLASH_TRANSFER_INLINE_MAX_BYTES, } from '@snowluma/protocol/highway/utils'; import { stageSourceToDisk } from '@snowluma/protocol/highway/stage'; import { hashFlashFileStreaming } from '@snowluma/protocol/highway/hash-file'; import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream'; import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; -import type { FlashSliceUploadBody, FlashSliceUploadResp, FlashFileId } from '@snowluma/proto-defs/oidb-actions/flash-transfer'; +import type { + FlashSliceUploadBody, + FlashSliceUploadResp, + FlashFileId, +} from '@snowluma/proto-defs/oidb-actions/flash-transfer'; import { randomUUID, randomBytes, createHash } from 'node:crypto'; import { promises as fsp } from 'node:fs'; import { deflateSync } from 'node:zlib'; @@ -36,20 +40,53 @@ import { deflateSync } from 'node:zlib'; const FLASH_SLICE_SIZE = 1024 * 1024; const FLASH_IMAGE_EXT = new Set([ - 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'heic', 'avif', 'tiff', 'tif', 'ico', 'dib', 'heif', + 'jpg', + 'jpeg', + 'png', + 'gif', + 'bmp', + 'webp', + 'heic', + 'avif', + 'tiff', + 'tif', + 'ico', + 'dib', + 'heif', ]); const FLASH_AUDIO_EXT = new Set(['mp3', 'wav', 'aac', 'flac']); const FLASH_VIDEO_EXT = new Set([ - 'mp4', 'avi', 'mkv', 'mov', '3gp', 'mpeg', 'rmvb', 'rm', 'wmv', 'flv', 'asf', 'webm', 'mpg', 'vob', 'm4v', 'f4v', + 'mp4', + 'avi', + 'mkv', + 'mov', + '3gp', + 'mpeg', + 'rmvb', + 'rm', + 'wmv', + 'flv', + 'asf', + 'webm', + 'mpg', + 'vob', + 'm4v', + 'f4v', ]); const FLASH_ARCHIVE_EXT = new Set(['zip', 'rar', 'tar', 'bz2', 'xz', 'tgz', 'gz', '7z']); const FLASH_MODEL_EXT = new Set(['pt', 'pth', 'onnx', 'model', 'mlmodel']); /** 0x93cf f3 粗类:压缩包走 2/6,其余按媒体类 7。 */ function flashApplyTypeCode(ext: string): number { - if (ext === 'zip') return 6; - if (FLASH_ARCHIVE_EXT.has(ext)) return 2; - return 7; + if (ext === 'zip') { + return 6; + } + + if (FLASH_ARCHIVE_EXT.has(ext)) { + return 2; + } + + return 7; } /** @@ -57,30 +94,99 @@ function flashApplyTypeCode(ext: string): number { * 图片 26、音频 1、视频 2、文档 3、压缩包 4、未知 11。 */ function flashFormatCode(ext: string): number { - if (FLASH_IMAGE_EXT.has(ext)) return 26; - if (FLASH_AUDIO_EXT.has(ext)) return 1; - if (FLASH_VIDEO_EXT.has(ext)) return 2; - if (ext === 'doc' || ext === 'docx') return 3; - if (FLASH_ARCHIVE_EXT.has(ext)) return 4; - if (ext === 'apk') return 5; - if (ext === 'xls' || ext === 'xlsx') return 6; - if (ext === 'ppt' || ext === 'pptx') return 7; - if (ext === 'html' || ext === 'htm') return 8; - if (ext === 'pdf') return 9; - if (ext === 'txt') return 10; - if (ext === 'psd') return 12; - if (FLASH_MODEL_EXT.has(ext)) return 15; - if (ext === 'ttf' || ext === 'otf') return 16; - if (ext === 'ipa') return 17; - if (ext === 'dmg') return 23; - if (ext === 'pkg') return 24; - if (ext === 'key') return 18; - if (ext === 'note') return 19; - if (ext === 'numbers') return 20; - if (ext === 'pages') return 21; - if (ext === 'sketch') return 22; - if (ext === 'exe') return 27; - return 11; + if (FLASH_IMAGE_EXT.has(ext)) { + return 26; + } + + if (FLASH_AUDIO_EXT.has(ext)) { + return 1; + } + + if (FLASH_VIDEO_EXT.has(ext)) { + return 2; + } + + if (ext === 'doc' || ext === 'docx') { + return 3; + } + + if (FLASH_ARCHIVE_EXT.has(ext)) { + return 4; + } + + if (ext === 'apk') { + return 5; + } + + if (ext === 'xls' || ext === 'xlsx') { + return 6; + } + + if (ext === 'ppt' || ext === 'pptx') { + return 7; + } + + if (ext === 'html' || ext === 'htm') { + return 8; + } + + if (ext === 'pdf') { + return 9; + } + + if (ext === 'txt') { + return 10; + } + + if (ext === 'psd') { + return 12; + } + + if (FLASH_MODEL_EXT.has(ext)) { + return 15; + } + + if (ext === 'ttf' || ext === 'otf') { + return 16; + } + + if (ext === 'ipa') { + return 17; + } + + if (ext === 'dmg') { + return 23; + } + + if (ext === 'pkg') { + return 24; + } + + if (ext === 'key') { + return 18; + } + + if (ext === 'note') { + return 19; + } + + if (ext === 'numbers') { + return 20; + } + + if (ext === 'pages') { + return 21; + } + + if (ext === 'sketch') { + return 22; + } + + if (ext === 'exe') { + return 27; + } + + return 11; } /** After create returns, 0x93d4 can still omit the main-file fileId for a @@ -88,68 +194,72 @@ function flashFormatCode(ext: string): number { const FLASH_FILE_ID_RETRY_DELAYS_MS = [1000, 2000, 4000, 4000] as const; /** Fail cleanly if the staged file changed since the streaming hash pass. */ -async function assertUnchanged(filePath: string, baseline: { size: number; mtimeMs: number }): Promise { - const now = await fsp.stat(filePath); - if (now.size !== baseline.size || now.mtimeMs !== baseline.mtimeMs) { - throw new Error('file source changed during send (mutated between hashing and upload)'); - } +async function assertUnchanged( + filePath: string, + baseline: { size: number; mtimeMs: number }, +): Promise { + const now = await fsp.stat(filePath); + + if (now.size !== baseline.size || now.mtimeMs !== baseline.mtimeMs) { + throw new Error('file source changed during send (mutated between hashing and upload)'); + } } function flashStageMaxBytes(source: string): number { - return inlineBase64Payload(source) !== null - ? FLASH_TRANSFER_INLINE_MAX_BYTES - : FLASH_TRANSFER_MAX_BYTES; + return inlineBase64Payload(source) !== null + ? FLASH_TRANSFER_INLINE_MAX_BYTES + : FLASH_TRANSFER_MAX_BYTES; } interface StagedFlashItem { - filePath: string; - fileSize: number; - fileName: string; - fileUuid: string; - fileIndex: number; - formatCode: number; - guardStat: { size: number; mtimeMs: number }; - cleanup(): Promise; + filePath: string; + fileSize: number; + fileName: string; + fileUuid: string; + fileIndex: number; + formatCode: number; + guardStat: { size: number; mtimeMs: number }; + cleanup(): Promise; } /** One create_flash_task source: a path/URL, or a path plus a display name. */ export type FlashTaskFileInput = string | { file: string; name?: string }; function flashFileDisplayName(override: string | undefined, fallback: string): string { - const cleaned = (override ?? '').replace(/[/\\]/g, '_').trim(); - return cleaned || fallback; + const cleaned = (override ?? '').replace(/[/\\]/g, '_').trim(); + return cleaned || fallback; } function normalizeFlashTaskInputs( - files: FlashTaskFileInput | FlashTaskFileInput[], + files: FlashTaskFileInput | FlashTaskFileInput[], ): { file: string; name?: string }[] { - const list = Array.isArray(files) ? files : [files]; - return list.map((item) => (typeof item === 'string' ? { file: item } : item)); + const list = Array.isArray(files) ? files : [files]; + return list.map((item) => (typeof item === 'string' ? { file: item } : item)); } /** 闪传文件信息(业务层,从 FlashFileEntry 转换)。 */ export interface FlashFileInfo { - filesetUuid: string; - fileName: string; - origName: string; - fileSize: number; - /** 上传/分享链接 qfile.qq.com/q/。 */ - shareUrl: string; - fileId: string; - /** 下载链接 multimedia.qfile.qq.com/download?...&rkey=... */ - downloadUrl: string; + filesetUuid: string; + fileName: string; + origName: string; + fileSize: number; + /** 上传/分享链接 qfile.qq.com/q/。 */ + shareUrl: string; + fileId: string; + /** 下载链接 multimedia.qfile.qq.com/download?...&rkey=... */ + downloadUrl: string; } function entryToInfo(e: FlashFileEntry): FlashFileInfo { - return { - filesetUuid: e.filesetUuid ?? '', - fileName: e.fileName ?? '', - origName: e.origName ?? '', - fileSize: Number(e.fileSize ?? 0), - shareUrl: e.uploadUrlWrap?.uploadUrl ?? '', - fileId: e.fileIdWrap?.fileId ?? '', - downloadUrl: e.fileIdWrap?.download?.downloadUrl ?? '', - }; + return { + filesetUuid: e.filesetUuid ?? '', + fileName: e.fileName ?? '', + origName: e.origName ?? '', + fileSize: Number(e.fileSize ?? 0), + shareUrl: e.uploadUrlWrap?.uploadUrl ?? '', + fileId: e.fileIdWrap?.fileId ?? '', + downloadUrl: e.fileIdWrap?.download?.downloadUrl ?? '', + }; } const QFILE_SHARE_ORIGIN = 'https://qfile.qq.com'; @@ -157,546 +267,748 @@ const QFILE_SHARE_PAGE_MAX_BYTES = 2 * 1024 * 1024; const QFILE_SHARE_TIMEOUT_MS = 20_000; function officialQfileShareUrl(input: string): string { - const value = input.trim(); - if (!value) throw new Error('get_fileset_id: share code is empty'); + const value = input.trim(); - let code = value; - if (/^[a-z][a-z\d+.-]*:/i.test(value) || value.startsWith('//')) { - let parsed: URL; - try { - parsed = new URL(value); - } catch (error) { - throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error }); + if (!value) { + throw new Error('get_fileset_id: share code is empty'); } - if ( - parsed.protocol !== 'https:' - || parsed.hostname !== 'qfile.qq.com' - || parsed.port !== '' - || parsed.username !== '' - || parsed.password !== '' - ) { - throw new Error('get_fileset_id: expected an official QQ share URL'); - } - const match = /^\/q\/([^/]+)\/?$/.exec(parsed.pathname); - if (!match) throw new Error('get_fileset_id: expected an official QQ share URL'); - try { - code = decodeURIComponent(match[1]); - } catch (error) { - throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error }); - } - } - const hasForbiddenCharacter = Array.from(code).some((char) => { - const codePoint = char.codePointAt(0) ?? 0; - return codePoint <= 0x20 || codePoint === 0x7f || '/\\?#'.includes(char); - }); - if (code.length > 256 || hasForbiddenCharacter) { - throw new Error('get_fileset_id: invalid share code'); - } - return `${QFILE_SHARE_ORIGIN}/q/${encodeURIComponent(code)}`; + let code = value; + + if (/^[a-z][a-z\d+.-]*:/i.test(value) || value.startsWith('//')) { + let parsed: URL; + + try { + parsed = new URL(value); + } catch (error) { + throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error }); + } + + if ( + parsed.protocol !== 'https:' || + parsed.hostname !== 'qfile.qq.com' || + parsed.port !== '' || + parsed.username !== '' || + parsed.password !== '' + ) { + throw new Error('get_fileset_id: expected an official QQ share URL'); + } + + const match = /^\/q\/([^/]+)\/?$/.exec(parsed.pathname); + + if (!match) { + throw new Error('get_fileset_id: expected an official QQ share URL'); + } + + try { + code = decodeURIComponent(match[1]); + } catch (error) { + throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error }); + } + } + + const hasForbiddenCharacter = Array.from(code).some((char) => { + const codePoint = char.codePointAt(0) ?? 0; + return codePoint <= 0x20 || codePoint === 0x7f || '/\\?#'.includes(char); + }); + + if (code.length > 256 || hasForbiddenCharacter) { + throw new Error('get_fileset_id: invalid share code'); + } + + return `${QFILE_SHARE_ORIGIN}/q/${encodeURIComponent(code)}`; } async function rejectShareResponse(response: Response, error: Error): Promise { - try { - await response.body?.cancel(error); - } catch (cleanupError) { - throw new AggregateError([error, cleanupError], error.message); - } - throw error; + try { + await response.body?.cancel(error); + } catch (cleanupError) { + throw new AggregateError([error, cleanupError], error.message); + } + + throw error; } async function readSharePage(response: Response): Promise { - const declaredLength = response.headers.get('content-length'); - if (declaredLength !== null) { - if (!/^\d+$/.test(declaredLength)) { - await rejectShareResponse(response, new Error('get_fileset_id: invalid response length')); - } - if (Number(declaredLength) > QFILE_SHARE_PAGE_MAX_BYTES) { - await rejectShareResponse(response, new Error('get_fileset_id: share page too large')); - } - } - if (!response.body) throw new Error('get_fileset_id: share page response has no body'); + const declaredLength = response.headers.get('content-length'); - const reader = response.body.getReader(); - const decoder = new TextDecoder(); - let total = 0; - let html = ''; - try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - if (!value) continue; - total += value.byteLength; - if (total > QFILE_SHARE_PAGE_MAX_BYTES) { - const error = new Error('get_fileset_id: share page too large'); - try { - await reader.cancel(error); - } catch (cleanupError) { - throw new AggregateError([error, cleanupError], error.message); + if (declaredLength !== null) { + if (!/^\d+$/.test(declaredLength)) { + await rejectShareResponse( + response, + new Error('get_fileset_id: invalid response length'), + ); + } + + if (Number(declaredLength) > QFILE_SHARE_PAGE_MAX_BYTES) { + await rejectShareResponse(response, new Error('get_fileset_id: share page too large')); } - throw error; - } - html += decoder.decode(value, { stream: true }); } - html += decoder.decode(); - return html; - } finally { - reader.releaseLock(); - } + + if (!response.body) { + throw new Error('get_fileset_id: share page response has no body'); + } + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let total = 0; + let html = ''; + + try { + while (true) { + const { done, value } = await reader.read(); + + if (done) { + break; + } + + if (!value) { + continue; + } + + total += value.byteLength; + + if (total > QFILE_SHARE_PAGE_MAX_BYTES) { + const error = new Error('get_fileset_id: share page too large'); + + try { + await reader.cancel(error); + } catch (cleanupError) { + throw new AggregateError([error, cleanupError], error.message); + } + + throw error; + } + + html += decoder.decode(value, { stream: true }); + } + + html += decoder.decode(); + return html; + } finally { + reader.releaseLock(); + } } // 手写 PNG 编码(zlib 压缩,避免引入图像库)。缩略图用随机纯色,每次 SHA1 不同, // 避免命中服务端秒传缓存。 const CRC_TABLE: Uint32Array = (() => { - const table = new Uint32Array(256); - for (let n = 0; n < 256; n++) { - let c = n; - for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1); - table[n] = c >>> 0; - } - return table; + const table = new Uint32Array(256); + + for (let n = 0; n < 256; n++) { + let c = n; + + for (let k = 0; k < 8; k++) { + c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + } + + table[n] = c >>> 0; + } + + return table; })(); function crc32(buf: Buffer): number { - let c = 0xFFFFFFFF; - for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xFF] ^ (c >>> 8); - return (c ^ 0xFFFFFFFF) >>> 0; + let c = 0xffffffff; + + for (let i = 0; i < buf.length; i++) { + c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); + } + + return (c ^ 0xffffffff) >>> 0; } function pngChunk(type: string, data: Buffer): Buffer { - const len = Buffer.alloc(4); - len.writeUInt32BE(data.length, 0); - const typeBuf = Buffer.from(type, 'ascii'); - const crc = crc32(Buffer.concat([typeBuf, data])); - const crcBuf = Buffer.alloc(4); - crcBuf.writeUInt32BE(crc, 0); - return Buffer.concat([len, typeBuf, data, crcBuf]); + const len = Buffer.alloc(4); + len.writeUInt32BE(data.length, 0); + const typeBuf = Buffer.from(type, 'ascii'); + const crc = crc32(Buffer.concat([typeBuf, data])); + const crcBuf = Buffer.alloc(4); + crcBuf.writeUInt32BE(crc, 0); + return Buffer.concat([len, typeBuf, data, crcBuf]); } /** 生成 width×height 随机纯色 PNG(8-bit RGB)。每次随机颜色,SHA1 不同以避免秒传。 */ function generatePng(width: number, height: number): Buffer { - const r = Math.floor(Math.random() * 256); - const g = Math.floor(Math.random() * 256); - const b = Math.floor(Math.random() * 256); - const rowLen = 1 + width * 3; - const raw = Buffer.alloc(rowLen * height); - for (let y = 0; y < height; y++) { - const off = y * rowLen; - raw[off] = 0; // filter none - for (let x = 0; x < width; x++) { - raw[off + 1 + x * 3] = r; - raw[off + 1 + x * 3 + 1] = g; - raw[off + 1 + x * 3 + 2] = b; + const r = Math.floor(Math.random() * 256); + const g = Math.floor(Math.random() * 256); + const b = Math.floor(Math.random() * 256); + const rowLen = 1 + width * 3; + const raw = Buffer.alloc(rowLen * height); + + for (let y = 0; y < height; y++) { + const off = y * rowLen; + raw[off] = 0; // filter none + + for (let x = 0; x < width; x++) { + raw[off + 1 + x * 3] = r; + raw[off + 1 + x * 3 + 1] = g; + raw[off + 1 + x * 3 + 2] = b; + } } - } - const compressed = deflateSync(raw); - const sig = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); - const ihdr = Buffer.alloc(13); - ihdr.writeUInt32BE(width, 0); - ihdr.writeUInt32BE(height, 4); - ihdr[8] = 8; // bit depth - ihdr[9] = 2; // color type RGB - ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; - return Buffer.concat([sig, pngChunk('IHDR', ihdr), pngChunk('IDAT', compressed), pngChunk('IEND', Buffer.alloc(0))]); + + const compressed = deflateSync(raw); + const sig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; // bit depth + ihdr[9] = 2; // color type RGB + ihdr[10] = 0; + ihdr[11] = 0; + ihdr[12] = 0; + return Buffer.concat([ + sig, + pngChunk('IHDR', ihdr), + pngChunk('IDAT', compressed), + pngChunk('IEND', Buffer.alloc(0)), + ]); } export class FlashTransferApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - /** 获取文件集信息(get_fileset_info)。 */ - async getFilesetInfo(filesetUuid: string): Promise { - const entries = await GetFilesetDetail.invoke(this.ctx, { filesetUuid }); - return entries.map(entryToInfo); - } + /** 获取文件集信息(get_fileset_info)。 */ + async getFilesetInfo(filesetUuid: string): Promise { + const entries = await GetFilesetDetail.invoke(this.ctx, { filesetUuid }); + return entries.map(entryToInfo); + } - /** 获取闪传文件列表(get_flash_file_list)。同 getFilesetInfo,返回文件数组。 */ - async getFlashFileList(filesetUuid: string): Promise { - return this.getFilesetInfo(filesetUuid); - } + /** 获取闪传文件列表(get_flash_file_list)。同 getFilesetInfo,返回文件数组。 */ + async getFlashFileList(filesetUuid: string): Promise { + return this.getFilesetInfo(filesetUuid); + } - /** - * 拿指定文件的下载直链 + 元信息。0x93d4 返回 fileset 内所有文件(f3 repeated, - * 多文件时每条 f6=序号、f14=主文件 fileId),按 fileIndex 选中后走 0x12a9 sub=200 - * 拿主文件直链。0x93d3/0x93d4 的 downloadUrl 字段是缩略图(appid=14903/14902), - * 主文件必须走 0x12a9 sub=200。 - * - * create 刚返回时 f14 可能还是空的(#364)。fileId 空则按 - * FLASH_FILE_ID_RETRY_DELAYS_MS 再问 0x93d4;已经有 fileId 后 0x12a9 只打一枪。 - */ - private async getFileDownload( - filesetUuid: string, fileIndex: number = 1, - ): Promise<{ url: string; fileName: string; fileSize: number } | null> { - for (let attempt = 0; ; attempt++) { - const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid }); - const meta = metas.find((m) => m.fileIndex === fileIndex); - if (meta?.fileId) { - const url = await GetFlashDownload.invoke(this.ctx, { - filesetUuid: meta.filesetUuid, - fileUuid: meta.fileUuid, - fileId: meta.fileId, - fileName: meta.fileName, + /** + * 拿指定文件的下载直链 + 元信息。0x93d4 返回 fileset 内所有文件(f3 repeated, + * 多文件时每条 f6=序号、f14=主文件 fileId),按 fileIndex 选中后走 0x12a9 sub=200 + * 拿主文件直链。0x93d3/0x93d4 的 downloadUrl 字段是缩略图(appid=14903/14902), + * 主文件必须走 0x12a9 sub=200。 + * + * create 刚返回时 f14 可能还是空的(#364)。fileId 空则按 + * FLASH_FILE_ID_RETRY_DELAYS_MS 再问 0x93d4;已经有 fileId 后 0x12a9 只打一枪。 + */ + private async getFileDownload( + filesetUuid: string, + fileIndex: number = 1, + ): Promise<{ url: string; fileName: string; fileSize: number } | null> { + for (let attempt = 0; ; attempt++) { + const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid }); + const meta = metas.find((m) => m.fileIndex === fileIndex); + + if (meta?.fileId) { + const url = await GetFlashDownload.invoke(this.ctx, { + filesetUuid: meta.filesetUuid, + fileUuid: meta.fileUuid, + fileId: meta.fileId, + fileName: meta.fileName, + }); + + if (!url) { + return null; + } + + return { url, fileName: meta.fileName, fileSize: meta.fileSize }; + } + + const delay = FLASH_FILE_ID_RETRY_DELAYS_MS[attempt]; + + if (delay === undefined) { + return null; + } + + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + + /** + * 获取闪传文件下载链接(get_flash_file_url)。主文件直链走 0x12a9 sub=200 + * (0x93d3 的 downloadUrl 是缩略图 appid=14903,非主文件)。多文件 fileset 用 + * fileIndex 指定第几个文件(默认 1)。找不到文件或拿不到直链时抛错。 + */ + async getFlashFileUrl(filesetUuid: string, fileIndex: number = 1): Promise { + const dl = await this.getFileDownload(filesetUuid, fileIndex); + + if (!dl || !dl.url) { + throw new Error('get_flash_file_url: no download url available'); + } + + return dl.url; + } + + /** + * 解析闪传文件下载直链(download_fileset)。返回指定文件的下载 URL + 文件名/大小, + * 不下载文件内容(由调用方拉)。多文件 fileset 用 fileIndex 指定第几个文件(默认 1)。 + */ + async downloadFileset( + filesetUuid: string, + opts?: { fileName?: string; fileIndex?: number }, + ): Promise<{ url: string; fileName: string; fileSize: number }> { + const dl = await this.getFileDownload(filesetUuid, opts?.fileIndex ?? 1); + + if (!dl || !dl.url) { + throw new Error('download_fileset: no download url available'); + } + + return dl; + } + + /** 获取分享链接(get_share_link)= qfile.qq.com/q/。 */ + async getShareLink(filesetUuid: string): Promise { + const entries = await GetFilesetDetail.invoke(this.ctx, { filesetUuid }); + return entries.find((e) => e.uploadUrlWrap?.uploadUrl)?.uploadUrlWrap?.uploadUrl ?? ''; + } + + /** 列出当前账号的所有 fileset(OneBot 标准未定义,QQ 面板有此入口)。 */ + async listFilesets(): Promise { + const entries = await ListFilesets.invoke(this.ctx, {}); + return entries.map(entryToInfo); + } + + /** 删除闪传文件(delete_flash_file)。 */ + async deleteFlashFile(filesetUuid: string): Promise { + await DeleteFlashFile.invoke(this.ctx, { filesetUuid }); + } + + /** 重命名闪传文件(rename_flash_file)。 */ + async renameFlashFile(filesetUuid: string, newName: string): Promise { + await RenameFlashFile.invoke(this.ctx, { filesetUuid, newName }); + } + + /** + * 发送闪传文件(send_flash_msg,0x93d7)。私聊:user_id→uid;群聊:group_id 直接用。 + * 0x93d7 响应无 message_id(分享 fileset,非传统消息),OneBot 层 message_id 由 action 返回 0。 + */ + async sendFlashMsg( + filesetUuid: string, + target: { userId?: number; groupId?: number }, + ): Promise { + if (target.groupId) { + await SendFlashMsg.invoke(this.ctx, { groupId: target.groupId, filesetUuid }); + return; + } + + const userId = target.userId; + + if (!userId) { + throw new Error('send_flash_msg: user_id or group_id is required'); + } + + const targetUid = await this.ctx.identity.resolveUid(userId); + await SendFlashMsg.invoke(this.ctx, { targetUid, filesetUuid }); + } + + /** + * 从分享码/链接获取 fileset_id(get_fileset_id)。code→UUID 不走 OIDB,QQ 客户端 + * 走 trpc HTTP API;分享页 qfile.qq.com/q/ 的 HTML 内嵌了 fileset_id(trpc + * 接口数据),直接 GET + 正则提取即可,无需复刻带签名的 trpc 调用。 + */ + async getFilesetIdByCode(shareCode: string): Promise { + const url = officialQfileShareUrl(shareCode); + let resp: Response; + + try { + resp = await fetch(url, { + redirect: 'manual', + signal: AbortSignal.timeout(QFILE_SHARE_TIMEOUT_MS), + }); + } catch (error) { + if ( + error instanceof Error && + (error.name === 'AbortError' || error.name === 'TimeoutError') + ) { + throw new Error('get_fileset_id: share page request timed out', { cause: error }); + } + + throw error; + } + + if (resp.status >= 300 && resp.status < 400) { + await rejectShareResponse( + resp, + new Error('get_fileset_id: share page redirect is not allowed'), + ); + } + + if (!resp.ok) { + await rejectShareResponse(resp, new Error(`get_fileset_id: HTTP ${resp.status}`)); + } + + const html = await readSharePage(resp); + // 网页里 fileset_id 以 JSON 嵌入(引号可能被转义为 \"),正则兼容两种形态。 + const m = + /fileset_id\\?"\s*:\s*\\?"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec( + html, + ); + + if (!m) { + throw new Error('get_fileset_id: fileset_id not found in share page'); + } + + return m[1]; + } + + // ─────────────── 文件上传 ─────────────── + + /** + * 文件扩展名 → 闪传类型码。typeCode 用于 0x93cf f3(卡片粗类:压缩包/媒体); + * formatCode 用于 0x93d0 commit f7 与 0x12a9 filesetWrap.f7,决定对端图标 + * (png=26,mp4=2,zip=4,未知=11)。 + */ + private static fileTypeCode(fileName: string): { typeCode: number; formatCode: number } { + const ext = fileName.toLowerCase().match(/\.([^.]+)$/)?.[1] ?? ''; + return { typeCode: flashApplyTypeCode(ext), formatCode: flashFormatCode(ext) }; + } + + /** 构造 sub=103 的 fileId(客户端生成的 protobuf,base64url 编码)。 + * f2=SHA1, f3=filesize, f4=appid, f5=微秒时间戳, f6="prod", + * f10=TTL(1209600), f11=16B 会话ID, f15=3B, f16="gz"。 + * f11/f15 随机生成,服务端不校验。 + * appid 决定 fileId 落在哪个槽位:主文件用 14901(0x93d4 f14.f1), + * png 缩略图用 14903、jpg 缩略图用 14902(f13.f1)。主文件必须用 14901, + * 否则 fileId 不会被服务端采纳进 f14,对端无法拿到主文件下载入口。 */ + private static buildFileId(sha1: Uint8Array, fileSize: number, appid: number = 14901): string { + const fileId: FlashFileId = { + sha1: new Uint8Array(sha1), + fileSize, + appid, + timestamp: BigInt(Date.now()) * 1000n, // 微秒时间戳 + env: 'prod', + ttl: 1209600, + sessionId: randomBytes(16), + field15: randomBytes(3), + region: 'gz', + }; + return Buffer.from(protobuf_encode(fileId)).toString('base64url'); + } + + /** + * 创建闪传任务(create_flash_task)。所有文件统一走 sub=100/103+sliceupload, + * 不走小文件 PUT——QQ 客户端即使几百 KB 的文件也走 sliceupload。只有 sliceupload + * 路径会上报主文件 sha1/size,服务端据此把 fileset 标记为完成(对端可下载); + * PUT 路径不上报 sha1,fileset 会卡在"上传中"无法被下载。 + * + * 多文件:0x93d0 的 f4 是 repeated,一个 commit 请求同时携带 fileset 内所有文件 + * 条目,每条 f6=文件序号(1,2,3...)。commit 在上传前只发一次,之后 complete → + * 逐个 prepare/apply/sliceupload。prepare/apply 的 filesetWrap.f4 必须与 commit + * 的 f6 一致,否则文件不计入 fileset。ApplyFileset 的 fileName 是 fileset 显示名 + * (卡片标题):有 name 用 name,否则单文件用首文件名、多文件用「<首文件名>等N个文件」。 + * fileSize 用总和——服务端据此判定 fileset 为多文件。各文件在 commit 里用 + * 条目上的 name(若有),否则用路径 basename。 + * + * 源文件经 stageSourceToDisk 落到本地路径后流式哈希 / 分片读取,不再经 + * loadBinarySource 整文件进内存。本地与 HTTP 上限与群文件相同(4 GiB); + * 内联 base64 仍按 1 GiB 封顶,因为 stage 解码时会占用等量 RAM。 + */ + async createFlashTask( + files: FlashTaskFileInput | FlashTaskFileInput[], + name?: string, + _thumbPath?: string, + ): Promise<{ filesetId: string }> { + const fileList = normalizeFlashTaskInputs(files); + + if (fileList.length === 0) { + throw new Error('create_flash_task: files is empty'); + } + + const uploader = { + uin: this.ctx.identity.uin, + nickname: this.ctx.identity.nickname, + // Resolve our own uid rather than ship an empty one — a blank uploader + // uid drops the fileset if this runs before warmup populated selfUid. + uid: await resolveSelfUid(this.ctx), + }; + const items: StagedFlashItem[] = []; + + try { + for (let i = 0; i < fileList.length; i++) { + const source = fileList[i]!.file; + + if (!source) { + throw new Error('create_flash_task: files is empty'); + } + + const staged = await stageSourceToDisk(source, flashStageMaxBytes(source)); + const fileName = flashFileDisplayName(fileList[i]!.name, staged.fileName); + const { formatCode } = FlashTransferApi.fileTypeCode(fileName); + items.push({ + filePath: staged.filePath, + fileSize: staged.fileSize, + fileName, + fileUuid: randomUUID(), + fileIndex: i + 1, + formatCode, + guardStat: await fsp.stat(staged.filePath), + cleanup: () => staged.cleanup(), + }); + + if (staged.fileSize === 0) { + throw new Error('create_flash_task: file is empty'); + } + } + + // 申请 fileset。fileName 是卡片/面板上的 fileset 标题;各文件真实名走 commit。 + // 未指定 name 时,多文件用「<首文件名>等N个文件」、fileSize 用总和, + // 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。 + const first = items[0]; + const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName); + const isMulti = items.length > 1; + const filesetName = + name?.trim() || + (isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName); + const totalSize = items.reduce((s, it) => s + it.fileSize, 0); + const apply = await ApplyFileset.invoke(this.ctx, { + fileName: filesetName, + origName: filesetName, + fileSize: totalSize, + typeCode, + uploader, + }); + const filesetUuid = apply.filesetUuid; + + if (!filesetUuid) { + throw new Error('apply fileset failed: missing uuid'); + } + + // 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号) + const commitEntries = items.map((it) => ({ + fileUuid: it.fileUuid, + fileName: it.fileName, + origName: it.fileName, + fileSize: it.fileSize, + formatCode: it.formatCode, + fileIndex: it.fileIndex, + })); + await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries }); + await CompleteFileset.invoke(this.ctx, { filesetUuid }); + // 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。 + const prepared: { + it: StagedFlashItem; + rkey: string; + sha1StateV: Uint8Array[]; + sliceCount: number; + }[] = []; + + for (const it of items) { + const p = await this.prepareAndApply(filesetUuid, it); + + if (p) { + prepared.push({ it, ...p }); + } + } + + for (const p of prepared) { + await assertUnchanged(p.it.filePath, p.it.guardStat); + await this.sliceuploadFile( + p.it.filePath, + p.it.fileSize, + p.rkey, + p.sha1StateV, + p.sliceCount, + p.it.fileName, + ); + } + + // fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联 + await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1); + await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2); + await SetFilesetStatus.invoke(this.ctx, { filesetUuid }); + return { filesetId: filesetUuid }; + } finally { + await Promise.all(items.map((it) => it.cleanup())); + } + } + + /** + * 阶段1:流式哈希 + prepare(拿 rkey)+ apply(注册 fileId)。 + * 秒传时 prepare 不回 rkey,仍必须 apply,否则 fileset 会一直停在等待上传; + * 返回 null 只表示调用方跳过 sliceupload。 + */ + private async prepareAndApply( + filesetUuid: string, + it: StagedFlashItem, + ): Promise<{ rkey: string; sha1StateV: Uint8Array[]; sliceCount: number } | null> { + const hashes = await hashFlashFileStreaming(it.filePath); + await assertUnchanged(it.filePath, it.guardStat); + + const rkey = await PrepareUpload.invoke(this.ctx, { + filesetUuid, + fileUuid: it.fileUuid, + fileName: it.fileName, + fileSize: it.fileSize, + sha1: hashes.sha1Hex, + fileIndex: it.fileIndex, + formatCode: it.formatCode, }); - if (!url) return null; - return { url, fileName: meta.fileName, fileSize: meta.fileSize }; - } - const delay = FLASH_FILE_ID_RETRY_DELAYS_MS[attempt]; - if (delay === undefined) return null; - await new Promise((resolve) => setTimeout(resolve, delay)); - } - } - - /** - * 获取闪传文件下载链接(get_flash_file_url)。主文件直链走 0x12a9 sub=200 - * (0x93d3 的 downloadUrl 是缩略图 appid=14903,非主文件)。多文件 fileset 用 - * fileIndex 指定第几个文件(默认 1)。找不到文件或拿不到直链时抛错。 - */ - async getFlashFileUrl(filesetUuid: string, fileIndex: number = 1): Promise { - const dl = await this.getFileDownload(filesetUuid, fileIndex); - if (!dl || !dl.url) throw new Error('get_flash_file_url: no download url available'); - return dl.url; - } - - /** - * 解析闪传文件下载直链(download_fileset)。返回指定文件的下载 URL + 文件名/大小, - * 不下载文件内容(由调用方拉)。多文件 fileset 用 fileIndex 指定第几个文件(默认 1)。 - */ - async downloadFileset( - filesetUuid: string, - opts?: { fileName?: string; fileIndex?: number }, - ): Promise<{ url: string; fileName: string; fileSize: number }> { - const dl = await this.getFileDownload(filesetUuid, opts?.fileIndex ?? 1); - if (!dl || !dl.url) throw new Error('download_fileset: no download url available'); - return dl; - } - - /** 获取分享链接(get_share_link)= qfile.qq.com/q/。 */ - async getShareLink(filesetUuid: string): Promise { - const entries = await GetFilesetDetail.invoke(this.ctx, { filesetUuid }); - return entries.find((e) => e.uploadUrlWrap?.uploadUrl)?.uploadUrlWrap?.uploadUrl ?? ''; - } - - /** 列出当前账号的所有 fileset(OneBot 标准未定义,QQ 面板有此入口)。 */ - async listFilesets(): Promise { - const entries = await ListFilesets.invoke(this.ctx, {}); - return entries.map(entryToInfo); - } - - /** 删除闪传文件(delete_flash_file)。 */ - async deleteFlashFile(filesetUuid: string): Promise { - await DeleteFlashFile.invoke(this.ctx, { filesetUuid }); - } - - /** 重命名闪传文件(rename_flash_file)。 */ - async renameFlashFile(filesetUuid: string, newName: string): Promise { - await RenameFlashFile.invoke(this.ctx, { filesetUuid, newName }); - } - - /** - * 发送闪传文件(send_flash_msg,0x93d7)。私聊:user_id→uid;群聊:group_id 直接用。 - * 0x93d7 响应无 message_id(分享 fileset,非传统消息),OneBot 层 message_id 由 action 返回 0。 - */ - async sendFlashMsg(filesetUuid: string, target: { userId?: number; groupId?: number }): Promise { - if (target.groupId) { - await SendFlashMsg.invoke(this.ctx, { groupId: target.groupId, filesetUuid }); - return; - } - const userId = target.userId; - if (!userId) throw new Error('send_flash_msg: user_id or group_id is required'); - const targetUid = await this.ctx.identity.resolveUid(userId); - await SendFlashMsg.invoke(this.ctx, { targetUid, filesetUuid }); - } - - /** - * 从分享码/链接获取 fileset_id(get_fileset_id)。code→UUID 不走 OIDB,QQ 客户端 - * 走 trpc HTTP API;分享页 qfile.qq.com/q/ 的 HTML 内嵌了 fileset_id(trpc - * 接口数据),直接 GET + 正则提取即可,无需复刻带签名的 trpc 调用。 - */ - async getFilesetIdByCode(shareCode: string): Promise { - const url = officialQfileShareUrl(shareCode); - let resp: Response; - try { - resp = await fetch(url, { - redirect: 'manual', - signal: AbortSignal.timeout(QFILE_SHARE_TIMEOUT_MS), - }); - } catch (error) { - if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) { - throw new Error('get_fileset_id: share page request timed out', { cause: error }); - } - throw error; - } - if (resp.status >= 300 && resp.status < 400) { - await rejectShareResponse(resp, new Error('get_fileset_id: share page redirect is not allowed')); - } - if (!resp.ok) { - await rejectShareResponse(resp, new Error(`get_fileset_id: HTTP ${resp.status}`)); - } - const html = await readSharePage(resp); - // 网页里 fileset_id 以 JSON 嵌入(引号可能被转义为 \"),正则兼容两种形态。 - const m = /fileset_id\\?"\s*:\s*\\?"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec(html); - if (!m) throw new Error('get_fileset_id: fileset_id not found in share page'); - return m[1]; - } - - // ─────────────── 文件上传 ─────────────── - - /** - * 文件扩展名 → 闪传类型码。typeCode 用于 0x93cf f3(卡片粗类:压缩包/媒体); - * formatCode 用于 0x93d0 commit f7 与 0x12a9 filesetWrap.f7,决定对端图标 - * (png=26,mp4=2,zip=4,未知=11)。 - */ - private static fileTypeCode(fileName: string): { typeCode: number; formatCode: number } { - const ext = fileName.toLowerCase().match(/\.([^.]+)$/)?.[1] ?? ''; - return { typeCode: flashApplyTypeCode(ext), formatCode: flashFormatCode(ext) }; - } - - /** 构造 sub=103 的 fileId(客户端生成的 protobuf,base64url 编码)。 - * f2=SHA1, f3=filesize, f4=appid, f5=微秒时间戳, f6="prod", - * f10=TTL(1209600), f11=16B 会话ID, f15=3B, f16="gz"。 - * f11/f15 随机生成,服务端不校验。 - * appid 决定 fileId 落在哪个槽位:主文件用 14901(0x93d4 f14.f1), - * png 缩略图用 14903、jpg 缩略图用 14902(f13.f1)。主文件必须用 14901, - * 否则 fileId 不会被服务端采纳进 f14,对端无法拿到主文件下载入口。 */ - private static buildFileId(sha1: Uint8Array, fileSize: number, appid: number = 14901): string { - const fileId: FlashFileId = { - sha1: new Uint8Array(sha1), - fileSize, - appid, - timestamp: BigInt(Date.now()) * 1000n, // 微秒时间戳 - env: 'prod', - ttl: 1209600, - sessionId: randomBytes(16), - field15: randomBytes(3), - region: 'gz', - }; - return Buffer.from(protobuf_encode(fileId)).toString('base64url'); - } - - /** - * 创建闪传任务(create_flash_task)。所有文件统一走 sub=100/103+sliceupload, - * 不走小文件 PUT——QQ 客户端即使几百 KB 的文件也走 sliceupload。只有 sliceupload - * 路径会上报主文件 sha1/size,服务端据此把 fileset 标记为完成(对端可下载); - * PUT 路径不上报 sha1,fileset 会卡在"上传中"无法被下载。 - * - * 多文件:0x93d0 的 f4 是 repeated,一个 commit 请求同时携带 fileset 内所有文件 - * 条目,每条 f6=文件序号(1,2,3...)。commit 在上传前只发一次,之后 complete → - * 逐个 prepare/apply/sliceupload。prepare/apply 的 filesetWrap.f4 必须与 commit - * 的 f6 一致,否则文件不计入 fileset。ApplyFileset 的 fileName 是 fileset 显示名 - * (卡片标题):有 name 用 name,否则单文件用首文件名、多文件用「<首文件名>等N个文件」。 - * fileSize 用总和——服务端据此判定 fileset 为多文件。各文件在 commit 里用 - * 条目上的 name(若有),否则用路径 basename。 - * - * 源文件经 stageSourceToDisk 落到本地路径后流式哈希 / 分片读取,不再经 - * loadBinarySource 整文件进内存。本地与 HTTP 上限与群文件相同(4 GiB); - * 内联 base64 仍按 1 GiB 封顶,因为 stage 解码时会占用等量 RAM。 - */ - async createFlashTask( - files: FlashTaskFileInput | FlashTaskFileInput[], - name?: string, - _thumbPath?: string, - ): Promise<{ filesetId: string }> { - const fileList = normalizeFlashTaskInputs(files); - if (fileList.length === 0) throw new Error('create_flash_task: files is empty'); - const uploader = { - uin: this.ctx.identity.uin, - nickname: this.ctx.identity.nickname, - // Resolve our own uid rather than ship an empty one — a blank uploader - // uid drops the fileset if this runs before warmup populated selfUid. - uid: await resolveSelfUid(this.ctx), - }; - const items: StagedFlashItem[] = []; - try { - for (let i = 0; i < fileList.length; i++) { - const source = fileList[i]!.file; - if (!source) throw new Error('create_flash_task: files is empty'); - const staged = await stageSourceToDisk(source, flashStageMaxBytes(source)); - const fileName = flashFileDisplayName(fileList[i]!.name, staged.fileName); - const { formatCode } = FlashTransferApi.fileTypeCode(fileName); - items.push({ - filePath: staged.filePath, - fileSize: staged.fileSize, - fileName, - fileUuid: randomUUID(), - fileIndex: i + 1, - formatCode, - guardStat: await fsp.stat(staged.filePath), - cleanup: () => staged.cleanup(), + const fileId = FlashTransferApi.buildFileId(hashes.sha1, it.fileSize); + await ApplyUpload.invoke(this.ctx, { + filesetUuid, + fileUuid: it.fileUuid, + fileId, + fileName: it.fileName, + fileSize: it.fileSize, + md5: hashes.md5Hex, + sha1: hashes.sha1Hex, + fileIndex: it.fileIndex, + formatCode: it.formatCode, }); - if (staged.fileSize === 0) throw new Error('create_flash_task: file is empty'); - } - // 申请 fileset。fileName 是卡片/面板上的 fileset 标题;各文件真实名走 commit。 - // 未指定 name 时,多文件用「<首文件名>等N个文件」、fileSize 用总和, - // 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。 - const first = items[0]; - const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName); - const isMulti = items.length > 1; - const filesetName = name?.trim() - || (isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName); - const totalSize = items.reduce((s, it) => s + it.fileSize, 0); - const apply = await ApplyFileset.invoke(this.ctx, { - fileName: filesetName, origName: filesetName, - fileSize: totalSize, typeCode, uploader, - }); - const filesetUuid = apply.filesetUuid; - if (!filesetUuid) throw new Error('apply fileset failed: missing uuid'); - // 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号) - const commitEntries = items.map((it) => ({ - fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName, - fileSize: it.fileSize, formatCode: it.formatCode, fileIndex: it.fileIndex, - })); - await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries }); - await CompleteFileset.invoke(this.ctx, { filesetUuid }); - // 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。 - const prepared: { it: StagedFlashItem; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = []; - for (const it of items) { - const p = await this.prepareAndApply(filesetUuid, it); - if (p) prepared.push({ it, ...p }); - } - for (const p of prepared) { - await assertUnchanged(p.it.filePath, p.it.guardStat); - await this.sliceuploadFile( - p.it.filePath, p.it.fileSize, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName, - ); - } - // fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联 - await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1); - await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2); - await SetFilesetStatus.invoke(this.ctx, { filesetUuid }); - return { filesetId: filesetUuid }; - } finally { - await Promise.all(items.map((it) => it.cleanup())); + + if (rkey === null) { + return null; + } + + return { rkey, sha1StateV: hashes.sha1StateV, sliceCount: hashes.sliceCount }; } - } - /** - * 阶段1:流式哈希 + prepare(拿 rkey)+ apply(注册 fileId)。 - * 秒传时 prepare 不回 rkey,仍必须 apply,否则 fileset 会一直停在等待上传; - * 返回 null 只表示调用方跳过 sliceupload。 - */ - private async prepareAndApply( - filesetUuid: string, it: StagedFlashItem, - ): Promise<{ rkey: string; sha1StateV: Uint8Array[]; sliceCount: number } | null> { - const hashes = await hashFlashFileStreaming(it.filePath); - await assertUnchanged(it.filePath, it.guardStat); + /** + * 阶段2:从磁盘按 1 MiB 切片 POST sliceupload(所有文件 prepare+apply 完成后调用)。 + */ + private async sliceuploadFile( + filePath: string, + fileSize: number, + rkey: string, + sha1StateV: Uint8Array[], + sliceCount: number, + fileName: string, + ): Promise { + const src = await FileChunkSource.open(filePath, fileSize); - const rkey = await PrepareUpload.invoke(this.ctx, { - filesetUuid, fileUuid: it.fileUuid, fileName: it.fileName, fileSize: it.fileSize, - sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode, - }); - const fileId = FlashTransferApi.buildFileId(hashes.sha1, it.fileSize); - await ApplyUpload.invoke(this.ctx, { - filesetUuid, fileUuid: it.fileUuid, fileId, fileName: it.fileName, fileSize: it.fileSize, - md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode, - }); - if (rkey === null) return null; - return { rkey, sha1StateV: hashes.sha1StateV, sliceCount: hashes.sliceCount }; - } + try { + for (let i = 0; i < sliceCount; i++) { + const start = i * FLASH_SLICE_SIZE; + const chunkLen = Math.min(FLASH_SLICE_SIZE, fileSize - start); + const chunk = await src.read(start, chunkLen); + const chunkSha1 = new Uint8Array( + createHash('sha1').update(Buffer.from(chunk)).digest(), + ); + const body: FlashSliceUploadBody = { + field1: 0, + appid: 14901, + field3: 2, + payload: { + field1: {}, + rkey, + start, + end: start + chunkLen - 1, + sha1: chunkSha1, + sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) }, + chunk: new Uint8Array(chunk), + }, + }; + const bodyBytes = protobuf_encode(body); + await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`); + } + } finally { + await src.close(); + } + } - /** - * 阶段2:从磁盘按 1 MiB 切片 POST sliceupload(所有文件 prepare+apply 完成后调用)。 - */ - private async sliceuploadFile( - filePath: string, fileSize: number, rkey: string, - sha1StateV: Uint8Array[], sliceCount: number, fileName: string, - ): Promise { - const src = await FileChunkSource.open(filePath, fileSize); - try { - for (let i = 0; i < sliceCount; i++) { - const start = i * FLASH_SLICE_SIZE; - const chunkLen = Math.min(FLASH_SLICE_SIZE, fileSize - start); - const chunk = await src.read(start, chunkLen); - const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest()); + /** + * POST sliceupload 并校验响应。服务端即使 HTTP 200 也可能在业务体里返回错误, + * 所以必须解析 f5(status),非 "success" 视为失败。label 用于错误信息定位切片来源。 + */ + private async postSliceupload(bodyBytes: Uint8Array, label: string): Promise { + const resp = await fetch('https://multimedia.qfile.qq.com/sliceupload', { + method: 'POST', + body: bodyBytes, + headers: { + Accept: '*/*', + Connection: 'Keep-Alive', + 'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + 'Content-Length': String(bodyBytes.length), + 'X-Retried-Times': '1', + }, + }); + + if (!resp.ok) { + const errBody = await resp.text().catch(() => ''); + throw new Error(`${label} failed: HTTP ${resp.status} ${errBody.slice(0, 300)}`); + } + + const respBuf = new Uint8Array(await resp.arrayBuffer()); + const sliceResp = protobuf_decode(respBuf); + + if (sliceResp.status !== 'success') { + throw new Error(`${label} failed: ${sliceResp.status || 'no status in response'}`); + } + } + + /** + * 上传占位缩略图(png+jpg)。主文件上传后调用——主文件下载入口(0x93d3 的下载 + * fileId)需要缩略图关联才会被服务端填充,不传缩略图时 bot 自身上传的 fileset + * 无法被 download_fileset 解析。缩略图用随机纯色 PNG,无需 ffmpeg/sharp。 + * fileIndex 为缩略图在 fileset 内的序号(主文件之后递增),与 commit f6 对齐。 + */ + private async uploadThumbnail( + filesetUuid: string, + mainFileUuid: string, + thumbType: 'png' | 'jpg', + fileIndex: number, + ): Promise { + // 526x360 是 QQ 客户端缩略图尺寸;1x1 会被服务端拒(HTTP 400,宽高太小)。 + const width = 526, + height = 360; + const thumbBytes = generatePng(width, height); // 随机纯色,SHA1 不同避免秒传 + const appid = thumbType === 'png' ? 14903 : 14902; // png=14903, jpg=14902 + const fileUuid = thumbType === 'png' ? randomUUID() : mainFileUuid; // png 独立,jpg 挂主文件 + const fileName = + thumbType === 'png' + ? `${randomUUID().slice(0, 8)}_one.png` + : `${createHash('md5').update(thumbBytes).digest('hex').slice(0, 32)}.jpg`; + const hashes = computeHashes(new Uint8Array(thumbBytes)); + const fileSize = thumbBytes.length; + const thumbFormatCode = thumbType === 'png' ? 26 : 2; // png缩略图=26, jpg缩略图=2 + const rkey = await PrepareUpload.invoke(this.ctx, { + filesetUuid, + fileUuid, + fileName, + fileSize, + sha1: hashes.sha1Hex, + fileIndex, + formatCode: thumbFormatCode, + thumbType, + width, + height, + }); + const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize, appid); + await ApplyUpload.invoke(this.ctx, { + filesetUuid, + fileUuid, + fileId, + fileName, + fileSize, + md5: hashes.md5Hex, + sha1: hashes.sha1Hex, + fileIndex, + formatCode: thumbFormatCode, + thumbType, + width, + height, + }); + + if (rkey === null) { + return; + } + + // sliceupload(缩略图小,1 片,Sha1StateV=[标准 SHA1]) + const sha1StateV = computeSha1StateV(new Uint8Array(thumbBytes), 1, fileSize); const body: FlashSliceUploadBody = { - field1: 0, - appid: 14901, - field3: 2, - payload: { - field1: {}, - rkey, - start, - end: start + chunkLen - 1, - sha1: chunkSha1, - sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) }, - chunk: new Uint8Array(chunk), - }, + field1: 0, + appid, + field3: 2, + payload: { + field1: {}, + rkey, + start: 0, + end: fileSize - 1, + sha1: new Uint8Array(hashes.sha1), + sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) }, + chunk: new Uint8Array(thumbBytes), + }, }; const bodyBytes = protobuf_encode(body); - await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`); - } - } finally { - await src.close(); + await this.postSliceupload(bodyBytes, 'thumbnail sliceupload'); } - } - - /** - * POST sliceupload 并校验响应。服务端即使 HTTP 200 也可能在业务体里返回错误, - * 所以必须解析 f5(status),非 "success" 视为失败。label 用于错误信息定位切片来源。 - */ - private async postSliceupload(bodyBytes: Uint8Array, label: string): Promise { - const resp = await fetch('https://multimedia.qfile.qq.com/sliceupload', { - method: 'POST', body: bodyBytes, - headers: { - Accept: '*/*', Connection: 'Keep-Alive', - 'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)', - Pragma: 'no-cache', 'Cache-Control': 'no-cache', - 'Content-Length': String(bodyBytes.length), - 'X-Retried-Times': '1', - }, - }); - if (!resp.ok) { - const errBody = await resp.text().catch(() => ''); - throw new Error(`${label} failed: HTTP ${resp.status} ${errBody.slice(0, 300)}`); - } - const respBuf = new Uint8Array(await resp.arrayBuffer()); - const sliceResp = protobuf_decode(respBuf); - if (sliceResp.status !== 'success') { - throw new Error(`${label} failed: ${sliceResp.status || 'no status in response'}`); - } - } - - /** - * 上传占位缩略图(png+jpg)。主文件上传后调用——主文件下载入口(0x93d3 的下载 - * fileId)需要缩略图关联才会被服务端填充,不传缩略图时 bot 自身上传的 fileset - * 无法被 download_fileset 解析。缩略图用随机纯色 PNG,无需 ffmpeg/sharp。 - * fileIndex 为缩略图在 fileset 内的序号(主文件之后递增),与 commit f6 对齐。 - */ - private async uploadThumbnail( - filesetUuid: string, mainFileUuid: string, thumbType: 'png' | 'jpg', fileIndex: number, - ): Promise { - // 526x360 是 QQ 客户端缩略图尺寸;1x1 会被服务端拒(HTTP 400,宽高太小)。 - const width = 526, height = 360; - const thumbBytes = generatePng(width, height); // 随机纯色,SHA1 不同避免秒传 - const appid = thumbType === 'png' ? 14903 : 14902; // png=14903, jpg=14902 - const fileUuid = thumbType === 'png' ? randomUUID() : mainFileUuid; // png 独立,jpg 挂主文件 - const fileName = thumbType === 'png' - ? `${randomUUID().slice(0, 8)}_one.png` - : `${createHash('md5').update(thumbBytes).digest('hex').slice(0, 32)}.jpg`; - const hashes = computeHashes(new Uint8Array(thumbBytes)); - const fileSize = thumbBytes.length; - const thumbFormatCode = thumbType === 'png' ? 26 : 2; // png缩略图=26, jpg缩略图=2 - const rkey = await PrepareUpload.invoke(this.ctx, { - filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex, - fileIndex, formatCode: thumbFormatCode, thumbType, width, height, - }); - const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize, appid); - await ApplyUpload.invoke(this.ctx, { - filesetUuid, fileUuid, fileId, fileName, fileSize, - md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode: thumbFormatCode, thumbType, width, height, - }); - if (rkey === null) return; - // sliceupload(缩略图小,1 片,Sha1StateV=[标准 SHA1]) - const sha1StateV = computeSha1StateV(new Uint8Array(thumbBytes), 1, fileSize); - const body: FlashSliceUploadBody = { - field1: 0, appid, field3: 2, - payload: { - field1: {}, rkey, - start: 0, end: fileSize - 1, - sha1: new Uint8Array(hashes.sha1), - sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) }, - chunk: new Uint8Array(thumbBytes), - }, - }; - const bodyBytes = protobuf_encode(body); - await this.postSliceupload(bodyBytes, 'thumbnail sliceupload'); - } } diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/bridge/apis/forward.ts index d4ee369c..cf6af8fb 100644 --- a/packages/core/src/bridge/apis/forward.ts +++ b/packages/core/src/bridge/apis/forward.ts @@ -2,18 +2,22 @@ import type { PacketInfo } from '@snowluma/common/protocol-types'; import { mapWithConcurrency } from '@snowluma/common/concurrency'; import { createLogger } from '@snowluma/common/logger'; import type { - LongMsgResult, - RecvLongMsgReq, - RecvLongMsgResp, - SendLongMsgReq, - SendLongMsgResp, + LongMsgResult, + RecvLongMsgReq, + RecvLongMsgResp, + SendLongMsgReq, + SendLongMsgResp, } from '@snowluma/proto-defs/longmsg'; import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message'; import { buildSendElems } from '@snowluma/protocol/element-builder'; -import type { ForwardNodePayload, MessageElement, MessageElementOf } from '@snowluma/protocol/events'; +import type { + ForwardNodePayload, + MessageElement, + MessageElementOf, +} from '@snowluma/protocol/events'; import { - assertWindowShakeSendPolicy, - MessageElementValidationError, + assertWindowShakeSendPolicy, + MessageElementValidationError, } from '@snowluma/protocol/element-manifest'; import { parseMsgPush } from '@snowluma/protocol/msg-push'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; @@ -23,7 +27,9 @@ import type { Bridge } from '../bridge'; import type { BridgeContext, UploadedFileMeta } from '../bridge-context'; import { resolveSelfUid, toInt } from './shared'; -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } +function asBridge(ctx: BridgeContext): Bridge { + return ctx as unknown as Bridge; +} // Module-scoped cache, keyed by res_id. Survives only for the lifetime // of the process — that's enough because OneBot clients typically @@ -57,137 +63,149 @@ const FORWARD_PROFILE_CONCURRENCY = 4; // both ship a single-action model and silently break when the // recipient is a NapCat instance trying to walk the tree. interface ForwardInnerAction { - uuid: string; - msgBody: PushMsgBody[]; + uuid: string; + msgBody: PushMsgBody[]; } interface ForwardUploadResult { - resId: string; - // The current level's msgBody + uuid — what an outer caller would - // piggyback to expose this layer through the tree. - msgBody: PushMsgBody[]; - uuid: string; - // All accumulated piggyback entries from deeper levels. Outer - // callers concatenate these to their own actions list so the - // outermost upload carries the full tree. - innerActions: ForwardInnerAction[]; + resId: string; + // The current level's msgBody + uuid — what an outer caller would + // piggyback to expose this layer through the tree. + msgBody: PushMsgBody[]; + uuid: string; + // All accumulated piggyback entries from deeper levels. Outer + // callers concatenate these to their own actions list so the + // outermost upload carries the full tree. + innerActions: ForwardInnerAction[]; } // Local hex-decode helper — avoids importing the heavyweight `pipeline` // module just for one call. Mirrors `highway/pipeline.ts::hexToBytes`. function hexToBytesLocal(hex: string): Uint8Array { - const s = hex.trim(); - if (!s) return new Uint8Array(0); - const len = s.length >> 1; - const out = new Uint8Array(len); - for (let i = 0; i < len; i++) { - out[i] = parseInt(s.substr(i * 2, 2), 16); - } - return out; + const s = hex.trim(); + + if (!s) { + return new Uint8Array(0); + } + + const len = s.length >> 1; + const out = new Uint8Array(len); + + for (let i = 0; i < len; i++) { + out[i] = parseInt(s.substr(i * 2, 2), 16); + } + + return out; } async function buildForwardPushBody( - bridge: Bridge, - node: ForwardNodePayload, - groupId?: number, - userUid?: string, + bridge: Bridge, + node: ForwardNodePayload, + groupId?: number, + userUid?: string, ): Promise { - const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin); - if (fromUin <= 0) throw new Error('forward node user uin is invalid'); + const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin); - const nickname = node.nickname.trim() || String(fromUin); - // image/record/video upload inside a forward node must be scoped to the - // forward's recipient: group → groupId, private → recipient uid. - // Without this the OIDB upload (0x11c4/0x11c5) has no scene and the - // element builder throws "private image target uid is missing". - // - // `forwardFake: true` keeps `{type:'file'}` segments in the - // long-msg payload: group → emitted as transElem(24) in elems[], - // c2c → handled below via msgContent (FileExtra { file: NotOnlineFile }). - // The QQ-NT live-send pipeline would reject these (transElem(24) → - // result=79; notOnlineFile via PbSendMsg doesn't render), but the - // long-msg upload service stores the bytes verbatim and the - // receiver decodes them through the normal msg-push path. - const sendCtx = groupId !== undefined - ? { bridge, groupId, forwardFake: true, scene: 'forward' as const } - : userUid - ? { bridge, userUid, forwardFake: true, scene: 'forward' as const } - : { bridge, forwardFake: true, scene: 'forward' as const }; - const elems = await buildSendElems(node.elements, sendCtx); - const now = Math.floor(Date.now() / 1000); - const random = Math.floor(Math.random() * 0x7fffffff) >>> 0; - const seq = Math.floor(Math.random() * 9000000) + 1000000; - - // c2c-file in a forward node — element-builder intentionally skips - // it (RichText.notOnlineFile + msgContent live outside elems[]). For - // forward fake-send we mirror what an inbound c2c file message looks - // like on the wire: serialise the FileExtra blob and ride it on - // `body.msgContent`. The receiver's rich-body-decoder reads from - // `msgContent` first (see msg-push/rich-body-decoder.ts:446+), so - // the bubble renders with the right file name + size when the - // forward is expanded. Only the FIRST c2c file in a node ships — - // QQ NT's bubble can only carry one msgContent payload, same as - // a live c2c send. Group nodes ignore this branch entirely (the - // transElem(24) elems[] entry above covers them). - let msgContent: Uint8Array | undefined; - if (groupId === undefined) { - const fileEl = node.elements.find(e => e.type === 'file' && e.fileId); - if (fileEl) { - // Honour inline segment fields first; fall back to the upload - // metadata cache (populated by upload_private_file). Without - // size/md5 the receiver would render "0 B" so prefer recovering - // them — see same logic in modules/message-actions.ts. - const cached = bridge.recallUploadedFile(fileEl.fileId ?? ''); - const fileMd5 = fileEl.md5Hex - ? hexToBytesLocal(fileEl.md5Hex) - : (cached?.fileMd5 ?? new Uint8Array(0)); - const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0; - const fileName = fileEl.fileName ?? cached?.fileName ?? 'file'; - const fileHash = fileEl.fileHash ?? cached?.fileHash ?? ''; - const sevenDays = 7 * 24 * 60 * 60; - msgContent = protobuf_encode({ - file: { - fileType: 0, - fileUuid: fileEl.fileId!, - fileMd5, - fileName, - fileSize: BigInt(fileSize), - subcmd: 1, - dangerEvel: 0, - expireTime: now + sevenDays, - fileHash, - }, - }); + if (fromUin <= 0) { + throw new Error('forward node user uin is invalid'); } - } - return { - responseHead: { - fromUin, - // Resolve our own uid rather than ship an empty one — a blank toUid is a - // broken packet if this runs before warmup populated selfUid. - toUid: await resolveSelfUid(bridge), - forward: { - friendName: nickname, - }, - }, - contentHead: { - msgType: 9, - subType: 4, - msgId: random, - sequence: seq, - // Honour a custom per-node display time (#209); default to now. `now` - // still drives the c2c-file expireTime above, which must stay real. - timestamp: node.time && node.time > 0 ? node.time : now, - c2cCmd: 0, - }, - body: { - richText: { - elems, - }, - ...(msgContent ? { msgContent } : {}), - }, - }; + const nickname = node.nickname.trim() || String(fromUin); + // image/record/video upload inside a forward node must be scoped to the + // forward's recipient: group → groupId, private → recipient uid. + // Without this the OIDB upload (0x11c4/0x11c5) has no scene and the + // element builder throws "private image target uid is missing". + // + // `forwardFake: true` keeps `{type:'file'}` segments in the + // long-msg payload: group → emitted as transElem(24) in elems[], + // c2c → handled below via msgContent (FileExtra { file: NotOnlineFile }). + // The QQ-NT live-send pipeline would reject these (transElem(24) → + // result=79; notOnlineFile via PbSendMsg doesn't render), but the + // long-msg upload service stores the bytes verbatim and the + // receiver decodes them through the normal msg-push path. + const sendCtx = + groupId !== undefined + ? { bridge, groupId, forwardFake: true, scene: 'forward' as const } + : userUid + ? { bridge, userUid, forwardFake: true, scene: 'forward' as const } + : { bridge, forwardFake: true, scene: 'forward' as const }; + const elems = await buildSendElems(node.elements, sendCtx); + const now = Math.floor(Date.now() / 1000); + const random = Math.floor(Math.random() * 0x7fffffff) >>> 0; + const seq = Math.floor(Math.random() * 9000000) + 1000000; + + // c2c-file in a forward node — element-builder intentionally skips + // it (RichText.notOnlineFile + msgContent live outside elems[]). For + // forward fake-send we mirror what an inbound c2c file message looks + // like on the wire: serialise the FileExtra blob and ride it on + // `body.msgContent`. The receiver's rich-body-decoder reads from + // `msgContent` first (see msg-push/rich-body-decoder.ts:446+), so + // the bubble renders with the right file name + size when the + // forward is expanded. Only the FIRST c2c file in a node ships — + // QQ NT's bubble can only carry one msgContent payload, same as + // a live c2c send. Group nodes ignore this branch entirely (the + // transElem(24) elems[] entry above covers them). + let msgContent: Uint8Array | undefined; + + if (groupId === undefined) { + const fileEl = node.elements.find((e) => e.type === 'file' && e.fileId); + + if (fileEl) { + // Honour inline segment fields first; fall back to the upload + // metadata cache (populated by upload_private_file). Without + // size/md5 the receiver would render "0 B" so prefer recovering + // them — see same logic in modules/message-actions.ts. + const cached = bridge.recallUploadedFile(fileEl.fileId ?? ''); + const fileMd5 = fileEl.md5Hex + ? hexToBytesLocal(fileEl.md5Hex) + : (cached?.fileMd5 ?? new Uint8Array(0)); + const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0; + const fileName = fileEl.fileName ?? cached?.fileName ?? 'file'; + const fileHash = fileEl.fileHash ?? cached?.fileHash ?? ''; + const sevenDays = 7 * 24 * 60 * 60; + msgContent = protobuf_encode({ + file: { + fileType: 0, + fileUuid: fileEl.fileId!, + fileMd5, + fileName, + fileSize: BigInt(fileSize), + subcmd: 1, + dangerEvel: 0, + expireTime: now + sevenDays, + fileHash, + }, + }); + } + } + + return { + responseHead: { + fromUin, + // Resolve our own uid rather than ship an empty one — a blank toUid is a + // broken packet if this runs before warmup populated selfUid. + toUid: await resolveSelfUid(bridge), + forward: { + friendName: nickname, + }, + }, + contentHead: { + msgType: 9, + subType: 4, + msgId: random, + sequence: seq, + // Honour a custom per-node display time (#209); default to now. `now` + // still drives the c2c-file expireTime above, which must stay real. + timestamp: node.time && node.time > 0 ? node.time : now, + c2cCmd: 0, + }, + body: { + richText: { + elems, + }, + ...(msgContent ? { msgContent } : {}), + }, + }; } // Inner forward preview metadata — kept minimal here (the OneBot @@ -196,647 +214,872 @@ async function buildForwardPushBody( // non-nested send path; nested levels just get sensible defaults // since they're synthesised by us and never reach OneBot input). function deriveInnerSource(innerNodes: ForwardNodePayload[], isGroup: boolean): string { - const nicks: string[] = []; - const seen = new Set(); - for (const node of innerNodes) { - const name = (node.nickname ?? '').trim(); - if (name && !seen.has(name)) { - seen.add(name); - nicks.push(name); + const nicks: string[] = []; + const seen = new Set(); + + for (const node of innerNodes) { + const name = (node.nickname ?? '').trim(); + + if (name && !seen.has(name)) { + seen.add(name); + nicks.push(name); + } + + if (nicks.length >= 4) { + break; + } } - if (nicks.length >= 4) break; - } - if (nicks.length === 0) return isGroup ? '群聊的聊天记录' : '聊天记录'; - return `${nicks.join('和')}的聊天记录`; + + if (nicks.length === 0) { + return isGroup ? '群聊的聊天记录' : '聊天记录'; + } + + return `${nicks.join('和')}的聊天记录`; } function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> { - return innerNodes.slice(0, 4).map(node => { - const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户'); - const previewText = previewFromElements(node.elements); - return { text: previewText ? `${name}: ${previewText}` : name }; - }); + return innerNodes.slice(0, 4).map((node) => { + const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户'); + const previewText = previewFromElements(node.elements); + return { text: previewText ? `${name}: ${previewText}` : name }; + }); } function previewFromElements(elements: MessageElement[]): string { - for (const elem of elements) { - if (elem.type === 'text' && elem.text) return elem.text.slice(0, 30); - if (elem.type === 'image') return '[图片]'; - if (elem.type === 'record') return '[语音]'; - if (elem.type === 'video') return '[视频]'; - if (elem.type === 'file') return '[文件]'; - if (elem.type === 'forward') return '[聊天记录]'; - if (elem.type === 'face') return '[表情]'; - } - return ''; + for (const elem of elements) { + if (elem.type === 'text' && elem.text) { + return elem.text.slice(0, 30); + } + + if (elem.type === 'image') { + return '[图片]'; + } + + if (elem.type === 'record') { + return '[语音]'; + } + + if (elem.type === 'video') { + return '[视频]'; + } + + if (elem.type === 'file') { + return '[文件]'; + } + + if (elem.type === 'forward') { + return '[聊天记录]'; + } + + if (elem.type === 'face') { + return '[表情]'; + } + } + + return ''; } -function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload { - return { - ...node, - elements, - news: node.news?.map(item => ({ ...item })), - }; +function cloneNodeWithElements( + node: ForwardNodePayload, + elements: MessageElement[], +): ForwardNodePayload { + return { + ...node, + elements, + news: node.news?.map((item) => ({ ...item })), + }; } function stripFileSource(element: MessageElementOf<'file'>): MessageElementOf<'file'> { - const next: MessageElementOf<'file'> = { ...element }; - delete next.url; - return next; + const next: MessageElementOf<'file'> = { ...element }; + delete next.url; + return next; } function isCachedFileUsableInTarget( - cached: UploadedFileMeta | undefined, - groupId?: number, - userId?: number, + cached: UploadedFileMeta | undefined, + groupId?: number, + userId?: number, ): boolean { - if (!cached) return true; - if (groupId !== undefined) { - return cached.scope === 'group' && cached.groupId === groupId; - } - if (userId !== undefined) { - return cached.scope === 'private' && cached.userId === userId; - } - return true; + if (!cached) { + return true; + } + + if (groupId !== undefined) { + return cached.scope === 'group' && cached.groupId === groupId; + } + + if (userId !== undefined) { + return cached.scope === 'private' && cached.userId === userId; + } + + return true; } function fileNameForUpload(element: MessageElement, cached?: UploadedFileMeta): string { - return (element.fileName ?? cached?.fileName ?? '').trim(); + return (element.fileName ?? cached?.fileName ?? '').trim(); } function assertPrivateForwardFileCapacity(nodes: ForwardNodePayload[]): void { - for (const node of nodes) { - const fileCount = node.elements.filter((element) => element.type === 'file').length; - if (fileCount > 1) { - throw new MessageElementValidationError( - 'UNSENDABLE_TYPE', - 'a private forward node can contain at most one file element', - 'file', - ); + for (const node of nodes) { + const fileCount = node.elements.filter((element) => element.type === 'file').length; + + if (fileCount > 1) { + throw new MessageElementValidationError( + 'UNSENDABLE_TYPE', + 'a private forward node can contain at most one file element', + 'file', + ); + } + + if (node.innerForward) { + assertPrivateForwardFileCapacity(node.innerForward); + } } - if (node.innerForward) assertPrivateForwardFileCapacity(node.innerForward); - } } function assertNoWindowShakeInForward(nodes: ForwardNodePayload[]): void { - for (const node of nodes) { - assertWindowShakeSendPolicy( - node.elements.filter((element) => element.type === 'poke').length, - node.elements.length, - 'forward', - ); - if (node.innerForward) assertNoWindowShakeInForward(node.innerForward); - } + for (const node of nodes) { + assertWindowShakeSendPolicy( + node.elements.filter((element) => element.type === 'poke').length, + node.elements.length, + 'forward', + ); + + if (node.innerForward) { + assertNoWindowShakeInForward(node.innerForward); + } + } } export class ForwardApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise { - // Reject the complete recursive tree before identity resolution, media - // upload, or long-message upload. Window shake has no forward wire form. - assertNoWindowShakeInForward(nodes); - // A c2c RichText owns exactly one msgContent/FileExtra payload. Validate - // the entire recursive tree before any file/media/long-message upload so a - // second file cannot be uploaded and then silently discarded. - if (groupId === undefined) assertPrivateForwardFileCapacity(nodes); - const { resId } = await this.uploadRecursive(nodes, groupId, userId); - return resId; - } + async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise { + // Reject the complete recursive tree before identity resolution, media + // upload, or long-message upload. Window shake has no forward wire form. + assertNoWindowShakeInForward(nodes); - private async downloadSourceFromCachedFile(cached: UploadedFileMeta): Promise { - if (cached.scope === 'group' && cached.groupId !== undefined) { - return this.ctx.apis.groupFile.getUrl(cached.groupId, cached.fileId); - } - if (cached.scope === 'private' && cached.userId !== undefined && cached.fileHash) { - return this.ctx.apis.groupFile.getPrivateUrl(cached.userId, cached.fileId, cached.fileHash); - } - throw new Error('forward file_id belongs to another scope; pass file/base64/url so SnowLuma can re-upload it'); - } + // A c2c RichText owns exactly one msgContent/FileExtra payload. Validate + // the entire recursive tree before any file/media/long-message upload so a + // second file cannot be uploaded and then silently discarded. + if (groupId === undefined) { + assertPrivateForwardFileCapacity(nodes); + } - private async uploadForwardFileSource( - source: string, - name: string, - groupId?: number, - userId?: number, - ): Promise> { - if (groupId !== undefined) { - const uploaded = await this.ctx.apis.groupFile.upload(groupId, source, name, '/', true, false); - if (!uploaded.fileId) throw new Error('forward group file upload returned no file_id'); - const cached = this.ctx.recallUploadedFile(uploaded.fileId); - const element: MessageElement = { - type: 'file', - fileId: uploaded.fileId, - }; - const fileName = cached?.fileName || name; - if (fileName) element.fileName = fileName; - if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize; - return element; - } - if (userId !== undefined) { - const uploaded = await this.ctx.apis.groupFile.uploadPrivate(userId, source, name, true, false); - if (!uploaded.fileId) throw new Error('forward private file upload returned no file_id'); - const cached = this.ctx.recallUploadedFile(uploaded.fileId); - const element: MessageElement = { - type: 'file', - fileId: uploaded.fileId, - }; - const fileName = cached?.fileName || name; - const fileHash = uploaded.fileHash ?? cached?.fileHash ?? ''; - if (fileName) element.fileName = fileName; - if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize; - if (fileHash) element.fileHash = fileHash; - return element; - } - throw new Error('forward file source requires group_id or user_id'); - } - - private async prepareForwardFileElement( - element: MessageElement, - groupId?: number, - userId?: number, - ): Promise { - if (element.type !== 'file') return element; - - const source = (element.url ?? '').trim(); - if (source && !element.fileId) { - const uploaded = await this.uploadForwardFileSource(source, fileNameForUpload(element), groupId, userId); - return { - ...stripFileSource(element), - ...uploaded, - }; + const { resId } = await this.uploadRecursive(nodes, groupId, userId); + return resId; } - if (element.fileId) { - const cached = this.ctx.recallUploadedFile(element.fileId); - if (isCachedFileUsableInTarget(cached, groupId, userId)) return element; - const sourceFromCache = await this.downloadSourceFromCachedFile(cached!); - const uploaded = await this.uploadForwardFileSource( - sourceFromCache, - fileNameForUpload(element, cached), - groupId, - userId, - ); - return { - ...stripFileSource(element), - ...uploaded, - }; + private async downloadSourceFromCachedFile(cached: UploadedFileMeta): Promise { + if (cached.scope === 'group' && cached.groupId !== undefined) { + return this.ctx.apis.groupFile.getUrl(cached.groupId, cached.fileId); + } + + if (cached.scope === 'private' && cached.userId !== undefined && cached.fileHash) { + return this.ctx.apis.groupFile.getPrivateUrl( + cached.userId, + cached.fileId, + cached.fileHash, + ); + } + + throw new Error( + 'forward file_id belongs to another scope; pass file/base64/url so SnowLuma can re-upload it', + ); } - return element; - } + private async uploadForwardFileSource( + source: string, + name: string, + groupId?: number, + userId?: number, + ): Promise> { + if (groupId !== undefined) { + const uploaded = await this.ctx.apis.groupFile.upload( + groupId, + source, + name, + '/', + true, + false, + ); - private async prepareForwardFiles( - nodes: ForwardNodePayload[], - groupId?: number, - userId?: number, - ): Promise { - return Promise.all(nodes.map(async (node) => { - const elements = await Promise.all(node.elements.map( - element => this.prepareForwardFileElement(element, groupId, userId), - )); - return cloneNodeWithElements(node, elements); - })); - } + if (!uploaded.fileId) { + throw new Error('forward group file upload returned no file_id'); + } - /** - * Recursive upload with NapCat-style piggyback. Each invocation: - * 1. Walks `nodes`. For any node whose `innerForward` is set, - * recursively uploads that inner chain first (which itself runs - * this same recursion). - * 2. Replaces the node's `elements` with an ARK preview pointing at - * the inner res_id (and inner uuid for receiver-side walking). - * 3. Accumulates the inner level's `{uuid, msgBody}` plus all of - * ITS accumulated `innerActions` into this level's piggyback list. - * 4. Encodes this level's long-msg payload as - * `[MultiMsg + thisMsgBody, ...innerActions]`, uploads it, - * returns `{resId, msgBody, uuid, innerActions}` so an outer - * caller can keep piggybacking up the tree. - */ - private async uploadRecursive( - nodes: ForwardNodePayload[], - groupId?: number, - userId?: number, - ): Promise { - if (!Array.isArray(nodes) || nodes.length === 0) { - throw new Error('forward nodes are required'); + const cached = this.ctx.recallUploadedFile(uploaded.fileId); + const element: MessageElement = { + type: 'file', + fileId: uploaded.fileId, + }; + const fileName = cached?.fileName || name; + + if (fileName) { + element.fileName = fileName; + } + + if (cached?.fileSize !== undefined) { + element.fileSize = cached.fileSize; + } + + return element; + } + + if (userId !== undefined) { + const uploaded = await this.ctx.apis.groupFile.uploadPrivate( + userId, + source, + name, + true, + false, + ); + + if (!uploaded.fileId) { + throw new Error('forward private file upload returned no file_id'); + } + + const cached = this.ctx.recallUploadedFile(uploaded.fileId); + const element: MessageElement = { + type: 'file', + fileId: uploaded.fileId, + }; + const fileName = cached?.fileName || name; + const fileHash = uploaded.fileHash ?? cached?.fileHash ?? ''; + + if (fileName) { + element.fileName = fileName; + } + + if (cached?.fileSize !== undefined) { + element.fileSize = cached.fileSize; + } + + if (fileHash) { + element.fileHash = fileHash; + } + + return element; + } + + throw new Error('forward file source requires group_id or user_id'); } - const bridge = asBridge(this.ctx); + private async prepareForwardFileElement( + element: MessageElement, + groupId?: number, + userId?: number, + ): Promise { + if (element.type !== 'file') { + return element; + } - // For a private forward to `userId`, any image/record/video inside a node - // needs the recipient's uid as upload scene. Resolve it once up-front, - // and only when at least one node actually contains media (saves an RPC - // for text-only forwards). Also need it when a node is itself a nested - // forward — the inner upload uses the same scene. - let userUid: string | undefined; - if (groupId === undefined && userId !== undefined && userId > 0) { - const needsUid = nodes.some(node => !!node.innerForward - || node.elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video')); - if (needsUid) { - const resolved = await this.ctx.resolveUserUid(userId); - if (resolved) userUid = resolved; - } + const source = (element.url ?? '').trim(); + + if (source && !element.fileId) { + const uploaded = await this.uploadForwardFileSource( + source, + fileNameForUpload(element), + groupId, + userId, + ); + return { + ...stripFileSource(element), + ...uploaded, + }; + } + + if (element.fileId) { + const cached = this.ctx.recallUploadedFile(element.fileId); + + if (isCachedFileUsableInTarget(cached, groupId, userId)) { + return element; + } + + const sourceFromCache = await this.downloadSourceFromCachedFile(cached!); + const uploaded = await this.uploadForwardFileSource( + sourceFromCache, + fileNameForUpload(element, cached), + groupId, + userId, + ); + return { + ...stripFileSource(element), + ...uploaded, + }; + } + + return element; } - // Walk nodes and resolve nested forwards first (so we know their - // res_id / uuid before encoding the outer ARK previews). Build - // `processedNodes` with elements rewritten for nested layers, - // and collect every inner level's piggyback in `myInnerActions`. - // - // CRITICAL: the same uuid (`inner.uuid`) MUST be baked into the - // outer's preview element as `forwardUuid` AND used as the - // `actionCommand` for the outer's piggyback entry. That's the - // alignment the QQ-NT receiver uses to find the inner layer - // inside the outer's LongMsgResult without a second server fetch - // — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round- - // trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`. - const myInnerActions: ForwardInnerAction[] = []; - const processedNodes: ForwardNodePayload[] = []; - const isGroup = groupId !== undefined; - for (const node of nodes) { - if (node.innerForward && node.innerForward.length > 0) { - const inner = await this.uploadRecursive(node.innerForward, groupId, userId); - // NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}` - // + the entire `inner.innerPacketMsg` array up to its caller. We - // mirror that — `inner.uuid` indexes the inner level itself, - // and `inner.innerActions` already contains deeper layers. - myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody }); - myInnerActions.push(...inner.innerActions); - // Replace the inner placeholder element with a forward preview - // pointing at the inner res_id. `forwardUuid: inner.uuid` - // baked into the LightApp JSON's `meta.detail.uniseq` is what - // closes the loop with our piggyback action above. - const previewElement: MessageElement = { - type: 'forward', - resId: inner.resId, - forwardUuid: inner.uuid, - forwardSource: node.source && node.source.length > 0 - ? node.source - : deriveInnerSource(node.innerForward, isGroup), - forwardSummary: node.summary && node.summary.length > 0 - ? node.summary - : `查看${node.innerForward.length}条转发消息`, - forwardPrompt: node.prompt && node.prompt.length > 0 - ? node.prompt - : '[聊天记录]', - forwardNews: node.news && node.news.length > 0 ? node.news : previewLinesFromNodes(node.innerForward), - forwardTSum: node.innerForward.length, + private async prepareForwardFiles( + nodes: ForwardNodePayload[], + groupId?: number, + userId?: number, + ): Promise { + return Promise.all( + nodes.map(async (node) => { + const elements = await Promise.all( + node.elements.map((element) => + this.prepareForwardFileElement(element, groupId, userId), + ), + ); + return cloneNodeWithElements(node, elements); + }), + ); + } + + /** + * Recursive upload with NapCat-style piggyback. Each invocation: + * 1. Walks `nodes`. For any node whose `innerForward` is set, + * recursively uploads that inner chain first (which itself runs + * this same recursion). + * 2. Replaces the node's `elements` with an ARK preview pointing at + * the inner res_id (and inner uuid for receiver-side walking). + * 3. Accumulates the inner level's `{uuid, msgBody}` plus all of + * ITS accumulated `innerActions` into this level's piggyback list. + * 4. Encodes this level's long-msg payload as + * `[MultiMsg + thisMsgBody, ...innerActions]`, uploads it, + * returns `{resId, msgBody, uuid, innerActions}` so an outer + * caller can keep piggybacking up the tree. + */ + private async uploadRecursive( + nodes: ForwardNodePayload[], + groupId?: number, + userId?: number, + ): Promise { + if (!Array.isArray(nodes) || nodes.length === 0) { + throw new Error('forward nodes are required'); + } + + const bridge = asBridge(this.ctx); + + // For a private forward to `userId`, any image/record/video inside a node + // needs the recipient's uid as upload scene. Resolve it once up-front, + // and only when at least one node actually contains media (saves an RPC + // for text-only forwards). Also need it when a node is itself a nested + // forward — the inner upload uses the same scene. + let userUid: string | undefined; + + if (groupId === undefined && userId !== undefined && userId > 0) { + const needsUid = nodes.some( + (node) => + !!node.innerForward || + node.elements.some( + (e) => e.type === 'image' || e.type === 'record' || e.type === 'video', + ), + ); + + if (needsUid) { + const resolved = await this.ctx.resolveUserUid(userId); + + if (resolved) { + userUid = resolved; + } + } + } + + // Walk nodes and resolve nested forwards first (so we know their + // res_id / uuid before encoding the outer ARK previews). Build + // `processedNodes` with elements rewritten for nested layers, + // and collect every inner level's piggyback in `myInnerActions`. + // + // CRITICAL: the same uuid (`inner.uuid`) MUST be baked into the + // outer's preview element as `forwardUuid` AND used as the + // `actionCommand` for the outer's piggyback entry. That's the + // alignment the QQ-NT receiver uses to find the inner layer + // inside the outer's LongMsgResult without a second server fetch + // — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round- + // trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`. + const myInnerActions: ForwardInnerAction[] = []; + const processedNodes: ForwardNodePayload[] = []; + const isGroup = groupId !== undefined; + + for (const node of nodes) { + if (node.innerForward && node.innerForward.length > 0) { + const inner = await this.uploadRecursive(node.innerForward, groupId, userId); + // NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}` + // + the entire `inner.innerPacketMsg` array up to its caller. We + // mirror that — `inner.uuid` indexes the inner level itself, + // and `inner.innerActions` already contains deeper layers. + myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody }); + myInnerActions.push(...inner.innerActions); + // Replace the inner placeholder element with a forward preview + // pointing at the inner res_id. `forwardUuid: inner.uuid` + // baked into the LightApp JSON's `meta.detail.uniseq` is what + // closes the loop with our piggyback action above. + const previewElement: MessageElement = { + type: 'forward', + resId: inner.resId, + forwardUuid: inner.uuid, + forwardSource: + node.source && node.source.length > 0 + ? node.source + : deriveInnerSource(node.innerForward, isGroup), + forwardSummary: + node.summary && node.summary.length > 0 + ? node.summary + : `查看${node.innerForward.length}条转发消息`, + forwardPrompt: + node.prompt && node.prompt.length > 0 ? node.prompt : '[聊天记录]', + forwardNews: + node.news && node.news.length > 0 + ? node.news + : previewLinesFromNodes(node.innerForward), + forwardTSum: node.innerForward.length, + }; + const processed = cloneNodeWithElements(node, [previewElement]); + delete processed.innerForward; + processedNodes.push(processed); + } else { + processedNodes.push(node); + } + } + + const uploadReadyNodes = await this.prepareForwardFiles(processedNodes, groupId, userId); + + // Encode this level's msgBody. + const msgBody = await Promise.all( + uploadReadyNodes.map((node) => buildForwardPushBody(bridge, node, groupId, userUid)), + ); + + // Compose the action list: own MultiMsg + piggybacked inner actions. + const longMsgResult = protobuf_encode({ + action: [ + { actionCommand: 'MultiMsg', actionData: { msgBody } }, + ...myInnerActions.map((a) => ({ + actionCommand: a.uuid, + actionData: { msgBody: a.msgBody }, + })), + ], + }); + + const selfUid = await resolveSelfUid(bridge); + const info: SendLongMsgReq['info'] = { + type: groupId ? 3 : 1, + uid: { uid: groupId ? String(groupId) : selfUid }, + payload: gzipSync(Buffer.from(longMsgResult)), }; - const processed = cloneNodeWithElements(node, [previewElement]); - delete processed.innerForward; - processedNodes.push(processed); - } else { - processedNodes.push(node); - } - } - const uploadReadyNodes = await this.prepareForwardFiles(processedNodes, groupId, userId); - - // Encode this level's msgBody. - const msgBody = await Promise.all(uploadReadyNodes.map( - node => buildForwardPushBody(bridge, node, groupId, userUid), - )); - - // Compose the action list: own MultiMsg + piggybacked inner actions. - const longMsgResult = protobuf_encode({ - action: [ - { actionCommand: 'MultiMsg', actionData: { msgBody } }, - ...myInnerActions.map(a => ({ - actionCommand: a.uuid, - actionData: { msgBody: a.msgBody }, - })), - ], - }); - - const selfUid = await resolveSelfUid(bridge); - const info: SendLongMsgReq['info'] = { - type: groupId ? 3 : 1, - uid: { uid: groupId ? String(groupId) : selfUid }, - payload: gzipSync(Buffer.from(longMsgResult)), - }; - if (groupId) info.groupUin = groupId; - - const request = protobuf_encode({ - info, - settings: { - field1: 4, - field2: 1, - field3: 7, - field4: 0, - }, - }); - - const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'upload forward message failed'); - } - - const resp = protobuf_decode(result.responseData); - const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : ''; - if (!resId) { - throw new Error('upload forward message response missing res_id'); - } - - forwardResCache.set(resId, uploadReadyNodes.map(node => ({ - ...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)), - groupId: node.groupId ?? groupId, - messageType: node.messageType ?? (groupId ? 'group' : 'private'), - }))); - - return { - resId, - msgBody, - // UUID generated here so the OUTER caller can use it as both - // (1) the `actionCommand` for its piggyback entry carrying our - // msgBody, and - // (2) the `forwardUuid` baked into its forward-preview element - // pointing at our resId. - // Receivers walking the outer's LongMsgResult find the inner - // layer by matching `uniseq` from (2) against `actionCommand` - // from (1) — no separate fetch needed. - uuid: randomUUID(), - innerActions: myInnerActions, - }; - } - - async fetch(resId: string): Promise { - const bridge = asBridge(this.ctx); - const cached = forwardResCache.get(resId); - if (cached) { - const nodes = cloneNodes(cached); - // Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich - // on read (a no-op once names are present) and persist so later hits skip. - if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes)); - return nodes; - } - - const selfUid = await resolveSelfUid(bridge); - const request = protobuf_encode({ - info: { - uid: { uid: selfUid }, - resId, - acquire: true, - }, - settings: { - field1: 2, - field2: 0, - field3: 0, - field4: 0, - }, - }); - - const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'download forward message failed'); - } - - const resp = protobuf_decode(result.responseData); - const payload = resp?.result?.payload; - if (!(payload instanceof Uint8Array) || payload.length === 0) { - throw new Error('download forward message payload is empty'); - } - - let inflate: Buffer; - try { - inflate = gunzipSync(Buffer.from(payload), { - maxOutputLength: FORWARD_LONG_MSG_MAX_OUTPUT_BYTES, - }); - } catch (cause) { - const reason = cause instanceof Error ? cause.message : String(cause); - log.warn( - 'forward long-msg decompression failed: res_id=%s compressed_bytes=%d max_output_bytes=%d error=%s', - resId, - payload.byteLength, - FORWARD_LONG_MSG_MAX_OUTPUT_BYTES, - reason, - ); - throw new Error( - `download forward message decompression failed ` + - `(res_id=${resId}, compressed_bytes=${payload.byteLength}, ` + - `max_output_bytes=${FORWARD_LONG_MSG_MAX_OUTPUT_BYTES}): ${reason}`, - { cause }, - ); - } - const longMsg = protobuf_decode(inflate); - const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : []; - const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg'); - const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody) ? mainAction!.actionData!.msgBody : []; - - // Piggyback index: any non-`MultiMsg` action carries an inner - // layer keyed by the uuid the sender baked into its forward - // preview's `uniseq`. Build a lookup so we can resolve inner - // forwards (via their uniseq → inner msgBody) without a second - // server roundtrip — matches the sender-side piggyback emitted in - // `uploadRecursive` above. - const piggybackByUuid = new Map(); - for (const action of actions) { - const cmd = action?.actionCommand; - if (!cmd || cmd === 'MultiMsg') continue; - const body = Array.isArray(action.actionData?.msgBody) ? action.actionData.msgBody : []; - piggybackByUuid.set(cmd, body); - } - - const nodes = this.decodeMsgBodiesToNodes(msgBodyList); - - // Walk the decoded outer nodes for inner-forward previews - // (`type: 'forward', forwardUuid: `). For each, pull the - // matching piggyback body, decode it into inner nodes, and seed - // the cache by the inner resId so a follow-up `fetch(innerResId)` - // hits the cache instead of the wire. - if (piggybackByUuid.size > 0) { - this.consumePiggybacks(nodes, piggybackByUuid); - } - - // Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty - // or stamped with the "QQ用户" placeholder (#174) — the long-msg member name - // isn't always populated, and the sync decode only consults the L1 cache. - await this.enrichSenders(nodes); - - if (nodes.length > 0) { - forwardResCache.set(resId, cloneNodes(nodes)); - } - return nodes; - } - - /** A node whose display name the server didn't give us (empty or the QQ - * placeholder) and that we can resolve (has a uin). */ - private needsName(n: ForwardNodePayload): boolean { - return !!n.userUin && (!n.nickname || n.nickname === FORWARD_NAME_PLACEHOLDER); - } - - /** Backfill sender nickname/card on forward nodes the long-msg payload left - * nameless. Resolves group senders via one member-list fetch per group (L3, - * inflight+TTL cached in ContactsApi), then any residue + private nodes via - * the user-profile lookup (L4). Best-effort: a failed lookup keeps the - * placeholder rather than failing the whole forward. Returns true if any - * node was changed (so callers can persist the enriched cache). */ - private async enrichSenders(nodes: ForwardNodePayload[]): Promise { - const pending = nodes.filter(n => this.needsName(n)); - if (pending.length === 0) return false; - let changed = false; - - // L3 — group member lists (one fetch resolves every sender from that group). - const byGroup = new Map(); - const residue: ForwardNodePayload[] = []; - for (const n of pending) { - if (n.messageType === 'group' && n.groupId) { - const arr = byGroup.get(n.groupId) ?? []; - arr.push(n); - byGroup.set(n.groupId, arr); - } else { - residue.push(n); - } - } - for (const [groupId, groupNodes] of byGroup) { - let byUin: Map; - try { - const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId); - byUin = new Map(members.map(m => [m.uin, { nickname: m.nickname, card: m.card }])); - } catch { - // Member list (one cheap, cached call) failed — keep the placeholder - // rather than fanning the whole group out to per-uin profile lookups. - // That error path is exactly what would amplify into a rate-limit ban. - continue; - } - for (const n of groupNodes) { - const m = byUin.get(n.userUin); - const name = m?.card || m?.nickname; - if (name) { - n.senderCard = m!.card || n.senderCard || ''; - n.nickname = name; - changed = true; - } else { - residue.push(n); // in-group sender that left the group → profile fallback + if (groupId) { + info.groupUin = groupId; } - } - } - // L4 — user profile for the residue (members who left the group, private - // nodes). fetchUserProfile is an un-cached single-point OIDB 0xFE1_2, and - // Tencent rate-limits these hard (see ContactsApi's member-list note), so: - // dedupe by uin, CAP the count (drop the rest to placeholder), and resolve - // in small concurrency-limited batches. Best-effort. - const uins = [...new Set(residue.filter(n => this.needsName(n)).map(n => n.userUin))] - .slice(0, FORWARD_PROFILE_MAX); - if (uins.length > 0) { - const byUin = new Map(); - const results = await mapWithConcurrency(uins, FORWARD_PROFILE_CONCURRENCY, - async (uin): Promise => { - try { return [uin, (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname] as const; } - catch { return [uin, ''] as const; } + const request = protobuf_encode({ + info, + settings: { + field1: 4, + field2: 1, + field3: 7, + field4: 0, + }, }); - for (const [uin, nick] of results) byUin.set(uin, nick); - for (const n of residue) { - if (!this.needsName(n)) continue; - const nick = byUin.get(n.userUin); - if (nick) { n.nickname = nick; changed = true; } - } - } - return changed; - } - /** Walk a list of PushMsgBody, run each through the regular msg-push - * pipeline, and shape the result into ForwardNodePayloads. Extracted - * so both the outer + piggyback decode paths share one implementation. */ - private decodeMsgBodiesToNodes(msgBodyList: PushMsgBody[]): ForwardNodePayload[] { - const out: ForwardNodePayload[] = []; - for (const msgBody of msgBodyList) { - const wrapped = protobuf_encode({ message: msgBody }); - const pkt: PacketInfo = { - pid: 0, - uin: this.ctx.identity.uin, - serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush', - seqId: 0, - retCode: 0, - fromClient: false, - body: wrapped, - }; - const events = parseMsgPush(pkt, this.ctx.identity); - const event = events.find(e => - e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message'); - if (!event) continue; + const result = await this.ctx.sendRawPacket( + 'trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', + request, + ); - if (event.kind === 'group_message') { - // [#201] The merged-forward sender name now comes through the group - // decoder (event.senderNick), which reads grp.memberCard (field 4) when - // there's no member cache — exactly the forward-node case. - out.push({ - userUin: event.senderUin, - nickname: event.senderCard || event.senderNick, - elements: event.elements, - time: event.time, - msgId: event.msgId, - msgSeq: event.msgSeq, - groupId: event.groupId, - senderCard: event.senderCard, - messageType: 'group', - }); - } else if (event.kind === 'friend_message') { - out.push({ - userUin: event.senderUin, - nickname: event.senderNick, - elements: event.elements, - time: event.time, - msgId: event.msgId, - msgSeq: event.msgSeq, - messageType: 'private', - }); - } else { - out.push({ - userUin: event.senderUin, - nickname: event.senderNick, - elements: event.elements, - time: event.time, - msgSeq: event.msgSeq, - groupId: event.groupId, - messageType: 'private', - }); - } - } - return out; - } - - /** Recursively resolve forward previews against the piggyback table. - * For every `{type: 'forward', resId, forwardUuid}` element we find, - * look up the uniseq in the piggyback map; if hit, decode the - * inner msgBody and cache it by inner resId, then descend into that - * inner layer to resolve deeper nestings carried in the SAME - * piggyback set (NapCat hoists the entire tree's piggybacks onto - * the outermost action list). */ - private consumePiggybacks( - nodes: ForwardNodePayload[], - piggybackByUuid: Map, - ): void { - const seen = new Set(); - const visit = (chain: ForwardNodePayload[]): void => { - for (const node of chain) { - for (const elem of node.elements) { - if (elem.type !== 'forward') continue; - const uuid = elem.forwardUuid; - const innerResId = elem.resId; - if (!uuid || !innerResId || seen.has(uuid)) continue; - const body = piggybackByUuid.get(uuid); - if (!body) continue; - seen.add(uuid); - const innerNodes = this.decodeMsgBodiesToNodes(body); - forwardResCache.set(innerResId, cloneNodes(innerNodes)); - visit(innerNodes); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'upload forward message failed'); } - } - }; - visit(nodes); - } + + const resp = protobuf_decode(result.responseData); + const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : ''; + + if (!resId) { + throw new Error('upload forward message response missing res_id'); + } + + forwardResCache.set( + resId, + uploadReadyNodes.map((node) => ({ + ...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)), + groupId: node.groupId ?? groupId, + messageType: node.messageType ?? (groupId ? 'group' : 'private'), + })), + ); + + return { + resId, + msgBody, + // UUID generated here so the OUTER caller can use it as both + // (1) the `actionCommand` for its piggyback entry carrying our + // msgBody, and + // (2) the `forwardUuid` baked into its forward-preview element + // pointing at our resId. + // Receivers walking the outer's LongMsgResult find the inner + // layer by matching `uniseq` from (2) against `actionCommand` + // from (1) — no separate fetch needed. + uuid: randomUUID(), + innerActions: myInnerActions, + }; + } + + async fetch(resId: string): Promise { + const bridge = asBridge(this.ctx); + const cached = forwardResCache.get(resId); + + if (cached) { + const nodes = cloneNodes(cached); + + // Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich + // on read (a no-op once names are present) and persist so later hits skip. + if (await this.enrichSenders(nodes)) { + forwardResCache.set(resId, cloneNodes(nodes)); + } + + return nodes; + } + + const selfUid = await resolveSelfUid(bridge); + const request = protobuf_encode({ + info: { + uid: { uid: selfUid }, + resId, + acquire: true, + }, + settings: { + field1: 2, + field2: 0, + field3: 0, + field4: 0, + }, + }); + + const result = await this.ctx.sendRawPacket( + 'trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', + request, + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'download forward message failed'); + } + + const resp = protobuf_decode(result.responseData); + const payload = resp?.result?.payload; + + if (!(payload instanceof Uint8Array) || payload.length === 0) { + throw new Error('download forward message payload is empty'); + } + + let inflate: Buffer; + + try { + inflate = gunzipSync(Buffer.from(payload), { + maxOutputLength: FORWARD_LONG_MSG_MAX_OUTPUT_BYTES, + }); + } catch (cause) { + const reason = cause instanceof Error ? cause.message : String(cause); + log.warn( + 'forward long-msg decompression failed: res_id=%s compressed_bytes=%d max_output_bytes=%d error=%s', + resId, + payload.byteLength, + FORWARD_LONG_MSG_MAX_OUTPUT_BYTES, + reason, + ); + throw new Error( + `download forward message decompression failed ` + + `(res_id=${resId}, compressed_bytes=${payload.byteLength}, ` + + `max_output_bytes=${FORWARD_LONG_MSG_MAX_OUTPUT_BYTES}): ${reason}`, + { cause }, + ); + } + + const longMsg = protobuf_decode(inflate); + const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : []; + const mainAction = actions.find((item) => item?.actionCommand === 'MultiMsg'); + const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody) + ? mainAction!.actionData!.msgBody + : []; + + // Piggyback index: any non-`MultiMsg` action carries an inner + // layer keyed by the uuid the sender baked into its forward + // preview's `uniseq`. Build a lookup so we can resolve inner + // forwards (via their uniseq → inner msgBody) without a second + // server roundtrip — matches the sender-side piggyback emitted in + // `uploadRecursive` above. + const piggybackByUuid = new Map(); + + for (const action of actions) { + const cmd = action?.actionCommand; + + if (!cmd || cmd === 'MultiMsg') { + continue; + } + + const body = Array.isArray(action.actionData?.msgBody) ? action.actionData.msgBody : []; + piggybackByUuid.set(cmd, body); + } + + const nodes = this.decodeMsgBodiesToNodes(msgBodyList); + + // Walk the decoded outer nodes for inner-forward previews + // (`type: 'forward', forwardUuid: `). For each, pull the + // matching piggyback body, decode it into inner nodes, and seed + // the cache by the inner resId so a follow-up `fetch(innerResId)` + // hits the cache instead of the wire. + if (piggybackByUuid.size > 0) { + this.consumePiggybacks(nodes, piggybackByUuid); + } + + // Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty + // or stamped with the "QQ用户" placeholder (#174) — the long-msg member name + // isn't always populated, and the sync decode only consults the L1 cache. + await this.enrichSenders(nodes); + + if (nodes.length > 0) { + forwardResCache.set(resId, cloneNodes(nodes)); + } + + return nodes; + } + + /** A node whose display name the server didn't give us (empty or the QQ + * placeholder) and that we can resolve (has a uin). */ + private needsName(n: ForwardNodePayload): boolean { + return !!n.userUin && (!n.nickname || n.nickname === FORWARD_NAME_PLACEHOLDER); + } + + /** Backfill sender nickname/card on forward nodes the long-msg payload left + * nameless. Resolves group senders via one member-list fetch per group (L3, + * inflight+TTL cached in ContactsApi), then any residue + private nodes via + * the user-profile lookup (L4). Best-effort: a failed lookup keeps the + * placeholder rather than failing the whole forward. Returns true if any + * node was changed (so callers can persist the enriched cache). */ + private async enrichSenders(nodes: ForwardNodePayload[]): Promise { + const pending = nodes.filter((n) => this.needsName(n)); + + if (pending.length === 0) { + return false; + } + + let changed = false; + + // L3 — group member lists (one fetch resolves every sender from that group). + const byGroup = new Map(); + const residue: ForwardNodePayload[] = []; + + for (const n of pending) { + if (n.messageType === 'group' && n.groupId) { + const arr = byGroup.get(n.groupId) ?? []; + arr.push(n); + byGroup.set(n.groupId, arr); + } else { + residue.push(n); + } + } + + for (const [groupId, groupNodes] of byGroup) { + let byUin: Map; + + try { + const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId); + byUin = new Map( + members.map((m) => [m.uin, { nickname: m.nickname, card: m.card }]), + ); + } catch { + // Member list (one cheap, cached call) failed — keep the placeholder + // rather than fanning the whole group out to per-uin profile lookups. + // That error path is exactly what would amplify into a rate-limit ban. + continue; + } + + for (const n of groupNodes) { + const m = byUin.get(n.userUin); + const name = m?.card || m?.nickname; + + if (name) { + n.senderCard = m!.card || n.senderCard || ''; + n.nickname = name; + changed = true; + } else { + residue.push(n); // in-group sender that left the group → profile fallback + } + } + } + + // L4 — user profile for the residue (members who left the group, private + // nodes). fetchUserProfile is an un-cached single-point OIDB 0xFE1_2, and + // Tencent rate-limits these hard (see ContactsApi's member-list note), so: + // dedupe by uin, CAP the count (drop the rest to placeholder), and resolve + // in small concurrency-limited batches. Best-effort. + const uins = [ + ...new Set(residue.filter((n) => this.needsName(n)).map((n) => n.userUin)), + ].slice(0, FORWARD_PROFILE_MAX); + + if (uins.length > 0) { + const byUin = new Map(); + const results = await mapWithConcurrency( + uins, + FORWARD_PROFILE_CONCURRENCY, + async (uin): Promise => { + try { + return [ + uin, + (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname, + ] as const; + } catch { + return [uin, ''] as const; + } + }, + ); + + for (const [uin, nick] of results) { + byUin.set(uin, nick); + } + + for (const n of residue) { + if (!this.needsName(n)) { + continue; + } + + const nick = byUin.get(n.userUin); + + if (nick) { + n.nickname = nick; + changed = true; + } + } + } + + return changed; + } + + /** Walk a list of PushMsgBody, run each through the regular msg-push + * pipeline, and shape the result into ForwardNodePayloads. Extracted + * so both the outer + piggyback decode paths share one implementation. */ + private decodeMsgBodiesToNodes(msgBodyList: PushMsgBody[]): ForwardNodePayload[] { + const out: ForwardNodePayload[] = []; + + for (const msgBody of msgBodyList) { + const wrapped = protobuf_encode({ message: msgBody }); + const pkt: PacketInfo = { + pid: 0, + uin: this.ctx.identity.uin, + serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush', + seqId: 0, + retCode: 0, + fromClient: false, + body: wrapped, + }; + const events = parseMsgPush(pkt, this.ctx.identity); + const event = events.find( + (e) => + e.kind === 'friend_message' || + e.kind === 'group_message' || + e.kind === 'temp_message', + ); + + if (!event) { + continue; + } + + if (event.kind === 'group_message') { + // [#201] The merged-forward sender name now comes through the group + // decoder (event.senderNick), which reads grp.memberCard (field 4) when + // there's no member cache — exactly the forward-node case. + out.push({ + userUin: event.senderUin, + nickname: event.senderCard || event.senderNick, + elements: event.elements, + time: event.time, + msgId: event.msgId, + msgSeq: event.msgSeq, + groupId: event.groupId, + senderCard: event.senderCard, + messageType: 'group', + }); + } else if (event.kind === 'friend_message') { + out.push({ + userUin: event.senderUin, + nickname: event.senderNick, + elements: event.elements, + time: event.time, + msgId: event.msgId, + msgSeq: event.msgSeq, + messageType: 'private', + }); + } else { + out.push({ + userUin: event.senderUin, + nickname: event.senderNick, + elements: event.elements, + time: event.time, + msgSeq: event.msgSeq, + groupId: event.groupId, + messageType: 'private', + }); + } + } + + return out; + } + + /** Recursively resolve forward previews against the piggyback table. + * For every `{type: 'forward', resId, forwardUuid}` element we find, + * look up the uniseq in the piggyback map; if hit, decode the + * inner msgBody and cache it by inner resId, then descend into that + * inner layer to resolve deeper nestings carried in the SAME + * piggyback set (NapCat hoists the entire tree's piggybacks onto + * the outermost action list). */ + private consumePiggybacks( + nodes: ForwardNodePayload[], + piggybackByUuid: Map, + ): void { + const seen = new Set(); + + const visit = (chain: ForwardNodePayload[]): void => { + for (const node of chain) { + for (const elem of node.elements) { + if (elem.type !== 'forward') { + continue; + } + + const uuid = elem.forwardUuid; + const innerResId = elem.resId; + + if (!uuid || !innerResId || seen.has(uuid)) { + continue; + } + + const body = piggybackByUuid.get(uuid); + + if (!body) { + continue; + } + + seen.add(uuid); + const innerNodes = this.decodeMsgBodiesToNodes(body); + forwardResCache.set(innerResId, cloneNodes(innerNodes)); + visit(innerNodes); + } + } + }; + + visit(nodes); + } } function cacheableForwardElement(element: MessageElement): MessageElement { - if (element.type !== 'image') return element; - if (element.imageUrl || element.fileId || element.md5Hex) return element; - const source = (element.url ?? '').trim(); - if (!source) return element; - return { ...element, imageUrl: source }; + if (element.type !== 'image') { + return element; + } + + if (element.imageUrl || element.fileId || element.md5Hex) { + return element; + } + + const source = (element.url ?? '').trim(); + + if (!source) { + return element; + } + + return { ...element, imageUrl: source }; } function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] { - return nodes.map(node => cloneNodeWithElements(node, [...node.elements])); + return nodes.map((node) => cloneNodeWithElements(node, [...node.elements])); } diff --git a/packages/core/src/bridge/apis/friend.ts b/packages/core/src/bridge/apis/friend.ts index 43278bff..27a2e96d 100644 --- a/packages/core/src/bridge/apis/friend.ts +++ b/packages/core/src/bridge/apis/friend.ts @@ -3,7 +3,10 @@ import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-cont import { ApproveDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/approve-doubt-buddy-req'; import { ClearFriendRemark } from '@snowluma/protocol/oidb-services/friend/clear-friend-remark'; import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend'; -import { GetDoubtBuddyReq, type DoubtBuddyRequest } from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req'; +import { + GetDoubtBuddyReq, + type DoubtBuddyRequest, +} from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req'; import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request'; import { RejectDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/reject-doubt-buddy-req'; import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark'; @@ -14,96 +17,107 @@ export type { DoubtBuddyRequest }; const log = createLogger('Bridge.Friend'); export class FriendApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - /** - * Accept or reject an inbound friend request. `uidOrFlag` is either a - * pre-resolved UID string or a numeric uin (then resolved on the fly). - */ - handleRequest(uidOrFlag: string, approve: boolean): Promise { - return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve }); - } - - async delete(userId: number, block = false): Promise { - if (findDatalineDeviceByUin(userId)) { - throw new Error('this contact cannot be deleted'); + /** + * Accept or reject an inbound friend request. `uidOrFlag` is either a + * pre-resolved UID string or a numeric uin (then resolved on the fly). + */ + handleRequest(uidOrFlag: string, approve: boolean): Promise { + return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve }); } - await DeleteFriend.invoke(this.ctx, { userId, block }); - // The server-side delete has already completed. A refresh failure must be - // visible, but throwing here would misreport the delete itself as failed - // and encourage callers to repeat a destructive request. - try { - await this.ctx.apis.contacts.fetchFriendList(); - } catch (err: unknown) { - log.warn( - 'friend-list refresh failed after deleting user=%d: %s', - userId, - err instanceof Error ? err.message : String(err), - ); - } - } - - async setRemark(userId: number, remark: string): Promise { - if (findDatalineDeviceByUin(userId)) { - throw new Error('this contact does not support remarks'); - } - if (remark === '') { - await ClearFriendRemark.invoke(this.ctx, { userId }); - return; - } - await SetFriendRemark.invoke(this.ctx, { userId, remark }); - } - - /** List doubtful friend-add requests (可能认识的人). */ - async getDoubtRequests(count: number): Promise { - const list = await GetDoubtBuddyReq.invoke(this.ctx, { count }); - return Promise.all(list.map(async (item) => { - let uid = item.uid; - let userId = item.user_id; - if (userId <= 0 && uid) { - userId = this.ctx.identity.findUinByUid(uid) ?? 0; - } - // Applicants need not be friends or share a group. Use Identity's - // profile lookup when the list only supplies an account number. - if (!uid && userId > 0) { - try { - uid = await this.ctx.resolveUserUid(userId); - } catch (err: unknown) { - log.warn( - 'doubt-request uid resolve failed: user=%d err=%s', - userId, - err instanceof Error ? err.message : String(err), - ); + async delete(userId: number, block = false): Promise { + if (findDatalineDeviceByUin(userId)) { + throw new Error('this contact cannot be deleted'); } - } - return { ...item, uid: uid || '', user_id: userId }; - })); - } - /** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */ - async approveDoubtRequest(uidOrFlag: string): Promise { - log.trace('doubt-request approval: resolving applicant'); - const uid = await this.resolveDoubtFlag(uidOrFlag); - log.trace('doubt-request approval: submitting request'); - await ApproveDoubtBuddyReq.invoke(this.ctx, { uid }); - log.trace('doubt-request approval: completed'); - } + await DeleteFriend.invoke(this.ctx, { userId, block }); - /** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */ - async rejectDoubtRequest(uidOrFlag: string): Promise { - return RejectDoubtBuddyReq.invoke(this.ctx, { - uid: await this.resolveDoubtFlag(uidOrFlag), - }); - } + // The server-side delete has already completed. A refresh failure must be + // visible, but throwing here would misreport the delete itself as failed + // and encourage callers to repeat a destructive request. + try { + await this.ctx.apis.contacts.fetchFriendList(); + } catch (err: unknown) { + log.warn( + 'friend-list refresh failed after deleting user=%d: %s', + userId, + err instanceof Error ? err.message : String(err), + ); + } + } - /** - * Digit-only flags are account numbers and must be translated before the - * approval/reject packet is built. A raw number in that packet is rejected - * by the server. Same rule as inbound friend-request handling. - */ - private resolveDoubtFlag(uidOrFlag: string): Promise { - if (!/^\d+$/.test(uidOrFlag)) return Promise.resolve(uidOrFlag); - return this.ctx.resolveUserUid(parseInt(uidOrFlag, 10)); - } + async setRemark(userId: number, remark: string): Promise { + if (findDatalineDeviceByUin(userId)) { + throw new Error('this contact does not support remarks'); + } + + if (remark === '') { + await ClearFriendRemark.invoke(this.ctx, { userId }); + return; + } + + await SetFriendRemark.invoke(this.ctx, { userId, remark }); + } + + /** List doubtful friend-add requests (可能认识的人). */ + async getDoubtRequests(count: number): Promise { + const list = await GetDoubtBuddyReq.invoke(this.ctx, { count }); + return Promise.all( + list.map(async (item) => { + let uid = item.uid; + let userId = item.user_id; + + if (userId <= 0 && uid) { + userId = this.ctx.identity.findUinByUid(uid) ?? 0; + } + + // Applicants need not be friends or share a group. Use Identity's + // profile lookup when the list only supplies an account number. + if (!uid && userId > 0) { + try { + uid = await this.ctx.resolveUserUid(userId); + } catch (err: unknown) { + log.warn( + 'doubt-request uid resolve failed: user=%d err=%s', + userId, + err instanceof Error ? err.message : String(err), + ); + } + } + + return { ...item, uid: uid || '', user_id: userId }; + }), + ); + } + + /** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */ + async approveDoubtRequest(uidOrFlag: string): Promise { + log.trace('doubt-request approval: resolving applicant'); + const uid = await this.resolveDoubtFlag(uidOrFlag); + log.trace('doubt-request approval: submitting request'); + await ApproveDoubtBuddyReq.invoke(this.ctx, { uid }); + log.trace('doubt-request approval: completed'); + } + + /** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */ + async rejectDoubtRequest(uidOrFlag: string): Promise { + return RejectDoubtBuddyReq.invoke(this.ctx, { + uid: await this.resolveDoubtFlag(uidOrFlag), + }); + } + + /** + * Digit-only flags are account numbers and must be translated before the + * approval/reject packet is built. A raw number in that packet is rejected + * by the server. Same rule as inbound friend-request handling. + */ + private resolveDoubtFlag(uidOrFlag: string): Promise { + if (!/^\d+$/.test(uidOrFlag)) { + return Promise.resolve(uidOrFlag); + } + + return this.ctx.resolveUserUid(parseInt(uidOrFlag, 10)); + } } diff --git a/packages/core/src/bridge/apis/group-admin.ts b/packages/core/src/bridge/apis/group-admin.ts index aa423b1e..a45f7dc8 100644 --- a/packages/core/src/bridge/apis/group-admin.ts +++ b/packages/core/src/bridge/apis/group-admin.ts @@ -13,22 +13,22 @@ import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card'; import { FetchGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/get-group-ext-info'; import { - decodeMemberInvitePolicy, - MEMBER_INVITE_PRIVILEGE_MASK, - mergeMemberInvitePrivilegeFlag, - SetMemberInvitePolicy, - type GroupMemberInvitePolicy, + decodeMemberInvitePolicy, + MEMBER_INVITE_PRIVILEGE_MASK, + mergeMemberInvitePrivilegeFlag, + SetMemberInvitePolicy, + type GroupMemberInvitePolicy, } from '@snowluma/protocol/oidb-services/group-admin/set-member-invite-policy'; import { - decodeGroupHistoryVisibility, - SetNewMemberHistoryVisibility, + decodeGroupHistoryVisibility, + SetNewMemberHistoryVisibility, } from '@snowluma/protocol/oidb-services/group-admin/set-new-member-history-visibility'; import { - decodeGroupMemberPermissions, - GROUP_MEMBER_PERMISSION_MASKS, - mergeGroupMemberPermission, - SetMemberPermission, - type GroupMemberPermission, + decodeGroupMemberPermissions, + GROUP_MEMBER_PERMISSION_MASKS, + mergeGroupMemberPermission, + SetMemberPermission, + type GroupMemberPermission, } from '@snowluma/protocol/oidb-services/group-admin/set-member-permission'; import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search'; import { GetGroupCategoryTags } from '@snowluma/protocol/oidb-services/group-admin/get-group-category-tags'; @@ -41,282 +41,334 @@ import type { BridgeContext } from '../bridge-context'; /** QQ only accepts this write from the group owner (#411). */ export const MEMBER_PERMISSIONS_OWNER_ONLY = - 'only the group owner can change group member permissions'; + 'only the group owner can change group member permissions'; export type GroupAdminSettings = { - add_type: number; - group_question: string; - group_answer: string; - robot_member_switch: number; - robot_member_examine: number; - member_invite_policy: GroupMemberInvitePolicy; - allow_member_upload_album: boolean; - allow_member_temporary_session: boolean; - allow_member_create_group: boolean; - new_member_history_visible: boolean; - no_finger_open: number; - no_code_finger_open: number; + add_type: number; + group_question: string; + group_answer: string; + robot_member_switch: number; + robot_member_examine: number; + member_invite_policy: GroupMemberInvitePolicy; + allow_member_upload_album: boolean; + allow_member_temporary_session: boolean; + allow_member_create_group: boolean; + new_member_history_visible: boolean; + no_finger_open: number; + no_code_finger_open: number; }; export interface GroupMemberPermissions { - allowMemberUploadAlbum?: boolean; - allowMemberTemporarySession?: boolean; - allowMemberCreateGroup?: boolean; + allowMemberUploadAlbum?: boolean; + allowMemberTemporarySession?: boolean; + allowMemberCreateGroup?: boolean; } export class GroupAdminApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - /** Set the group's robot-add option (switch / examine) via group ext-info. */ - setRobotAddOption(groupId: number, robotMemberSwitch?: number, robotMemberExamine?: number): Promise { - return ModifyGroupExtInfo.invoke(this.ctx, { groupId, robotMemberSwitch, robotMemberExamine }); - } - - async getAdminSettings(groupId: number): Promise { - const [detail, robot] = await Promise.all([ - FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }), - FetchGroupExtInfo.invoke(this.ctx, { groupId }), - ]); - const results = detail.groupInfo?.results; - if (!results) { - throw new Error(`unable to read group admin settings for group ${groupId}`); - } - const privilegeFlag = results.privilegeFlag ?? 0; - const permissions = decodeGroupMemberPermissions(privilegeFlag); - return { - add_type: results.addType ?? 0, - group_question: results.question ?? '', - group_answer: results.answer ?? '', - robot_member_switch: robot.robotMemberSwitch, - robot_member_examine: robot.robotMemberExamine, - member_invite_policy: decodeMemberInvitePolicy(privilegeFlag), - allow_member_upload_album: permissions.allowMemberUploadAlbum, - allow_member_temporary_session: permissions.allowMemberTemporarySession, - allow_member_create_group: permissions.allowMemberCreateGroup, - new_member_history_visible: decodeGroupHistoryVisibility(results.groupFlagExt4 ?? 0), - no_finger_open: results.noFingerOpen ?? 0, - no_code_finger_open: results.noCodeFingerOpen ?? 0, - }; - } - - muteMember(groupId: number, userId: number, duration: number): Promise { - return MuteMember.invoke(this.ctx, { groupId, userId, duration }); - } - - muteAll(groupId: number, enable: boolean): Promise { - return MuteAll.invoke(this.ctx, { groupId, enable }); - } - - setAddOption( - groupId: number, - addType: number, - groupQuestion?: string, - groupAnswer?: string, - ): Promise { - return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer }); - } - - setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise { - return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen }); - } - - listCategoryTags(groupClass: number): Promise<{ tags: { id: number; name: string; type: number }[] }> { - return GetGroupCategoryTags.invoke(this.ctx, { groupClass }); - } - - addCategoryTag(groupClass: number, name: string): Promise { - return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name }); - } - - removeCategoryTag(groupClass: number, name: string): Promise { - return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name }); - } - - async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise { - const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag( - groupId, - 'group member invite policy', - 'before update', - ); - const expectedPrivilegeFlag = mergeMemberInvitePrivilegeFlag(currentPrivilegeFlag, policy); - - await SetMemberInvitePolicy.invoke(this.ctx, { - groupId, - currentPrivilegeFlag, - policy, - }); - - const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag( - groupId, - 'group member invite policy', - 'after update', - ); - const mask = BigInt(MEMBER_INVITE_PRIVILEGE_MASK); - if ((BigInt(actualPrivilegeFlag) & mask) !== (BigInt(expectedPrivilegeFlag) & mask)) { - throw new Error(`group member invite policy was not applied for group ${groupId}`); - } - } - - private async fetchGroupPrivilegeFlag(groupId: number, setting: string, phase: string): Promise { - return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag; - } - - private async fetchGroupPrivilegeState( - groupId: number, - setting: string, - phase: string, - ): Promise<{ privilegeFlag: number; ownerUid?: string }> { - const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }); - const results = detail.groupInfo?.results; - if (!results) { - throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`); - } - return { - privilegeFlag: results.privilegeFlag ?? 0, - ownerUid: results.ownerUid, - }; - } - - async setMemberPermissions(groupId: number, permissions: GroupMemberPermissions): Promise { - const updates: ReadonlyArray = [ - ['upload_album', permissions.allowMemberUploadAlbum], - ['temporary_session', permissions.allowMemberTemporarySession], - ['create_group', permissions.allowMemberCreateGroup], - ]; - if (!updates.some(([, allow]) => allow !== undefined)) { - throw new Error('at least one member permission must be specified'); - } - - const before = await this.fetchGroupPrivilegeState( - groupId, - 'group member permissions', - 'before update', - ); - const selfUid = this.ctx.identity.selfUid; - if (selfUid && before.ownerUid && selfUid !== before.ownerUid) { - throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY); - } - - let expectedPrivilegeFlag = before.privilegeFlag; - let combinedMask = 0n; - - for (const [permission, allow] of updates) { - if (allow === undefined) continue; - try { - await SetMemberPermission.invoke(this.ctx, { - groupId, - currentPrivilegeFlag: expectedPrivilegeFlag, - permission, - allow, + /** Set the group's robot-add option (switch / examine) via group ext-info. */ + setRobotAddOption( + groupId: number, + robotMemberSwitch?: number, + robotMemberExamine?: number, + ): Promise { + return ModifyGroupExtInfo.invoke(this.ctx, { + groupId, + robotMemberSwitch, + robotMemberExamine, }); - } catch (error) { - if (error instanceof OidbError && error.code === 1287) { - throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY); + } + + async getAdminSettings(groupId: number): Promise { + const [detail, robot] = await Promise.all([ + FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }), + FetchGroupExtInfo.invoke(this.ctx, { groupId }), + ]); + const results = detail.groupInfo?.results; + + if (!results) { + throw new Error(`unable to read group admin settings for group ${groupId}`); } - throw error; - } - expectedPrivilegeFlag = mergeGroupMemberPermission(expectedPrivilegeFlag, permission, allow); - combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]); + + const privilegeFlag = results.privilegeFlag ?? 0; + const permissions = decodeGroupMemberPermissions(privilegeFlag); + return { + add_type: results.addType ?? 0, + group_question: results.question ?? '', + group_answer: results.answer ?? '', + robot_member_switch: robot.robotMemberSwitch, + robot_member_examine: robot.robotMemberExamine, + member_invite_policy: decodeMemberInvitePolicy(privilegeFlag), + allow_member_upload_album: permissions.allowMemberUploadAlbum, + allow_member_temporary_session: permissions.allowMemberTemporarySession, + allow_member_create_group: permissions.allowMemberCreateGroup, + new_member_history_visible: decodeGroupHistoryVisibility(results.groupFlagExt4 ?? 0), + no_finger_open: results.noFingerOpen ?? 0, + no_code_finger_open: results.noCodeFingerOpen ?? 0, + }; } - const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag( - groupId, - 'group member permissions', - 'after update', - ); - if ((BigInt(actualPrivilegeFlag) & combinedMask) !== (BigInt(expectedPrivilegeFlag) & combinedMask)) { - throw new Error(`group member permissions were not applied for group ${groupId}`); + muteMember(groupId: number, userId: number, duration: number): Promise { + return MuteMember.invoke(this.ctx, { groupId, userId, duration }); } - } - async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise { - await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible }); - - const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update'); - if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) { - throw new Error(`new-member history visibility was not applied for group ${groupId}`); + muteAll(groupId: number, enable: boolean): Promise { + return MuteAll.invoke(this.ctx, { groupId, enable }); } - } - private async fetchGroupFlagExt4(groupId: number, phase: string): Promise { - const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }); - const results = detail.groupInfo?.results; - if (!results) { - throw new Error(`unable to read new-member history visibility ${phase} for group ${groupId}`); + setAddOption( + groupId: number, + addType: number, + groupQuestion?: string, + groupAnswer?: string, + ): Promise { + return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer }); } - return results.groupFlagExt4 ?? 0; - } - setAddRequest( - groupId: number, sequence: number, eventType: number, - approve: boolean, reason = '', filtered = false, - operateTransInfo?: Uint8Array, - ): Promise { - return SetAddRequest.invoke(this.ctx, { - groupId, sequence, eventType, approve, reason, filtered, operateTransInfo, - }); - } + setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise { + return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen }); + } - kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise { - return KickMember.invoke(this.ctx, { groupId, userId, reject, reason }); - } + listCategoryTags( + groupClass: number, + ): Promise<{ tags: { id: number; name: string; type: number }[] }> { + return GetGroupCategoryTags.invoke(this.ctx, { groupClass }); + } - kickMembers(groupId: number, userIds: number[], reject: boolean): Promise { - return KickMembers.invoke(this.ctx, { groupId, userIds, reject }); - } + addCategoryTag(groupClass: number, name: string): Promise { + return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name }); + } - async leave(groupId: number): Promise { - await LeaveGroup.invoke(this.ctx, { groupId }); - // The server doesn't push a member-decrease back to the member who left of - // its own accord, so synthesize the self group_member_leave here — otherwise - // downstream never sees notice.group_decrease and keeps a "zombie" group in - // its cache (#133). Also drop the group from our own roster. - const selfUin = Number(this.ctx.identity.uin) || 0; - const selfUid = this.ctx.identity.selfUid ?? ''; - await this.ctx.events.emit({ - kind: 'group_member_leave', - time: Math.floor(Date.now() / 1000), - selfUin, - groupId, - userUin: selfUin, - operatorUin: selfUin, - userUid: selfUid, - operatorUid: selfUid, - leaveType: 'leave', - }); - this.ctx.identity.forgetGroup(groupId); - } + removeCategoryTag(groupClass: number, name: string): Promise { + return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name }); + } - setAdmin(groupId: number, userId: number, enable: boolean): Promise { - return SetAdmin.invoke(this.ctx, { groupId, userId, enable }); - } + async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise { + const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag( + groupId, + 'group member invite policy', + 'before update', + ); + const expectedPrivilegeFlag = mergeMemberInvitePrivilegeFlag(currentPrivilegeFlag, policy); - setCard(groupId: number, userId: number, card: string): Promise { - return SetMemberCard.invoke(this.ctx, { groupId, userId, card }); - } + await SetMemberInvitePolicy.invoke(this.ctx, { + groupId, + currentPrivilegeFlag, + policy, + }); - setName(groupId: number, name: string): Promise { - return SetGroupName.invoke(this.ctx, { groupId, name }); - } + const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag( + groupId, + 'group member invite policy', + 'after update', + ); + const mask = BigInt(MEMBER_INVITE_PRIVILEGE_MASK); - setSpecialTitle(groupId: number, userId: number, title: string): Promise { - return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title }); - } + if ((BigInt(actualPrivilegeFlag) & mask) !== (BigInt(expectedPrivilegeFlag) & mask)) { + throw new Error(`group member invite policy was not applied for group ${groupId}`); + } + } - /** - * The bot's local-only label for a group. Lives here rather than - * `FriendApi` because the semantic is "operate on a group" rather - * than "operate on a contact list". - */ - setRemark(groupId: number, remark: string): Promise { - return SetGroupRemark.invoke(this.ctx, { groupId, remark }); - } + private async fetchGroupPrivilegeFlag( + groupId: number, + setting: string, + phase: string, + ): Promise { + return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag; + } - getAtAllRemain(groupId: number): Promise<{ - can_at_all: boolean; - remain_at_all_count_for_group: number; - remain_at_all_count_for_uin: number; - }> { - return GetAtAllRemain.invoke(this.ctx, { groupId }); - } + private async fetchGroupPrivilegeState( + groupId: number, + setting: string, + phase: string, + ): Promise<{ privilegeFlag: number; ownerUid?: string }> { + const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }); + const results = detail.groupInfo?.results; + + if (!results) { + throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`); + } + + return { + privilegeFlag: results.privilegeFlag ?? 0, + ownerUid: results.ownerUid, + }; + } + + async setMemberPermissions( + groupId: number, + permissions: GroupMemberPermissions, + ): Promise { + const updates: ReadonlyArray = [ + ['upload_album', permissions.allowMemberUploadAlbum], + ['temporary_session', permissions.allowMemberTemporarySession], + ['create_group', permissions.allowMemberCreateGroup], + ]; + + if (!updates.some(([, allow]) => allow !== undefined)) { + throw new Error('at least one member permission must be specified'); + } + + const before = await this.fetchGroupPrivilegeState( + groupId, + 'group member permissions', + 'before update', + ); + const selfUid = this.ctx.identity.selfUid; + + if (selfUid && before.ownerUid && selfUid !== before.ownerUid) { + throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY); + } + + let expectedPrivilegeFlag = before.privilegeFlag; + let combinedMask = 0n; + + for (const [permission, allow] of updates) { + if (allow === undefined) { + continue; + } + + try { + await SetMemberPermission.invoke(this.ctx, { + groupId, + currentPrivilegeFlag: expectedPrivilegeFlag, + permission, + allow, + }); + } catch (error) { + if (error instanceof OidbError && error.code === 1287) { + throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY); + } + + throw error; + } + + expectedPrivilegeFlag = mergeGroupMemberPermission( + expectedPrivilegeFlag, + permission, + allow, + ); + combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]); + } + + const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag( + groupId, + 'group member permissions', + 'after update', + ); + + if ( + (BigInt(actualPrivilegeFlag) & combinedMask) !== + (BigInt(expectedPrivilegeFlag) & combinedMask) + ) { + throw new Error(`group member permissions were not applied for group ${groupId}`); + } + } + + async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise { + await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible }); + + const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update'); + + if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) { + throw new Error(`new-member history visibility was not applied for group ${groupId}`); + } + } + + private async fetchGroupFlagExt4(groupId: number, phase: string): Promise { + const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }); + const results = detail.groupInfo?.results; + + if (!results) { + throw new Error( + `unable to read new-member history visibility ${phase} for group ${groupId}`, + ); + } + + return results.groupFlagExt4 ?? 0; + } + + setAddRequest( + groupId: number, + sequence: number, + eventType: number, + approve: boolean, + reason = '', + filtered = false, + operateTransInfo?: Uint8Array, + ): Promise { + return SetAddRequest.invoke(this.ctx, { + groupId, + sequence, + eventType, + approve, + reason, + filtered, + operateTransInfo, + }); + } + + kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise { + return KickMember.invoke(this.ctx, { groupId, userId, reject, reason }); + } + + kickMembers(groupId: number, userIds: number[], reject: boolean): Promise { + return KickMembers.invoke(this.ctx, { groupId, userIds, reject }); + } + + async leave(groupId: number): Promise { + await LeaveGroup.invoke(this.ctx, { groupId }); + // The server doesn't push a member-decrease back to the member who left of + // its own accord, so synthesize the self group_member_leave here — otherwise + // downstream never sees notice.group_decrease and keeps a "zombie" group in + // its cache (#133). Also drop the group from our own roster. + const selfUin = Number(this.ctx.identity.uin) || 0; + const selfUid = this.ctx.identity.selfUid ?? ''; + await this.ctx.events.emit({ + kind: 'group_member_leave', + time: Math.floor(Date.now() / 1000), + selfUin, + groupId, + userUin: selfUin, + operatorUin: selfUin, + userUid: selfUid, + operatorUid: selfUid, + leaveType: 'leave', + }); + this.ctx.identity.forgetGroup(groupId); + } + + setAdmin(groupId: number, userId: number, enable: boolean): Promise { + return SetAdmin.invoke(this.ctx, { groupId, userId, enable }); + } + + setCard(groupId: number, userId: number, card: string): Promise { + return SetMemberCard.invoke(this.ctx, { groupId, userId, card }); + } + + setName(groupId: number, name: string): Promise { + return SetGroupName.invoke(this.ctx, { groupId, name }); + } + + setSpecialTitle(groupId: number, userId: number, title: string): Promise { + return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title }); + } + + /** + * The bot's local-only label for a group. Lives here rather than + * `FriendApi` because the semantic is "operate on a group" rather + * than "operate on a contact list". + */ + setRemark(groupId: number, remark: string): Promise { + return SetGroupRemark.invoke(this.ctx, { groupId, remark }); + } + + getAtAllRemain(groupId: number): Promise<{ + can_at_all: boolean; + remain_at_all_count_for_group: number; + remain_at_all_count_for_uin: number; + }> { + return GetAtAllRemain.invoke(this.ctx, { groupId }); + } } diff --git a/packages/core/src/bridge/apis/group-album.ts b/packages/core/src/bridge/apis/group-album.ts index 47fcde46..50664123 100644 --- a/packages/core/src/bridge/apis/group-album.ts +++ b/packages/core/src/bridge/apis/group-album.ts @@ -2,28 +2,31 @@ import type { JsonObject, JsonValue } from '@snowluma/common/json'; import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout'; import { createLogger } from '@snowluma/common/logger'; import type { - AlbumCreator, - CommentReqBodyHeader, - CommentReqPhotoInfo, - CommentRespData, - DeleteMediasRequest, - DeleteMediasResponse, - DoQunCommentRequest, - DoQunCommentResponse, - DoQunLikeRequest, - DoQunLikeResponse, - GetAlbumListRequest, - GetAlbumListResponse, - GetQunFeedDetailRequest, - GetQunFeedDetailResponse, - GroupAlbumInfo as GroupAlbumInfoWire, - QunFeedCellCommon, - GetMediaListRequest, - GetMediaListResponse, - MediaInfo, - UrlInfo, + AlbumCreator, + CommentReqBodyHeader, + CommentReqPhotoInfo, + CommentRespData, + DeleteMediasRequest, + DeleteMediasResponse, + DoQunCommentRequest, + DoQunCommentResponse, + DoQunLikeRequest, + DoQunLikeResponse, + GetAlbumListRequest, + GetAlbumListResponse, + GetQunFeedDetailRequest, + GetQunFeedDetailResponse, + GroupAlbumInfo as GroupAlbumInfoWire, + QunFeedCellCommon, + GetMediaListRequest, + GetMediaListResponse, + MediaInfo, + UrlInfo, } from '@snowluma/proto-defs/oidb-actions/group-album'; -import { uploadImageToGroupAlbum, uploadVideoToGroupAlbum } from '@snowluma/protocol/web/group-album'; +import { + uploadImageToGroupAlbum, + uploadVideoToGroupAlbum, +} from '@snowluma/protocol/web/group-album'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { BridgeContext } from '../bridge-context'; @@ -36,819 +39,955 @@ const GET_QUN_FEED_DETAIL_CMD = 'QunAlbum.trpc.qzone.webapp_qun_feeds.FeedsReade const GET_QUN_FEED_DETAIL_COMMENT_COUNT = 20; function uint64ToString(value: bigint | undefined): string { - return (value ?? 0n).toString(); + return (value ?? 0n).toString(); } function uint64ToSafeNumber(value: bigint | undefined, fieldName: string): number { - const normalized = value ?? 0n; - if (normalized > BigInt(Number.MAX_SAFE_INTEGER)) { - throw new Error(`group album ${fieldName} exceeds Number.MAX_SAFE_INTEGER: ${normalized}`); - } - return Number(normalized); + const normalized = value ?? 0n; + + if (normalized > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error(`group album ${fieldName} exceeds Number.MAX_SAFE_INTEGER: ${normalized}`); + } + + return Number(normalized); } function normalizeAlbumCreator(creator: AlbumCreator | undefined): QunAlbumCreator | undefined { - if (!creator) return undefined; - return { - uid: creator.uid ?? '', - nick: creator.nick ?? '', - is_sweet: creator.isSweet ?? false, - is_special: creator.isSpecial ?? false, - is_super_like: creator.isSuperLike ?? false, - custom_id: creator.customId ?? '', - poly_id: creator.polyId ?? '', - portrait: creator.portrait ?? '', - can_follow: creator.canFollow ?? 0, - isfollowed: creator.isFollowed ?? 0, - uin: creator.uin ?? '', - ditto_uin: creator.dittoUin ?? '', - }; + if (!creator) { + return undefined; + } + + return { + uid: creator.uid ?? '', + nick: creator.nick ?? '', + is_sweet: creator.isSweet ?? false, + is_special: creator.isSpecial ?? false, + is_super_like: creator.isSuperLike ?? false, + custom_id: creator.customId ?? '', + poly_id: creator.polyId ?? '', + portrait: creator.portrait ?? '', + can_follow: creator.canFollow ?? 0, + isfollowed: creator.isFollowed ?? 0, + uin: creator.uin ?? '', + ditto_uin: creator.dittoUin ?? '', + }; } function normalizeCoverUrl(url: UrlInfo | null | undefined): QunAlbumCoverUrl | null { - if (!url) return null; - return { - url: url.url ?? '', - width: url.width ?? 0, - height: url.height ?? 0, - }; + if (!url) { + return null; + } + + return { + url: url.url ?? '', + width: url.width ?? 0, + height: url.height ?? 0, + }; } function normalizeAlbumCover(cover: MediaInfo | undefined): QunAlbumCover | null { - if (!cover) return null; - const image = cover.image; - return { - type: cover.type ?? 0, - image: image ? { - name: image.name ?? '', - sloc: image.sloc ?? '', - lloc: image.lloc ?? '', - photoUrls: (image.photoUrls ?? []).map((photoUrl) => ({ - spec: photoUrl.spec ?? 0, - url: normalizeCoverUrl(photoUrl.url), - })), - defaultUrl: normalizeCoverUrl(image.defaultUrl), - isGif: image.isGif ?? false, - hasRaw: image.hasRaw ?? false, - } : null, - }; + if (!cover) { + return null; + } + + const image = cover.image; + return { + type: cover.type ?? 0, + image: image + ? { + name: image.name ?? '', + sloc: image.sloc ?? '', + lloc: image.lloc ?? '', + photoUrls: (image.photoUrls ?? []).map((photoUrl) => ({ + spec: photoUrl.spec ?? 0, + url: normalizeCoverUrl(photoUrl.url), + })), + defaultUrl: normalizeCoverUrl(image.defaultUrl), + isGif: image.isGif ?? false, + hasRaw: image.hasRaw ?? false, + } + : null, + }; } function normalizeQunAlbum(album: GroupAlbumInfoWire): QunAlbumInfo { - const normalized: QunAlbumInfo = { - album_id: album.albumId ?? '', - owner: album.owner ?? '', - name: album.name ?? '', - desc: album.description ?? '', - create_time: uint64ToString(album.createTime), - modify_time: uint64ToString(album.modifyTime), - last_upload_time: uint64ToString(album.lastUploadTime), - upload_number: uint64ToString(album.uploadNumber), - cover: normalizeAlbumCover(album.cover), - top_flag: uint64ToString(album.topFlag), - busi_type: album.busiType ?? 0, - status: album.status ?? 0, - allow_share: album.allowShare ?? false, - is_subscribe: album.isSubscribe ?? false, - bitmap: album.bitmap ?? '', - is_share_album: album.isShareAlbum ?? false, - qz_album_type: album.qzAlbumType ?? 0, - cover_type: album.coverType ?? 0, - default_desc: album.defaultDesc ?? '', - sort_type: album.sortType ?? 0, - }; - const creator = normalizeAlbumCreator(album.creator); - if (creator) normalized.creator = creator; - return normalized; + const normalized: QunAlbumInfo = { + album_id: album.albumId ?? '', + owner: album.owner ?? '', + name: album.name ?? '', + desc: album.description ?? '', + create_time: uint64ToString(album.createTime), + modify_time: uint64ToString(album.modifyTime), + last_upload_time: uint64ToString(album.lastUploadTime), + upload_number: uint64ToString(album.uploadNumber), + cover: normalizeAlbumCover(album.cover), + top_flag: uint64ToString(album.topFlag), + busi_type: album.busiType ?? 0, + status: album.status ?? 0, + allow_share: album.allowShare ?? false, + is_subscribe: album.isSubscribe ?? false, + bitmap: album.bitmap ?? '', + is_share_album: album.isShareAlbum ?? false, + qz_album_type: album.qzAlbumType ?? 0, + cover_type: album.coverType ?? 0, + default_desc: album.defaultDesc ?? '', + sort_type: album.sortType ?? 0, + }; + const creator = normalizeAlbumCreator(album.creator); + + if (creator) { + normalized.creator = creator; + } + + return normalized; } function toLegacyAlbum(album: GroupAlbumInfoWire): GroupAlbumInfo { - const creator = normalizeAlbumCreator(album.creator); - return { - id: album.albumId ?? '', - name: album.name ?? '', - picNum: uint64ToSafeNumber(album.uploadNumber, 'upload_number'), - createTime: uint64ToSafeNumber(album.createTime, 'create_time'), - desc: album.description ?? '', - owner: album.owner ?? '', - createuin: creator?.uin || album.owner || creator?.uid || '', - // QQ NT's AlbumService returns this as a normal UTF-8 protobuf string. - // Unlike the legacy Qzone HTTP endpoint, it does not rewrite Unicode - // emoji into ambiguous [em]...[/em] tags. - createnickname: creator?.nick ?? '', - last_upload_time: uint64ToSafeNumber(album.lastUploadTime, 'last_upload_time'), - cover: normalizeAlbumCover(album.cover), - }; + const creator = normalizeAlbumCreator(album.creator); + return { + id: album.albumId ?? '', + name: album.name ?? '', + picNum: uint64ToSafeNumber(album.uploadNumber, 'upload_number'), + createTime: uint64ToSafeNumber(album.createTime, 'create_time'), + desc: album.description ?? '', + owner: album.owner ?? '', + createuin: creator?.uin || album.owner || creator?.uid || '', + // QQ NT's AlbumService returns this as a normal UTF-8 protobuf string. + // Unlike the legacy Qzone HTTP endpoint, it does not rewrite Unicode + // emoji into ambiguous [em]...[/em] tags. + createnickname: creator?.nick ?? '', + last_upload_time: uint64ToSafeNumber(album.lastUploadTime, 'last_upload_time'), + cover: normalizeAlbumCover(album.cover), + }; } function convertBigIntToString(obj: unknown): JsonValue { - if (obj === null || obj === undefined) return null; - if (typeof obj === 'bigint') return obj.toString(); - if (Array.isArray(obj)) return obj.map(convertBigIntToString); - if (typeof obj === 'object') { - const result: JsonObject = {}; - for (const [key, value] of Object.entries(obj)) { - result[key] = convertBigIntToString(value); + if (obj === null || obj === undefined) { + return null; } - return result; - } - if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') return obj; - return null; + + if (typeof obj === 'bigint') { + return obj.toString(); + } + + if (Array.isArray(obj)) { + return obj.map(convertBigIntToString); + } + + if (typeof obj === 'object') { + const result: JsonObject = {}; + + for (const [key, value] of Object.entries(obj)) { + result[key] = convertBigIntToString(value); + } + + return result; + } + + if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') { + return obj; + } + + return null; } export class GroupAlbumApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - private async fetchAlbumList(groupId: number, attachInfo: string): Promise { - const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - const body = protobuf_encode({ - seq: GET_ALBUM_LIST_SEQ, - field2: new Uint8Array(0), - field3: new Uint8Array(0), - data: { - groupId: groupId.toString(), - attachInfo, - }, - traceId, - extMap: [{ key: 'fc-appid', value: '100' }], - }); + private async fetchAlbumList( + groupId: number, + attachInfo: string, + ): Promise { + const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + const body = protobuf_encode({ + seq: GET_ALBUM_LIST_SEQ, + field2: new Uint8Array(0), + field3: new Uint8Array(0), + data: { + groupId: groupId.toString(), + attachInfo, + }, + traceId, + extMap: [{ key: 'fc-appid', value: '100' }], + }); - log.debug( - 'get album list request: group=%d cursorChars=%d requestBytes=%d', - groupId, - attachInfo.length, - body.length, - ); - - const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, packetTimeoutMs()); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error( - `get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`, - ); - } - - const response = protobuf_decode(result.responseData); - const resultCode = response.result ?? 0; - if (resultCode !== 0) { - throw new Error( - `get group album list failed: result=${resultCode}, error=${response.errorText || 'unknown'}`, - ); - } - - const normalized: GroupAlbumWireResult = { - albumList: response.data?.albumList ?? [], - attachInfo: response.data?.attachInfo ?? '', - hasMore: response.data?.hasMore ?? false, - }; - - log.debug( - 'get album list response: group=%d albums=%d hasMore=%s cursorChars=%d responseBytes=%d', - groupId, - normalized.albumList.length, - String(normalized.hasMore), - normalized.attachInfo.length, - result.responseData.length, - ); - return normalized; - } - - /** QQ NT AlbumService-backed list, including its pagination cursor. */ - async listQun(groupId: number, attachInfo = ''): Promise { - const result = await this.fetchAlbumList(groupId, attachInfo); - return { - albumList: result.albumList.map(normalizeQunAlbum), - attachInfo: result.attachInfo, - hasMore: result.hasMore, - }; - } - - // OneBot compatibility shape used by get_group_album_list. - async list(groupId: number): Promise { - const albumList: GroupAlbumList = []; - const seenCursors = new Set(); - let attachInfo = ''; - let page = 0; - - while (true) { - const result = await this.fetchAlbumList(groupId, attachInfo); - page += 1; - albumList.push(...result.albumList.map(toLegacyAlbum)); - - if (!result.hasMore) { log.debug( - 'get complete album list: group=%d pages=%d albums=%d', - groupId, - page, - albumList.length, + 'get album list request: group=%d cursorChars=%d requestBytes=%d', + groupId, + attachInfo.length, + body.length, ); - return albumList; - } - const nextAttachInfo = result.attachInfo; - if (!nextAttachInfo) { - throw new Error( - `get group album list pagination failed: group=${groupId} page=${page} ` - + 'hasMore=true but cursor is empty', - ); - } - if (seenCursors.has(nextAttachInfo)) { - throw new Error( - `get group album list pagination failed: group=${groupId} repeated cursor at page ${page}`, - ); - } + const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, packetTimeoutMs()); - seenCursors.add(nextAttachInfo); - attachInfo = nextAttachInfo; - } - } - - // 上传图片到现有相册(HTTP 分片上传)。 - async upload(groupId: number, albumId: string, albumName: string, filePath: string): Promise { - const groupCode = groupId.toString(); - const uin = this.ctx.identity.uin; - const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin); - } - - async uploadVideo(groupId: number, albumId: string, albumName: string, filePath: string): Promise<{ id: string }> { - const groupCode = groupId.toString(); - const uin = this.ctx.identity.uin; - const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - return uploadVideoToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin); - } - - async getMediaList(groupId: number, albumId: string, attachInfo = ''): Promise { - const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - - const body = protobuf_encode({ - field1: 0, - field2: new Uint8Array(0), - field3: new Uint8Array(0), - reqInfo: { - groupId: groupId.toString(), - albumId, - field3: 0, - field4: '', - pageInfo: attachInfo, - }, - traceId, - extMap: [{ key: 'fc-appid', value: '100' }], - }); - - const result = await this.ctx.sendRawPacket( - 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList', - body, - packetTimeoutMs(), - ); - - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'failed to get album media list'); - } - - const resp = protobuf_decode(result.responseData); - - const retCode = resp.field1 ?? 0; - if (retCode !== 0) { - throw new Error(`fetch album media list error: retCode ${retCode}`); - } - - const data = resp.data ?? {}; - const mediaList = data.mediaList ?? []; - const nextAttachInfo = data.nextAttachInfo ?? ''; - - return convertBigIntToString({ mediaList, nextAttachInfo }) as unknown as GroupAlbumMediaResult; - } - - async comment(groupId: number, albumId: string, lloc: string, content: string): Promise { - const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - const clientKey = Date.now().toString(); - const uin = this.ctx.identity.uin; - const resolved = await this.resolveCommentMedia(groupId, albumId, lloc); - const batchId = optionalBatchId(resolved?.batchId); - if (batchId === undefined) { - throw new Error('comment album media error: media not found'); - } - const mediaLloc = commentMediaLloc(resolved, lloc); - const feed = await this.getQunFeedDetail(groupId, albumId, batchId, mediaLloc); - const ownerUin = feed.ownerUin || resolved?.uploader || ''; - const photoInfo = commentPhotoInfo( - feed.media, - mediaInfoForComment(resolved, mediaLloc), - albumId, - batchId, - ); - - const body = protobuf_encode({ - field1: DO_QUN_COMMENT_SEQ, - field2: new Uint8Array(0), - field3: new Uint8Array(0), - body: { - groupId: groupId.toString(), - field3: 2, - reqBody: { - field1: commentReqHeader(feed.cellCommon), - ...(ownerUin ? { field2: { field1: { uin: ownerUin } } } : {}), - field5: photoInfo, - }, - field5: { - user: { uin }, - contents: [{ type: 0, content }], - clientKey, - }, - }, - traceId, - extMap: [{ key: 'fc-appid', value: '100' }], - }); - - const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, packetTimeoutMs()); - - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'failed to comment on album media'); - } - - const resp = protobuf_decode(result.responseData); - const resultCode = resp.result ?? 0; - if (resultCode !== 0) { - throw new Error( - `comment album media error: retCode ${resultCode}` - + (resp.errorText ? `, ${resp.errorText}` : ''), - ); - } - - const commentData = commentFromResponse(resp); - if (!commentData.id) { - throw new Error('comment album media error: empty comment'); - } - - return convertBigIntToString({ - id: commentData.id, - user: { uin: commentData.user?.uin || uin }, - content: (commentData.content ?? [{ type: 0, content }]).map((item) => ({ - type: item.type ?? 0, - content: item.content ?? '', - })), - time: commentData.time ?? '0', - clientKey: commentData.clientKey || clientKey, - }) as unknown as GroupAlbumCommentResult; - } - - async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise { - const uin = this.ctx.identity.uin; - const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - - const type = isLike ? 2 : 1; - const status = isLike ? 0 : 1; - - const id = qunFeedCellId(groupId, albumId, batchId, lloc); - - const body = protobuf_encode({ - field1: 5495, - field2: 'h5_test', - field3: 'h5_test', - body: { - type, - like: { id, status }, - publish: { - cellCommon: { - time: BigInt(Date.now()), - feedId: `422_0_${batchId}`, - }, - cellUserInfo: { - user: { uin }, - }, - cellMedia: { - albumId, - batchId: BigInt(batchId), - }, - cellQunInfo: { - qunId: groupId.toString(), - }, - }, - clientKey, - }, - extMap: [{ key: 'fc-appid', value: '100' }], - }); - - const result = await this.ctx.sendRawPacket( - 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike', - body, - packetTimeoutMs(), - ); - - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'failed to like album media'); - } - - const resp = protobuf_decode(result.responseData); - const resCode = resp.field1; - - if (resCode !== 5495) { - throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`); - } - - return convertBigIntToString(resp.body?.like ?? {}); - } - - async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> { - const target = await this.resolveDeleteTarget(groupId, albumId, lloc); - const uin = this.ctx.identity.uin; - const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - - const body = protobuf_encode({ - field1: 8694, - field2: 'h5_test', - field3: 'h5_test', - body: { - groupId: groupId.toString(), - albumId, - mediaIds: [target.mediaId], - ...(target.batchId ? { batchIds: [target.batchId] } : {}), - }, - traceId: clientKey, - extMap: [{ key: 'fc-appid', value: '100' }], - }); - - const result = await this.ctx.sendRawPacket( - 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias', - body, - packetTimeoutMs(), - ); - - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'failed to delete album media'); - } - - const resp = protobuf_decode(result.responseData); - const resCode = resp.field1; - const errCode = resp.field2; - const errMsg = resp.field3; - - if (resCode !== 8694 || errCode) { - throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`); - } - - return { success: true }; - } - - /** - * Official delete uses a photo lloc, or a video's cover lloc plus batch id. - * Callers may pass either an image lloc or a video id; resolve the latter. - */ - private async resolveDeleteTarget( - groupId: number, - albumId: string, - mediaKey: string, - ): Promise<{ mediaId: string; batchId?: string }> { - try { - const seenCursors = new Set(); - let attachInfo = ''; - while (true) { - const page = await this.getMediaList(groupId, albumId, attachInfo); - const hit = findDeleteTarget(page.mediaList, mediaKey); - if (hit) return hit; - - const next = page.nextAttachInfo ?? ''; - if (!next || seenCursors.has(next)) { - return { mediaId: mediaKey }; + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error( + `get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`, + ); } - seenCursors.add(next); - attachInfo = next; - } - } catch (err) { - log.debug( - 'resolve album delete target failed, using raw id: group=%d album=%s err=%s', - groupId, - albumId, - err instanceof Error ? err.message : String(err), - ); - return { mediaId: mediaKey }; - } - } - /** - * Page the album when the caller only has a lloc / video id, so the - * comment can carry the official batch id and media kind. - */ - private async resolveCommentMedia( - groupId: number, - albumId: string, - mediaKey: string, - ): Promise { - const seenCursors = new Set(); - let attachInfo = ''; - while (true) { - const page = await this.getMediaList(groupId, albumId, attachInfo); - const hit = findCommentMedia(page.mediaList, mediaKey); - if (hit) return hit; + const response = protobuf_decode(result.responseData); + const resultCode = response.result ?? 0; - const next = page.nextAttachInfo ?? ''; - if (!next || seenCursors.has(next)) return undefined; - seenCursors.add(next); - attachInfo = next; - } - } + if (resultCode !== 0) { + throw new Error( + `get group album list failed: result=${resultCode}, error=${response.errorText || 'unknown'}`, + ); + } - private async getQunFeedDetail( - groupId: number, - albumId: string, - batchId: bigint, - lloc: string, - ): Promise<{ cellCommon: QunFeedCellCommon; ownerUin: string; media?: CommentReqPhotoInfo }> { - const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; - const body = protobuf_encode({ - seq: 0, - field2: new Uint8Array(0), - field3: new Uint8Array(0), - data: { - groupId: groupId.toString(), - feedId: '', - commentCount: GET_QUN_FEED_DETAIL_COMMENT_COUNT, - attachInfo: '', - albumId, - batchId: batchId.toString(), - lloc, - }, - traceId, - extMap: [{ key: 'fc-appid', value: '100' }], - }); + const normalized: GroupAlbumWireResult = { + albumList: response.data?.albumList ?? [], + attachInfo: response.data?.attachInfo ?? '', + hasMore: response.data?.hasMore ?? false, + }; - const result = await this.ctx.sendRawPacket(GET_QUN_FEED_DETAIL_CMD, body, packetTimeoutMs()); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'failed to fetch album feed'); + log.debug( + 'get album list response: group=%d albums=%d hasMore=%s cursorChars=%d responseBytes=%d', + groupId, + normalized.albumList.length, + String(normalized.hasMore), + normalized.attachInfo.length, + result.responseData.length, + ); + return normalized; } - const resp = protobuf_decode(result.responseData); - const resultCode = resp.result ?? 0; - if (resultCode !== 0) { - throw new Error( - `fetch album feed error: retCode ${resultCode}` - + (resp.errorText ? `, ${resp.errorText}` : ''), - ); + /** QQ NT AlbumService-backed list, including its pagination cursor. */ + async listQun(groupId: number, attachInfo = ''): Promise { + const result = await this.fetchAlbumList(groupId, attachInfo); + return { + albumList: result.albumList.map(normalizeQunAlbum), + attachInfo: result.attachInfo, + hasMore: result.hasMore, + }; } - const feed = resp.data?.feed?.feed; - const cell = feed?.cellCommon; - const feedId = cell?.feedId ?? ''; - if (!feedId) { - throw new Error('comment album media error: empty feed'); + // OneBot compatibility shape used by get_group_album_list. + async list(groupId: number): Promise { + const albumList: GroupAlbumList = []; + const seenCursors = new Set(); + let attachInfo = ''; + let page = 0; + + while (true) { + const result = await this.fetchAlbumList(groupId, attachInfo); + page += 1; + albumList.push(...result.albumList.map(toLegacyAlbum)); + + if (!result.hasMore) { + log.debug( + 'get complete album list: group=%d pages=%d albums=%d', + groupId, + page, + albumList.length, + ); + return albumList; + } + + const nextAttachInfo = result.attachInfo; + + if (!nextAttachInfo) { + throw new Error( + `get group album list pagination failed: group=${groupId} page=${page} ` + + 'hasMore=true but cursor is empty', + ); + } + + if (seenCursors.has(nextAttachInfo)) { + throw new Error( + `get group album list pagination failed: group=${groupId} repeated cursor at page ${page}`, + ); + } + + seenCursors.add(nextAttachInfo); + attachInfo = nextAttachInfo; + } + } + + // 上传图片到现有相册(HTTP 分片上传)。 + async upload( + groupId: number, + albumId: string, + albumName: string, + filePath: string, + ): Promise { + const groupCode = groupId.toString(); + const uin = this.ctx.identity.uin; + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin); + } + + async uploadVideo( + groupId: number, + albumId: string, + albumName: string, + filePath: string, + ): Promise<{ id: string }> { + const groupCode = groupId.toString(); + const uin = this.ctx.identity.uin; + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + return uploadVideoToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin); + } + + async getMediaList( + groupId: number, + albumId: string, + attachInfo = '', + ): Promise { + const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + + const body = protobuf_encode({ + field1: 0, + field2: new Uint8Array(0), + field3: new Uint8Array(0), + reqInfo: { + groupId: groupId.toString(), + albumId, + field3: 0, + field4: '', + pageInfo: attachInfo, + }, + traceId, + extMap: [{ key: 'fc-appid', value: '100' }], + }); + + const result = await this.ctx.sendRawPacket( + 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList', + body, + packetTimeoutMs(), + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to get album media list'); + } + + const resp = protobuf_decode(result.responseData); + + const retCode = resp.field1 ?? 0; + + if (retCode !== 0) { + throw new Error(`fetch album media list error: retCode ${retCode}`); + } + + const data = resp.data ?? {}; + const mediaList = data.mediaList ?? []; + const nextAttachInfo = data.nextAttachInfo ?? ''; + + return convertBigIntToString({ + mediaList, + nextAttachInfo, + }) as unknown as GroupAlbumMediaResult; + } + + async comment( + groupId: number, + albumId: string, + lloc: string, + content: string, + ): Promise { + const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + const clientKey = Date.now().toString(); + const uin = this.ctx.identity.uin; + const resolved = await this.resolveCommentMedia(groupId, albumId, lloc); + const batchId = optionalBatchId(resolved?.batchId); + + if (batchId === undefined) { + throw new Error('comment album media error: media not found'); + } + + const mediaLloc = commentMediaLloc(resolved, lloc); + const feed = await this.getQunFeedDetail(groupId, albumId, batchId, mediaLloc); + const ownerUin = feed.ownerUin || resolved?.uploader || ''; + const photoInfo = commentPhotoInfo( + feed.media, + mediaInfoForComment(resolved, mediaLloc), + albumId, + batchId, + ); + + const body = protobuf_encode({ + field1: DO_QUN_COMMENT_SEQ, + field2: new Uint8Array(0), + field3: new Uint8Array(0), + body: { + groupId: groupId.toString(), + field3: 2, + reqBody: { + field1: commentReqHeader(feed.cellCommon), + ...(ownerUin ? { field2: { field1: { uin: ownerUin } } } : {}), + field5: photoInfo, + }, + field5: { + user: { uin }, + contents: [{ type: 0, content }], + clientKey, + }, + }, + traceId, + extMap: [{ key: 'fc-appid', value: '100' }], + }); + + const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, packetTimeoutMs()); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to comment on album media'); + } + + const resp = protobuf_decode(result.responseData); + const resultCode = resp.result ?? 0; + + if (resultCode !== 0) { + throw new Error( + `comment album media error: retCode ${resultCode}` + + (resp.errorText ? `, ${resp.errorText}` : ''), + ); + } + + const commentData = commentFromResponse(resp); + + if (!commentData.id) { + throw new Error('comment album media error: empty comment'); + } + + return convertBigIntToString({ + id: commentData.id, + user: { uin: commentData.user?.uin || uin }, + content: (commentData.content ?? [{ type: 0, content }]).map((item) => ({ + type: item.type ?? 0, + content: item.content ?? '', + })), + time: commentData.time ?? '0', + clientKey: commentData.clientKey || clientKey, + }) as unknown as GroupAlbumCommentResult; + } + + async like( + groupId: number, + albumId: string, + batchId: string, + lloc: string | undefined, + isLike: boolean, + ): Promise { + const uin = this.ctx.identity.uin; + const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + + const type = isLike ? 2 : 1; + const status = isLike ? 0 : 1; + + const id = qunFeedCellId(groupId, albumId, batchId, lloc); + + const body = protobuf_encode({ + field1: 5495, + field2: 'h5_test', + field3: 'h5_test', + body: { + type, + like: { id, status }, + publish: { + cellCommon: { + time: BigInt(Date.now()), + feedId: `422_0_${batchId}`, + }, + cellUserInfo: { + user: { uin }, + }, + cellMedia: { + albumId, + batchId: BigInt(batchId), + }, + cellQunInfo: { + qunId: groupId.toString(), + }, + }, + clientKey, + }, + extMap: [{ key: 'fc-appid', value: '100' }], + }); + + const result = await this.ctx.sendRawPacket( + 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike', + body, + packetTimeoutMs(), + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to like album media'); + } + + const resp = protobuf_decode(result.responseData); + const resCode = resp.field1; + + if (resCode !== 5495) { + throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`); + } + + return convertBigIntToString(resp.body?.like ?? {}); + } + + async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> { + const target = await this.resolveDeleteTarget(groupId, albumId, lloc); + const uin = this.ctx.identity.uin; + const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + + const body = protobuf_encode({ + field1: 8694, + field2: 'h5_test', + field3: 'h5_test', + body: { + groupId: groupId.toString(), + albumId, + mediaIds: [target.mediaId], + ...(target.batchId ? { batchIds: [target.batchId] } : {}), + }, + traceId: clientKey, + extMap: [{ key: 'fc-appid', value: '100' }], + }); + + const result = await this.ctx.sendRawPacket( + 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias', + body, + packetTimeoutMs(), + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to delete album media'); + } + + const resp = protobuf_decode(result.responseData); + const resCode = resp.field1; + const errCode = resp.field2; + const errMsg = resp.field3; + + if (resCode !== 8694 || errCode) { + throw new Error( + `delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`, + ); + } + + return { success: true }; + } + + /** + * Official delete uses a photo lloc, or a video's cover lloc plus batch id. + * Callers may pass either an image lloc or a video id; resolve the latter. + */ + private async resolveDeleteTarget( + groupId: number, + albumId: string, + mediaKey: string, + ): Promise<{ mediaId: string; batchId?: string }> { + try { + const seenCursors = new Set(); + let attachInfo = ''; + + while (true) { + const page = await this.getMediaList(groupId, albumId, attachInfo); + const hit = findDeleteTarget(page.mediaList, mediaKey); + + if (hit) { + return hit; + } + + const next = page.nextAttachInfo ?? ''; + + if (!next || seenCursors.has(next)) { + return { mediaId: mediaKey }; + } + + seenCursors.add(next); + attachInfo = next; + } + } catch (err) { + log.debug( + 'resolve album delete target failed, using raw id: group=%d album=%s err=%s', + groupId, + albumId, + err instanceof Error ? err.message : String(err), + ); + return { mediaId: mediaKey }; + } + } + + /** + * Page the album when the caller only has a lloc / video id, so the + * comment can carry the official batch id and media kind. + */ + private async resolveCommentMedia( + groupId: number, + albumId: string, + mediaKey: string, + ): Promise { + const seenCursors = new Set(); + let attachInfo = ''; + + while (true) { + const page = await this.getMediaList(groupId, albumId, attachInfo); + const hit = findCommentMedia(page.mediaList, mediaKey); + + if (hit) { + return hit; + } + + const next = page.nextAttachInfo ?? ''; + + if (!next || seenCursors.has(next)) { + return undefined; + } + + seenCursors.add(next); + attachInfo = next; + } + } + + private async getQunFeedDetail( + groupId: number, + albumId: string, + batchId: bigint, + lloc: string, + ): Promise<{ cellCommon: QunFeedCellCommon; ownerUin: string; media?: CommentReqPhotoInfo }> { + const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; + const body = protobuf_encode({ + seq: 0, + field2: new Uint8Array(0), + field3: new Uint8Array(0), + data: { + groupId: groupId.toString(), + feedId: '', + commentCount: GET_QUN_FEED_DETAIL_COMMENT_COUNT, + attachInfo: '', + albumId, + batchId: batchId.toString(), + lloc, + }, + traceId, + extMap: [{ key: 'fc-appid', value: '100' }], + }); + + const result = await this.ctx.sendRawPacket( + GET_QUN_FEED_DETAIL_CMD, + body, + packetTimeoutMs(), + ); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'failed to fetch album feed'); + } + + const resp = protobuf_decode(result.responseData); + const resultCode = resp.result ?? 0; + + if (resultCode !== 0) { + throw new Error( + `fetch album feed error: retCode ${resultCode}` + + (resp.errorText ? `, ${resp.errorText}` : ''), + ); + } + + const feed = resp.data?.feed?.feed; + const cell = feed?.cellCommon; + const feedId = cell?.feedId ?? ''; + + if (!feedId) { + throw new Error('comment album media error: empty feed'); + } + + return { + cellCommon: cell ?? { feedId }, + ownerUin: feed?.cellUserInfo?.user?.uin ?? '', + media: feed?.cellMedia, + }; } - return { - cellCommon: cell ?? { feedId }, - ownerUin: feed?.cellUserInfo?.user?.uin ?? '', - media: feed?.cellMedia, - }; - } } interface AlbumDeleteMediaItem { - image?: { lloc?: string } | null; - video?: { id?: string; cover?: { lloc?: string } | null } | null; - batchId?: string | number; + image?: { lloc?: string } | null; + video?: { id?: string; cover?: { lloc?: string } | null } | null; + batchId?: string | number; } function findDeleteTarget( - mediaList: ReadonlyArray, - mediaKey: string, + mediaList: ReadonlyArray, + mediaKey: string, ): { mediaId: string; batchId?: string } | undefined { - for (const raw of mediaList) { - if (!raw || typeof raw !== 'object') continue; - const item = raw as AlbumDeleteMediaItem; - const batchId = item.batchId === undefined || item.batchId === '' - ? undefined - : String(item.batchId); - if (item.image?.lloc === mediaKey) { - return { mediaId: mediaKey, batchId }; + for (const raw of mediaList) { + if (!raw || typeof raw !== 'object') { + continue; + } + + const item = raw as AlbumDeleteMediaItem; + const batchId = + item.batchId === undefined || item.batchId === '' ? undefined : String(item.batchId); + + if (item.image?.lloc === mediaKey) { + return { mediaId: mediaKey, batchId }; + } + + const coverLloc = item.video?.cover?.lloc; + + if (item.video?.id === mediaKey || coverLloc === mediaKey) { + return { mediaId: coverLloc || mediaKey, batchId }; + } } - const coverLloc = item.video?.cover?.lloc; - if (item.video?.id === mediaKey || coverLloc === mediaKey) { - return { mediaId: coverLloc || mediaKey, batchId }; - } - } - return undefined; + + return undefined; } interface AlbumCommentMediaItem { - type?: number; - image?: { - name?: string; - sloc?: string; - lloc?: string; - isGif?: boolean; - hasRaw?: boolean; - } | null; - video?: { - id?: string; - cover?: { - name?: string; - sloc?: string; - lloc?: string; + type?: number; + image?: { + name?: string; + sloc?: string; + lloc?: string; + isGif?: boolean; + hasRaw?: boolean; } | null; - } | null; - uploader?: string; - batchId?: string | number | bigint; + video?: { + id?: string; + cover?: { + name?: string; + sloc?: string; + lloc?: string; + } | null; + } | null; + uploader?: string; + batchId?: string | number | bigint; } function optionalBatchId(value: unknown): bigint | undefined { - if (value === undefined || value === null || value === '') return undefined; - try { - const batchId = BigInt(value as string | number | bigint); - return batchId === 0n ? undefined : batchId; - } catch { - return undefined; - } + if (value === undefined || value === null || value === '') { + return undefined; + } + + try { + const batchId = BigInt(value as string | number | bigint); + return batchId === 0n ? undefined : batchId; + } catch { + return undefined; + } } function commentMediaLloc(item: AlbumCommentMediaItem | undefined, lloc: string): string { - if (item?.video?.cover?.lloc) return item.video.cover.lloc; - if (item?.image?.lloc) return item.image.lloc; - return lloc; + if (item?.video?.cover?.lloc) { + return item.video.cover.lloc; + } + + if (item?.image?.lloc) { + return item.image.lloc; + } + + return lloc; } function mediaInfoForComment(item: AlbumCommentMediaItem | undefined, lloc: string): MediaInfo { - const batchId = optionalBatchId(item?.batchId); - const shared: MediaInfo = { - ...(item?.uploader ? { uploader: item.uploader } : {}), - ...(batchId !== undefined ? { batchId } : {}), - }; - if (item?.video) { - return { - ...shared, - type: 1, - video: { cover: { lloc: item.video.cover?.lloc || lloc } }, + const batchId = optionalBatchId(item?.batchId); + const shared: MediaInfo = { + ...(item?.uploader ? { uploader: item.uploader } : {}), + ...(batchId !== undefined ? { batchId } : {}), + }; + + if (item?.video) { + return { + ...shared, + type: 1, + video: { cover: { lloc: item.video.cover?.lloc || lloc } }, + }; + } + + return { + ...shared, + type: 0, + image: { lloc: item?.image?.lloc || lloc }, }; - } - return { - ...shared, - type: 0, - image: { lloc: item?.image?.lloc || lloc }, - }; } function qunFeedCellId( - groupId: number, - albumId: string, - batchId: string | number | bigint, - lloc?: string, + groupId: number, + albumId: string, + batchId: string | number | bigint, + lloc?: string, ): string { - const head = `421_1_0_${groupId}|${albumId}|${batchId}`; - if (!lloc) return head; - return `${head}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`; + const head = `421_1_0_${groupId}|${albumId}|${batchId}`; + + if (!lloc) { + return head; + } + + return `${head}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`; } function commentReqHeader(cell: QunFeedCellCommon): CommentReqBodyHeader { - return { - ...(cell.time !== undefined ? { time: cell.time } : {}), - ...(cell.feedId ? { feedId: cell.feedId } : {}), - }; + return { + ...(cell.time !== undefined ? { time: cell.time } : {}), + ...(cell.feedId ? { feedId: cell.feedId } : {}), + }; } function commentPhotoInfo( - feedMedia: CommentReqPhotoInfo | undefined, - fallback: MediaInfo, - albumId: string, - batchId: bigint, + feedMedia: CommentReqPhotoInfo | undefined, + fallback: MediaInfo, + albumId: string, + batchId: bigint, ): CommentReqPhotoInfo { - if (feedMedia?.medias?.length) { - return { - medias: feedMedia.medias, - albumId: feedMedia.albumId || albumId, - batchId: feedMedia.batchId ?? batchId, - }; - } - return { medias: [fallback], albumId, batchId }; + if (feedMedia?.medias?.length) { + return { + medias: feedMedia.medias, + albumId: feedMedia.albumId || albumId, + batchId: feedMedia.batchId ?? batchId, + }; + } + + return { medias: [fallback], albumId, batchId }; } function findCommentMedia( - mediaList: ReadonlyArray, - mediaKey: string, + mediaList: ReadonlyArray, + mediaKey: string, ): AlbumCommentMediaItem | undefined { - for (const raw of mediaList) { - if (!raw || typeof raw !== 'object') continue; - const item = raw as AlbumCommentMediaItem; - if (item.image?.lloc === mediaKey) return item; - if (item.video?.id === mediaKey || item.video?.cover?.lloc === mediaKey) return item; - } - return undefined; + for (const raw of mediaList) { + if (!raw || typeof raw !== 'object') { + continue; + } + + const item = raw as AlbumCommentMediaItem; + + if (item.image?.lloc === mediaKey) { + return item; + } + + if (item.video?.id === mediaKey || item.video?.cover?.lloc === mediaKey) { + return item; + } + } + + return undefined; } function commentFromResponse(resp: DoQunCommentResponse): CommentRespData { - const wrapped = resp.comment; - if (!wrapped) return {}; - if (wrapped.data?.id) return wrapped.data; - if (wrapped.id) { - return { - id: wrapped.id, - content: wrapped.content, - time: wrapped.time, - clientKey: wrapped.clientKey, - user: wrapped.data?.user, - }; - } - return wrapped.data ?? {}; + const wrapped = resp.comment; + + if (!wrapped) { + return {}; + } + + if (wrapped.data?.id) { + return wrapped.data; + } + + if (wrapped.id) { + return { + id: wrapped.id, + content: wrapped.content, + time: wrapped.time, + clientKey: wrapped.clientKey, + user: wrapped.data?.user, + }; + } + + return wrapped.data ?? {}; } export interface GroupAlbumMediaResult { - mediaList: Array>; - nextAttachInfo: string; + mediaList: Array>; + nextAttachInfo: string; } interface GroupAlbumWireResult { - albumList: GroupAlbumInfoWire[]; - attachInfo: string; - hasMore: boolean; + albumList: GroupAlbumInfoWire[]; + attachInfo: string; + hasMore: boolean; } export interface GroupAlbumInfo { - id: string; - name: string; - picNum: number; - createTime: number; - desc: string; - owner: string; - createuin: string; - createnickname: string; - last_upload_time: number; - cover: QunAlbumCover | null; - [key: string]: JsonValue; + id: string; + name: string; + picNum: number; + createTime: number; + desc: string; + owner: string; + createuin: string; + createnickname: string; + last_upload_time: number; + cover: QunAlbumCover | null; + [key: string]: JsonValue; } export type GroupAlbumList = GroupAlbumInfo[]; export interface QunAlbumCreator { - uid: string; - nick: string; - is_sweet: boolean; - is_special: boolean; - is_super_like: boolean; - custom_id: string; - poly_id: string; - portrait: string; - can_follow: number; - isfollowed: number; - uin: string; - ditto_uin: string; + uid: string; + nick: string; + is_sweet: boolean; + is_special: boolean; + is_super_like: boolean; + custom_id: string; + poly_id: string; + portrait: string; + can_follow: number; + isfollowed: number; + uin: string; + ditto_uin: string; } export interface QunAlbumCoverUrl extends JsonObject { - url: string; - width: number; - height: number; + url: string; + width: number; + height: number; } export interface QunAlbumCoverPhotoUrl extends JsonObject { - spec: number; - url: QunAlbumCoverUrl | null; + spec: number; + url: QunAlbumCoverUrl | null; } export interface QunAlbumCoverImage extends JsonObject { - name: string; - sloc: string; - lloc: string; - photoUrls: QunAlbumCoverPhotoUrl[]; - defaultUrl: QunAlbumCoverUrl | null; - isGif: boolean; - hasRaw: boolean; + name: string; + sloc: string; + lloc: string; + photoUrls: QunAlbumCoverPhotoUrl[]; + defaultUrl: QunAlbumCoverUrl | null; + isGif: boolean; + hasRaw: boolean; } export interface QunAlbumCover extends JsonObject { - type: number; - image: QunAlbumCoverImage | null; + type: number; + image: QunAlbumCoverImage | null; } export interface QunAlbumInfo { - album_id: string; - owner: string; - name: string; - desc: string; - create_time: string; - modify_time: string; - last_upload_time: string; - upload_number: string; - cover: QunAlbumCover | null; - creator?: QunAlbumCreator; - top_flag: string; - busi_type: number; - status: number; - allow_share: boolean; - is_subscribe: boolean; - bitmap: string; - is_share_album: boolean; - qz_album_type: number; - cover_type: number; - default_desc: string; - sort_type: number; + album_id: string; + owner: string; + name: string; + desc: string; + create_time: string; + modify_time: string; + last_upload_time: string; + upload_number: string; + cover: QunAlbumCover | null; + creator?: QunAlbumCreator; + top_flag: string; + busi_type: number; + status: number; + allow_share: boolean; + is_subscribe: boolean; + bitmap: string; + is_share_album: boolean; + qz_album_type: number; + cover_type: number; + default_desc: string; + sort_type: number; } export interface QunAlbumListResult { - albumList: QunAlbumInfo[]; - attachInfo: string; - hasMore: boolean; + albumList: QunAlbumInfo[]; + attachInfo: string; + hasMore: boolean; } export interface GroupAlbumCommentResult { - id: string; - user: { uin: string }; - content: Array<{ type: number; content: string }>; - time: string; - clientKey: string; + id: string; + user: { uin: string }; + content: Array<{ type: number; content: string }>; + time: string; + clientKey: string; } diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts index bd99ce47..30bd705f 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/bridge/apis/group-file.ts @@ -1,6 +1,10 @@ import { createLogger } from '@snowluma/common/logger'; import type { FileUploadExt } from '@snowluma/proto-defs/highway'; -import { FileChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway'; +import { + FileChunkSource, + fetchHighwaySession, + uploadHighwayHttp, +} from '@snowluma/protocol/highway'; import { FILE_UPLOAD_MAX_BYTES } from '@snowluma/protocol/highway/utils'; import { stageSourceToDisk } from '@snowluma/protocol/highway/stage'; import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file'; @@ -26,50 +30,55 @@ import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move- 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 { TransGroupFile, type TransGroupFileResult } from '@snowluma/protocol/oidb-services/group-file/trans-group-file'; +import { + TransGroupFile, + type TransGroupFileResult, +} from '@snowluma/protocol/oidb-services/group-file/trans-group-file'; import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request'; import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request'; import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared'; const log = createLogger('GroupFile'); -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } +function asBridge(ctx: BridgeContext): Bridge { + return ctx as unknown as Bridge; +} // ─────────────── public result types ─────────────── export interface GroupFileInfo { - fileId: string; - fileName: string; - busId: number; - fileSize: number; - uploadTime: number; - deadTime: number; - modifyTime: number; - downloadTimes: number; - uploader: number; - uploaderName: string; + fileId: string; + fileName: string; + busId: number; + fileSize: number; + uploadTime: number; + deadTime: number; + modifyTime: number; + downloadTimes: number; + uploader: number; + uploaderName: string; } export interface GroupFolderInfo { - folderId: string; - folderName: string; - createTime: number; - creator: number; - creatorName: string; - totalFileCount: number; - lastUploadTime: number; - lastUploader: number; - lastUploaderName: string; + folderId: string; + folderName: string; + createTime: number; + creator: number; + creatorName: string; + totalFileCount: number; + lastUploadTime: number; + lastUploader: number; + lastUploaderName: string; } export interface GroupFilesResult { - files: GroupFileInfo[]; - folders: GroupFolderInfo[]; + files: GroupFileInfo[]; + folders: GroupFolderInfo[]; } export interface UploadFileResult { - fileId: string | null; - fileHash?: string | null; + fileId: string | null; + fileHash?: string | null; } // Re-export so callers don't have to dig into apis/shared. @@ -78,8 +87,11 @@ export type { MediaIndexNode } from './shared'; // ─────────────── file-specific helpers ─────────────── function normalizeDirectory(dir?: string): string { - if (!dir || !dir.trim()) return '/'; - return dir; + if (!dir || !dir.trim()) { + return '/'; + } + + return dir; } // Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives @@ -88,18 +100,22 @@ function normalizeDirectory(dir?: string): string { // rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000 // into a negative number. function int32ToIpv4Dotted(value: number): string { - const b1 = value & 0xFF; - const b2 = (value >>> 8) & 0xFF; - const b3 = (value >>> 16) & 0xFF; - const b4 = (value >>> 24) & 0xFF; - return `${b1}.${b2}.${b3}.${b4}`; + const b1 = value & 0xff; + const b2 = (value >>> 8) & 0xff; + const b3 = (value >>> 16) & 0xff; + const b4 = (value >>> 24) & 0xff; + return `${b1}.${b2}.${b3}.${b4}`; } function normalizeUploadFileName(name: string, fallback: string): string { - const trimmed = name.trim(); - if (trimmed) return trimmed; - const safeFallback = fallback.trim(); - return safeFallback || 'file.bin'; + const trimmed = name.trim(); + + if (trimmed) { + return trimmed; + } + + const safeFallback = fallback.trim(); + return safeFallback || 'file.bin'; } // QQ's "first 10 MB" checksum uses the magic limit 0x98A000 (10002432) — @@ -111,574 +127,675 @@ const MD5_HEAD_LIMIT = 10002432; /** Fail cleanly if the staged file changed since the streaming hash pass (a * local source mutated mid-send). The server's per-chunk md5 during the PUT is * the backstop; this is the cheap early check. */ -async function assertUnchanged(filePath: string, baseline: { size: number; mtimeMs: number }): Promise { - const now = await fsp.stat(filePath); - if (now.size !== baseline.size || now.mtimeMs !== baseline.mtimeMs) { - throw new Error('file source changed during send (mutated between hashing and upload)'); - } +async function assertUnchanged( + filePath: string, + baseline: { size: number; mtimeMs: number }, +): Promise { + const now = await fsp.stat(filePath); + + if (now.size !== baseline.size || now.mtimeMs !== baseline.mtimeMs) { + throw new Error('file source changed during send (mutated between hashing and upload)'); + } } function buildGroupFileUploadExt( - senderUin: number, - groupId: number, - fileName: string, - fileSize: number, - md5: Uint8Array, - fileId: string, - uploadKey: Uint8Array, - checkKey: Uint8Array, - uploadHost: string, - uploadPort: number, + senderUin: number, + groupId: number, + fileName: string, + fileSize: number, + md5: Uint8Array, + fileId: string, + uploadKey: Uint8Array, + checkKey: Uint8Array, + uploadHost: string, + uploadPort: number, ): Uint8Array { - return protobuf_encode({ - unknown1: 100, - unknown2: 1, - entry: { - busiBuff: { - busId: 102, - senderUin: BigInt(senderUin), - receiverUin: BigInt(groupId), - groupCode: BigInt(groupId), - }, - fileEntry: { - fileSize: BigInt(Math.max(0, fileSize)), - md5, - md5S2: md5, - checkKey, - fileId, - uploadKey, - }, - clientInfo: { - clientType: 3, - appId: '100', - terminalType: 3, - clientVer: '1.1.1', - unknown: 4, - }, - fileNameInfo: { - fileName, - }, - host: { - hosts: [ - { - url: { - host: uploadHost, - unknown: 1, + return protobuf_encode({ + unknown1: 100, + unknown2: 1, + entry: { + busiBuff: { + busId: 102, + senderUin: BigInt(senderUin), + receiverUin: BigInt(groupId), + groupCode: BigInt(groupId), }, - port: uploadPort, - }, - ], - }, - }, - unknown200: 0, - }); + fileEntry: { + fileSize: BigInt(Math.max(0, fileSize)), + md5, + md5S2: md5, + checkKey, + fileId, + uploadKey, + }, + clientInfo: { + clientType: 3, + appId: '100', + terminalType: 3, + clientVer: '1.1.1', + unknown: 4, + }, + fileNameInfo: { + fileName, + }, + host: { + hosts: [ + { + url: { + host: uploadHost, + unknown: 1, + }, + port: uploadPort, + }, + ], + }, + }, + unknown200: 0, + }); } function buildPrivateFileUploadExt( - senderUin: number, - fileName: string, - fileSize: number, - md5: Uint8Array, - sha1: Uint8Array, - fileId: string, - uploadKey: Uint8Array, - uploadHost: string, - uploadPort: number, + senderUin: number, + fileName: string, + fileSize: number, + md5: Uint8Array, + sha1: Uint8Array, + fileId: string, + uploadKey: Uint8Array, + uploadHost: string, + uploadPort: number, ): Uint8Array { - return protobuf_encode({ - unknown1: 100, - unknown2: 1, - entry: { - busiBuff: { - // #157: NapCat/Lagrange (and the QQ client, confirmed by packet - // capture) emit a busiBuff with ONLY senderUin — no busId. A stale - // busId:102 here made the offline-file server accept the highway - // upload but never finalise it as downloadable once the file got - // big (>5 MiB): the receiver saw the file but every download failed. - // (The other half of that bug was the wrong md5-head limit above.) - senderUin: BigInt(senderUin), - receiverUin: 0n, - groupCode: 0n, - }, - fileEntry: { - fileSize: BigInt(Math.max(0, fileSize)), - md5, - md5S2: md5, - checkKey: sha1, - fileId, - uploadKey, - }, - clientInfo: { - clientType: 3, - appId: '100', - terminalType: 3, - clientVer: '1.1.1', - unknown: 4, - }, - fileNameInfo: { - fileName, - }, - host: { - hosts: [ - { - url: { - host: uploadHost, - unknown: 1, + return protobuf_encode({ + unknown1: 100, + unknown2: 1, + entry: { + busiBuff: { + // #157: NapCat/Lagrange (and the QQ client, confirmed by packet + // capture) emit a busiBuff with ONLY senderUin — no busId. A stale + // busId:102 here made the offline-file server accept the highway + // upload but never finalise it as downloadable once the file got + // big (>5 MiB): the receiver saw the file but every download failed. + // (The other half of that bug was the wrong md5-head limit above.) + senderUin: BigInt(senderUin), + receiverUin: 0n, + groupCode: 0n, }, - port: uploadPort, - }, - ], - }, - }, - unknown3: 0, - unknown200: 1, - }); + fileEntry: { + fileSize: BigInt(Math.max(0, fileSize)), + md5, + md5S2: md5, + checkKey: sha1, + fileId, + uploadKey, + }, + clientInfo: { + clientType: 3, + appId: '100', + terminalType: 3, + clientVer: '1.1.1', + unknown: 4, + }, + fileNameInfo: { + fileName, + }, + host: { + hosts: [ + { + url: { + host: uploadHost, + unknown: 1, + }, + port: uploadPort, + }, + ], + }, + }, + unknown3: 0, + unknown200: 1, + }); } export class GroupFileApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - // ─────────────── publish (group file → chat) ─────────────── + // ─────────────── publish (group file → chat) ─────────────── - publish(groupId: number, fileId: string): Promise { - if (!fileId) throw new Error('publish requires fileId'); - return PublishGroupFile.invoke(this.ctx, { groupId, fileId }); - } - - trans(groupId: number, fileId: string): Promise { - if (!fileId) throw new Error('trans requires fileId'); - return TransGroupFile.invoke(this.ctx, { groupId, fileId }); - } - - // ─────────────── count ─────────────── - - getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { - return GetGroupFileCount.invoke(this.ctx, { groupId }); - } - - getSpace(groupId: number): Promise<{ usedSpace: number; totalSpace: number }> { - return GetGroupFileSpace.invoke(this.ctx, { groupId }); - } - - // ─────────────── upload (3-stage: OIDB preflight → highway → publish) ─────────────── - - async upload( - groupId: number, - source: string, - name = '', - folderId = '/', - uploadFile = true, - publishFile = uploadFile, - ): Promise { - const bridge = asBridge(this.ctx); - // Group/private files may legitimately be up to 4 GiB on QQ's wire, so - // override the default 1 GiB cap with the protocol ceiling. Stage onto a - // local disk path and stream-hash it — the (up to 4 GiB) file is never - // buffered in RAM. - const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES); - try { - if (staged.fileSize === 0) throw new Error('group file is empty'); - - const fileName = normalizeUploadFileName(name, staged.fileName); - const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline - const hashes = await hashFileStreaming(staged.filePath); - - const upload = await UploadGroupFileRequest.invoke(this.ctx, { - groupId, - fileName, - folderId: normalizeDirectory(folderId), - fileSize: staged.fileSize, - fileSha1: hashes.sha1, - fileMd5: hashes.md5, - }); - ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording); - - const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null; - if (!fileId) throw new Error('group file upload response missing file_id'); - - // Remember the upload so a later `send_group_msg` carrying just the - // file_id can route via `publish` without forcing the OneBot caller - // to thread fileName/size/md5 separately. For groups the wire - // publish (OIDB 0x6d9_4) only needs the file_id itself, so this is - // mainly for log-line correctness; the c2c counterpart in - // `uploadPrivate` is where the cache is actually load-bearing. - this.ctx.rememberUploadedFile({ - fileId, - scope: 'group', - groupId, - fileName, - fileSize: staged.fileSize, - fileMd5: hashes.md5, - fileSha1: hashes.sha1, - rememberedAt: Date.now(), - }); - - if (!upload.boolFileExist && uploadFile) { - const senderUin = toInt(this.ctx.identity.uin); - if (senderUin <= 0) throw new Error('invalid self uin for group file upload'); - - const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp) - || (typeof upload.serverDns === 'string' && upload.serverDns) - || ''; - const uploadPort = toInt(upload.uploadPort); - if (!uploadHost || uploadPort <= 0) { - throw new Error('group file upload host is invalid'); + publish(groupId: number, fileId: string): Promise { + if (!fileId) { + throw new Error('publish requires fileId'); } - const ext = buildGroupFileUploadExt( - senderUin, - groupId, - fileName, - staged.fileSize, - hashes.md5, - fileId, - upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0), - upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0), - uploadHost, - uploadPort, - ); - - // Fail cleanly if the source changed since hashing, then stream the PUT - // from disk. Fetch the session BEFORE opening the handle so - // uploadHighwayHttp (the handle's owner) is the next call and always - // closes it. - await assertUnchanged(staged.filePath, guardStat); - const session = await fetchHighwaySession(bridge); - const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize); - await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext); - } - - // Stage 3: file is on the server, now publish it as a chat message. - // - // Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes — - // the chat shows nothing. The publish step goes via a dedicated OIDB - // call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24) - // payload — the QQ-NT server rejects that with `result=79`. Mirrors - // Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when a - // caller only needs a valid file_id embedded elsewhere, e.g. a - // forward-message long-msg payload. Routes through `this.publish` so - // tests can mock at the same Api boundary. - if (publishFile) { - try { - await this.publish(groupId, fileId); - } catch (err) { - // The bytes are already on the server and the fileId is valid — - // fail loud but don't lose the upload result the action handler - // committed to returning. Callers can still resolve the file by - // id; they'll just have to re-publish it themselves. - log.warn('group file uploaded (fileId=%s) but chat post failed: %s', - fileId, err instanceof Error ? err.message : String(err)); - } - } - - return { fileId }; - } finally { - await staged.cleanup(); + return PublishGroupFile.invoke(this.ctx, { groupId, fileId }); } - } - async uploadPrivate( - userId: number, - source: string, - name = '', - uploadFile = true, - publishFile = uploadFile, - ): Promise { - const bridge = asBridge(this.ctx); - // Stage onto a local disk path + stream-hash — the (up to 4 GiB) file is - // never buffered in RAM. headLimit = MD5_HEAD_LIMIT yields the offline-file - // md510MCheckSum in the same single pass. - const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES); - try { - if (staged.fileSize === 0) throw new Error('private file is empty'); - - const targetUid = await this.ctx.resolveUserUid(userId); - const selfUid = await resolveSelfUid(this.ctx); - - const senderUin = toInt(this.ctx.identity.uin); - if (senderUin <= 0) throw new Error('invalid self uin for private file upload'); - - const fileName = normalizeUploadFileName(name, staged.fileName); - const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline - const hashes = await hashFileStreaming(staged.filePath, { headLimit: MD5_HEAD_LIMIT }); - - const upload = await UploadPrivateFileRequest.invoke(this.ctx, { - senderUid: selfUid, - receiverUid: targetUid, - fileName, - fileSize: staged.fileSize, - fileSha1: hashes.sha1, - fileMd5: hashes.md5, - md510MCheckSum: hashes.headMd5!, - }); - ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined); - - const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null; - const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null; - if (!fileId) throw new Error('private file upload response missing file_id'); - - // Cache the metadata so a later `send_private_msg` carrying just - // `{type:'file', file_id}` can resurrect the full c2c-file packet - // (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without - // this the recipient sees a 0-byte file because the OneBot send path - // has no way to recover those fields from the file_id alone. - this.ctx.rememberUploadedFile({ - fileId, - scope: 'private', - userId, - fileName, - fileSize: staged.fileSize, - fileMd5: hashes.md5, - fileSha1: hashes.sha1, - fileHash: fileHash ?? '', - rememberedAt: Date.now(), - }); - - if (!upload.boolFileExist && uploadFile) { - // Host selection. - // - // Current QQ-NT server rollout has stopped populating the legacy - // `uploadIp` (field 60) entirely. The host now arrives as the first - // entry of `rtpMediaPlatformUploadAddress` (field 210, repeated - // IPv4 message) — same place acidify reads it from since their - // 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort` - // (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN); - // acidify uses `inIP`/`inPort` exclusively and so do we, because - // that's the address the highway PUT actually needs to reach. - // - // The 32-bit IPs are little-endian-packed (byte0 = first octet) - // per acidify's `Int.toIpString()`. Cross-checked the byte order - // by inspecting their highway flow — there's no separate htonl - // step, so the integer is already in network-octet-first order. - // - // Older server versions still populate the legacy string fields - // (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain / - // uploadDns), so we fall through to those after rtpMediaPlatform. - // Pair an HTTPS-flavored host with `uploadHttpsPort` if that's - // what we picked. - const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress) - && upload.rtpMediaPlatformUploadAddress[0]) - ? upload.rtpMediaPlatformUploadAddress[0] : null; - const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0 - ? int32ToIpv4Dotted(rtpFirst.inIP) : ''; - const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number' - ? rtpFirst.inPort : 0; - const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0]) - ? upload.uploadIpList[0] : ''; - const uploadHost = (rtpInIP) - || (typeof upload.uploadIp === 'string' && upload.uploadIp) - || (typeof upload.uploadDomain === 'string' && upload.uploadDomain) - || (ipListFirst) - || (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain) - || (typeof upload.uploadDns === 'string' && upload.uploadDns) - || ''; - const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst - && typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain; - const uploadPort = rtpInIP && rtpInPort > 0 - ? rtpInPort - : httpsHostUsed && toInt(upload.uploadHttpsPort) > 0 - ? toInt(upload.uploadHttpsPort) - : toInt(upload.uploadPort); - if (!uploadHost || uploadPort <= 0) { - const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress) - ? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({ - outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort, - iPType: e.iPType, - }))) - : '[]'; - log.warn( - 'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s', - rtpDump, - upload.uploadIp ?? '', upload.uploadDomain ?? '', - JSON.stringify(upload.uploadIpList ?? []), - upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '', - upload.uploadLanip ?? '', upload.uploadPort ?? 0, - upload.uploadHttpsPort ?? 0, - ); - throw new Error('private file upload host is invalid'); + trans(groupId: number, fileId: string): Promise { + if (!fileId) { + throw new Error('trans requires fileId'); } - const ext = buildPrivateFileUploadExt( - senderUin, - fileName, - staged.fileSize, - hashes.md5, - hashes.sha1, - fileId, - upload.mediaPlatformUploadKey instanceof Uint8Array - ? upload.mediaPlatformUploadKey - : (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)), - uploadHost, - uploadPort, - ); + return TransGroupFile.invoke(this.ctx, { groupId, fileId }); + } - // Fail cleanly if the source changed since hashing, then stream the PUT - // from disk. Session BEFORE opening the handle so uploadHighwayHttp (the - // handle's owner) is the next call and always closes it. - await assertUnchanged(staged.filePath, guardStat); - const session = await fetchHighwaySession(bridge); - const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize); - await uploadHighwayHttp(bridge, session, 95, chunkSource, hashes.md5, ext); - } + // ─────────────── count ─────────────── + + getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { + return GetGroupFileCount.invoke(this.ctx, { groupId }); + } + + getSpace(groupId: number): Promise<{ usedSpace: number; totalSpace: number }> { + return GetGroupFileSpace.invoke(this.ctx, { groupId }); + } + + // ─────────────── upload (3-stage: OIDB preflight → highway → publish) ─────────────── + + async upload( + groupId: number, + source: string, + name = '', + folderId = '/', + uploadFile = true, + publishFile = uploadFile, + ): Promise { + const bridge = asBridge(this.ctx); + // Group/private files may legitimately be up to 4 GiB on QQ's wire, so + // override the default 1 GiB cap with the protocol ceiling. Stage onto a + // local disk path and stream-hash it — the (up to 4 GiB) file is never + // buffered in RAM. + const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES); - // Stage 3: publish the file as a c2c chat message. C2C files use - // `RichText.notOnlineFile` (parallel to `elems`), so we go through - // the dedicated `sendC2cFile` on MessageApi instead of `sendPrivate` - // which only knows about elems[]. NapCat does the same atomic - // upload+send dance — without it the file sits on the server and - // the recipient sees nothing. - if (publishFile) { try { - await this.ctx.apis.message.sendC2cFile(userId, targetUid, { + if (staged.fileSize === 0) { + throw new Error('group file is empty'); + } + + const fileName = normalizeUploadFileName(name, staged.fileName); + const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline + const hashes = await hashFileStreaming(staged.filePath); + + const upload = await UploadGroupFileRequest.invoke(this.ctx, { + groupId, + fileName, + folderId: normalizeDirectory(folderId), + fileSize: staged.fileSize, + fileSha1: hashes.sha1, + fileMd5: hashes.md5, + }); + ensureRetCodeZero( + 'group file upload', + upload.retCode, + upload.retMsg, + upload.clientWording, + ); + + const fileId = + typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null; + + if (!fileId) { + throw new Error('group file upload response missing file_id'); + } + + // Remember the upload so a later `send_group_msg` carrying just the + // file_id can route via `publish` without forcing the OneBot caller + // to thread fileName/size/md5 separately. For groups the wire + // publish (OIDB 0x6d9_4) only needs the file_id itself, so this is + // mainly for log-line correctness; the c2c counterpart in + // `uploadPrivate` is where the cache is actually load-bearing. + this.ctx.rememberUploadedFile({ + fileId, + scope: 'group', + groupId, + fileName, + fileSize: staged.fileSize, + fileMd5: hashes.md5, + fileSha1: hashes.sha1, + rememberedAt: Date.now(), + }); + + if (!upload.boolFileExist && uploadFile) { + const senderUin = toInt(this.ctx.identity.uin); + + if (senderUin <= 0) { + throw new Error('invalid self uin for group file upload'); + } + + const uploadHost = + (typeof upload.uploadIp === 'string' && upload.uploadIp) || + (typeof upload.serverDns === 'string' && upload.serverDns) || + ''; + const uploadPort = toInt(upload.uploadPort); + + if (!uploadHost || uploadPort <= 0) { + throw new Error('group file upload host is invalid'); + } + + const ext = buildGroupFileUploadExt( + senderUin, + groupId, + fileName, + staged.fileSize, + hashes.md5, + fileId, + upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0), + upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0), + uploadHost, + uploadPort, + ); + + // Fail cleanly if the source changed since hashing, then stream the PUT + // from disk. Fetch the session BEFORE opening the handle so + // uploadHighwayHttp (the handle's owner) is the next call and always + // closes it. + await assertUnchanged(staged.filePath, guardStat); + const session = await fetchHighwaySession(bridge); + const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize); + await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext); + } + + // Stage 3: file is on the server, now publish it as a chat message. + // + // Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes — + // the chat shows nothing. The publish step goes via a dedicated OIDB + // call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24) + // payload — the QQ-NT server rejects that with `result=79`. Mirrors + // Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when a + // caller only needs a valid file_id embedded elsewhere, e.g. a + // forward-message long-msg payload. Routes through `this.publish` so + // tests can mock at the same Api boundary. + if (publishFile) { + try { + await this.publish(groupId, fileId); + } catch (err) { + // The bytes are already on the server and the fileId is valid — + // fail loud but don't lose the upload result the action handler + // committed to returning. Callers can still resolve the file by + // id; they'll just have to re-publish it themselves. + log.warn( + 'group file uploaded (fileId=%s) but chat post failed: %s', + fileId, + err instanceof Error ? err.message : String(err), + ); + } + } + + return { fileId }; + } finally { + await staged.cleanup(); + } + } + + async uploadPrivate( + userId: number, + source: string, + name = '', + uploadFile = true, + publishFile = uploadFile, + ): Promise { + const bridge = asBridge(this.ctx); + // Stage onto a local disk path + stream-hash — the (up to 4 GiB) file is + // never buffered in RAM. headLimit = MD5_HEAD_LIMIT yields the offline-file + // md510MCheckSum in the same single pass. + const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES); + + try { + if (staged.fileSize === 0) { + throw new Error('private file is empty'); + } + + const targetUid = await this.ctx.resolveUserUid(userId); + const selfUid = await resolveSelfUid(this.ctx); + + const senderUin = toInt(this.ctx.identity.uin); + + if (senderUin <= 0) { + throw new Error('invalid self uin for private file upload'); + } + + const fileName = normalizeUploadFileName(name, staged.fileName); + const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline + const hashes = await hashFileStreaming(staged.filePath, { headLimit: MD5_HEAD_LIMIT }); + + const upload = await UploadPrivateFileRequest.invoke(this.ctx, { + senderUid: selfUid, + receiverUid: targetUid, + fileName, + fileSize: staged.fileSize, + fileSha1: hashes.sha1, + fileMd5: hashes.md5, + md510MCheckSum: hashes.headMd5!, + }); + ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined); + + const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null; + const fileHash = + typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null; + + if (!fileId) { + throw new Error('private file upload response missing file_id'); + } + + // Cache the metadata so a later `send_private_msg` carrying just + // `{type:'file', file_id}` can resurrect the full c2c-file packet + // (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without + // this the recipient sees a 0-byte file because the OneBot send path + // has no way to recover those fields from the file_id alone. + this.ctx.rememberUploadedFile({ + fileId, + scope: 'private', + userId, + fileName, + fileSize: staged.fileSize, + fileMd5: hashes.md5, + fileSha1: hashes.sha1, + fileHash: fileHash ?? '', + rememberedAt: Date.now(), + }); + + if (!upload.boolFileExist && uploadFile) { + // Host selection. + // + // Current QQ-NT server rollout has stopped populating the legacy + // `uploadIp` (field 60) entirely. The host now arrives as the first + // entry of `rtpMediaPlatformUploadAddress` (field 210, repeated + // IPv4 message) — same place acidify reads it from since their + // 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort` + // (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN); + // acidify uses `inIP`/`inPort` exclusively and so do we, because + // that's the address the highway PUT actually needs to reach. + // + // The 32-bit IPs are little-endian-packed (byte0 = first octet) + // per acidify's `Int.toIpString()`. Cross-checked the byte order + // by inspecting their highway flow — there's no separate htonl + // step, so the integer is already in network-octet-first order. + // + // Older server versions still populate the legacy string fields + // (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain / + // uploadDns), so we fall through to those after rtpMediaPlatform. + // Pair an HTTPS-flavored host with `uploadHttpsPort` if that's + // what we picked. + const rtpFirst = + Array.isArray(upload.rtpMediaPlatformUploadAddress) && + upload.rtpMediaPlatformUploadAddress[0] + ? upload.rtpMediaPlatformUploadAddress[0] + : null; + const rtpInIP = + rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0 + ? int32ToIpv4Dotted(rtpFirst.inIP) + : ''; + const rtpInPort = + rtpFirst && typeof rtpFirst.inPort === 'number' ? rtpFirst.inPort : 0; + const ipListFirst = + Array.isArray(upload.uploadIpList) && upload.uploadIpList[0] + ? upload.uploadIpList[0] + : ''; + const uploadHost = + rtpInIP || + (typeof upload.uploadIp === 'string' && upload.uploadIp) || + (typeof upload.uploadDomain === 'string' && upload.uploadDomain) || + ipListFirst || + (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain) || + (typeof upload.uploadDns === 'string' && upload.uploadDns) || + ''; + const httpsHostUsed = + !rtpInIP && + !upload.uploadIp && + !upload.uploadDomain && + !ipListFirst && + typeof upload.uploadHttpsDomain === 'string' && + !!upload.uploadHttpsDomain; + const uploadPort = + rtpInIP && rtpInPort > 0 + ? rtpInPort + : httpsHostUsed && toInt(upload.uploadHttpsPort) > 0 + ? toInt(upload.uploadHttpsPort) + : toInt(upload.uploadPort); + + if (!uploadHost || uploadPort <= 0) { + const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress) + ? JSON.stringify( + upload.rtpMediaPlatformUploadAddress.map((e) => ({ + outIP: e.outIP, + outPort: e.outPort, + inIP: e.inIP, + inPort: e.inPort, + iPType: e.iPType, + })), + ) + : '[]'; + log.warn( + 'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s', + rtpDump, + upload.uploadIp ?? '', + upload.uploadDomain ?? '', + JSON.stringify(upload.uploadIpList ?? []), + upload.uploadHttpsDomain ?? '', + upload.uploadDns ?? '', + upload.uploadLanip ?? '', + upload.uploadPort ?? 0, + upload.uploadHttpsPort ?? 0, + ); + throw new Error('private file upload host is invalid'); + } + + const ext = buildPrivateFileUploadExt( + senderUin, + fileName, + staged.fileSize, + hashes.md5, + hashes.sha1, + fileId, + upload.mediaPlatformUploadKey instanceof Uint8Array + ? upload.mediaPlatformUploadKey + : upload.uploadKey instanceof Uint8Array + ? upload.uploadKey + : new Uint8Array(0), + uploadHost, + uploadPort, + ); + + // Fail cleanly if the source changed since hashing, then stream the PUT + // from disk. Session BEFORE opening the handle so uploadHighwayHttp (the + // handle's owner) is the next call and always closes it. + await assertUnchanged(staged.filePath, guardStat); + const session = await fetchHighwaySession(bridge); + const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize); + await uploadHighwayHttp(bridge, session, 95, chunkSource, hashes.md5, ext); + } + + // Stage 3: publish the file as a c2c chat message. C2C files use + // `RichText.notOnlineFile` (parallel to `elems`), so we go through + // the dedicated `sendC2cFile` on MessageApi instead of `sendPrivate` + // which only knows about elems[]. NapCat does the same atomic + // upload+send dance — without it the file sits on the server and + // the recipient sees nothing. + if (publishFile) { + try { + await this.ctx.apis.message.sendC2cFile(userId, targetUid, { + fileId, + fileName, + fileSize: staged.fileSize, + fileMd5: hashes.md5, + fileHash: fileHash ?? '', + }); + } catch (err) { + log.warn( + 'private file uploaded (fileId=%s) but chat post failed: %s', + fileId, + err instanceof Error ? err.message : String(err), + ); + } + } + + return { fileId, fileHash }; + } finally { + await staged.cleanup(); + } + } + + // ─────────────── list (paginated loop) ─────────────── + + async list(groupId: number, folderId = '/'): Promise { + const targetDirectory = normalizeDirectory(folderId); + const files: GroupFileInfo[] = []; + const folders: GroupFolderInfo[] = []; + + const pageSize = 20; + let startIndex = 0; + + for (let page = 0; page < 200; page++) { + const list = await ListGroupFilesPage.invoke(this.ctx, { + groupId, + targetDirectory, + startIndex, + pageSize, + }); + + if (!list) { + break; + } + + for (const item of list.items) { + const type = toInt(item?.type); + + if (type === 1 && item?.fileInfo) { + const file = item.fileInfo; + const uploader = toInt(file.uploaderUin); + const cached = this.ctx.identity.findGroupMember(groupId, uploader); + files.push({ + fileId: typeof file.fileId === 'string' ? file.fileId : '', + fileName: typeof file.fileName === 'string' ? file.fileName : '', + busId: toInt(file.busId), + fileSize: toInt(file.fileSize), + uploadTime: toInt(file.uploadedTime), + deadTime: toInt(file.expireTime), + modifyTime: toInt(file.modifiedTime), + downloadTimes: toInt(file.downloadedTimes), + uploader, + uploaderName: + (typeof file.uploaderName === 'string' && file.uploaderName) || + cached?.card || + cached?.nickname || + '', + }); + } else if (type === 2 && item?.folderInfo) { + const folder = item.folderInfo; + const creator = toInt(folder.creatorUin); + const cached = this.ctx.identity.findGroupMember(groupId, creator); + const lastUploader = toInt(folder.modifierUin); + const lastUploaderCached = this.ctx.identity.findGroupMember( + groupId, + lastUploader, + ); + folders.push({ + folderId: typeof folder.folderId === 'string' ? folder.folderId : '', + folderName: typeof folder.folderName === 'string' ? folder.folderName : '', + createTime: toInt(folder.createTime), + creator, + creatorName: + (typeof folder.creatorName === 'string' && folder.creatorName) || + cached?.card || + cached?.nickname || + '', + totalFileCount: toInt(folder.totalFileCount), + lastUploadTime: toInt(folder.modifiedTime), + lastUploader, + lastUploaderName: + (typeof folder.modifierName === 'string' && folder.modifierName) || + lastUploaderCached?.card || + lastUploaderCached?.nickname || + '', + }); + } + } + + if (list.isEnd) { + break; + } + + startIndex += pageSize; + } + + return { files, folders }; + } + + // ─────────────── url fetch (group / private files) ─────────────── + + async getUrl(groupId: number, fileId: string, busId = 102): Promise { + return GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId }); + } + + async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise { + const bridge = asBridge(this.ctx); + const selfUid = await resolveSelfUid(bridge); + void userId; + return GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash }); + } + + // ─────────────── delete / move ─────────────── + + delete(groupId: number, fileId: string): Promise { + return DeleteGroupFile.invoke(this.ctx, { groupId, fileId }); + } + + move( + groupId: number, + fileId: string, + parentDirectory: string, + targetDirectory: string, + ): Promise { + return MoveGroupFile.invoke(this.ctx, { + groupId, fileId, - fileName, - fileSize: staged.fileSize, - fileMd5: hashes.md5, - fileHash: fileHash ?? '', - }); - } catch (err) { - log.warn('private file uploaded (fileId=%s) but chat post failed: %s', - fileId, err instanceof Error ? err.message : String(err)); - } - } - - return { fileId, fileHash }; - } finally { - await staged.cleanup(); - } - } - - // ─────────────── list (paginated loop) ─────────────── - - async list(groupId: number, folderId = '/'): Promise { - const targetDirectory = normalizeDirectory(folderId); - const files: GroupFileInfo[] = []; - const folders: GroupFolderInfo[] = []; - - const pageSize = 20; - let startIndex = 0; - for (let page = 0; page < 200; page++) { - const list = await ListGroupFilesPage.invoke(this.ctx, { - groupId, targetDirectory, startIndex, pageSize, - }); - if (!list) break; - - for (const item of list.items) { - const type = toInt(item?.type); - if (type === 1 && item?.fileInfo) { - const file = item.fileInfo; - const uploader = toInt(file.uploaderUin); - const cached = this.ctx.identity.findGroupMember(groupId, uploader); - files.push({ - fileId: typeof file.fileId === 'string' ? file.fileId : '', - fileName: typeof file.fileName === 'string' ? file.fileName : '', - busId: toInt(file.busId), - fileSize: toInt(file.fileSize), - uploadTime: toInt(file.uploadedTime), - deadTime: toInt(file.expireTime), - modifyTime: toInt(file.modifiedTime), - downloadTimes: toInt(file.downloadedTimes), - uploader, - uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName) - || cached?.card - || cached?.nickname - || '', - }); - } else if (type === 2 && item?.folderInfo) { - const folder = item.folderInfo; - const creator = toInt(folder.creatorUin); - const cached = this.ctx.identity.findGroupMember(groupId, creator); - const lastUploader = toInt(folder.modifierUin); - const lastUploaderCached = this.ctx.identity.findGroupMember(groupId, lastUploader); - folders.push({ - folderId: typeof folder.folderId === 'string' ? folder.folderId : '', - folderName: typeof folder.folderName === 'string' ? folder.folderName : '', - createTime: toInt(folder.createTime), - creator, - creatorName: (typeof folder.creatorName === 'string' && folder.creatorName) - || cached?.card - || cached?.nickname - || '', - totalFileCount: toInt(folder.totalFileCount), - lastUploadTime: toInt(folder.modifiedTime), - lastUploader, - lastUploaderName: (typeof folder.modifierName === 'string' && folder.modifierName) - || lastUploaderCached?.card - || lastUploaderCached?.nickname - || '', - }); - } - } - - if (list.isEnd) break; - startIndex += pageSize; + parentDirectory, + targetDirectory, + }); } - return { files, folders }; - } + rename( + groupId: number, + fileId: string, + parentDirectory: string, + newFileName: string, + ): Promise { + return RenameGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, newFileName }); + } - // ─────────────── url fetch (group / private files) ─────────────── + // ─────────────── folders ─────────────── - async getUrl(groupId: number, fileId: string, busId = 102): Promise { - return GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId }); - } + createFolder(groupId: number, name: string, parentId = '/'): Promise { + return CreateGroupFolder.invoke(this.ctx, { + groupId, + parentId: normalizeDirectory(parentId), + folderName: name, + }); + } - async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise { - const bridge = asBridge(this.ctx); - const selfUid = await resolveSelfUid(bridge); - void userId; - return GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash }); - } + deleteFolder(groupId: number, folderId: string): Promise { + return DeleteGroupFolder.invoke(this.ctx, { groupId, folderId }); + } - // ─────────────── delete / move ─────────────── + renameFolder(groupId: number, folderId: string, newFolderName: string): Promise { + return RenameGroupFolder.invoke(this.ctx, { groupId, folderId, newFolderName }); + } - delete(groupId: number, fileId: string): Promise { - return DeleteGroupFile.invoke(this.ctx, { groupId, fileId }); - } + // ─────────────── rich-media URL by node ─────────────── - move(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise { - return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory }); - } + getPttUrl(groupId: number, node: MediaIndexNode): Promise { + return GetGroupPttUrl.invoke(this.ctx, { groupId, node }); + } - rename(groupId: number, fileId: string, parentDirectory: string, newFileName: string): Promise { - return RenameGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, newFileName }); - } + async getPrivatePttUrl(node: MediaIndexNode): Promise { + const bridge = asBridge(this.ctx); + const selfUid = await resolveSelfUid(bridge); + return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node }); + } - // ─────────────── folders ─────────────── + getVideoUrl(groupId: number, node: MediaIndexNode): Promise { + return GetGroupVideoUrl.invoke(this.ctx, { groupId, node }); + } - createFolder(groupId: number, name: string, parentId = '/'): Promise { - return CreateGroupFolder.invoke(this.ctx, { - groupId, parentId: normalizeDirectory(parentId), folderName: name, - }); - } - - deleteFolder(groupId: number, folderId: string): Promise { - return DeleteGroupFolder.invoke(this.ctx, { groupId, folderId }); - } - - renameFolder(groupId: number, folderId: string, newFolderName: string): Promise { - return RenameGroupFolder.invoke(this.ctx, { groupId, folderId, newFolderName }); - } - - // ─────────────── rich-media URL by node ─────────────── - - getPttUrl(groupId: number, node: MediaIndexNode): Promise { - return GetGroupPttUrl.invoke(this.ctx, { groupId, node }); - } - - async getPrivatePttUrl(node: MediaIndexNode): Promise { - const bridge = asBridge(this.ctx); - const selfUid = await resolveSelfUid(bridge); - return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node }); - } - - getVideoUrl(groupId: number, node: MediaIndexNode): Promise { - return GetGroupVideoUrl.invoke(this.ctx, { groupId, node }); - } - - async getPrivateVideoUrl(node: MediaIndexNode): Promise { - const bridge = asBridge(this.ctx); - const selfUid = await resolveSelfUid(bridge); - return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node }); - } + async getPrivateVideoUrl(node: MediaIndexNode): Promise { + const bridge = asBridge(this.ctx); + const selfUid = await resolveSelfUid(bridge); + return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node }); + } } diff --git a/packages/core/src/bridge/apis/history-request-gate.ts b/packages/core/src/bridge/apis/history-request-gate.ts index e3566248..f3f5d455 100644 --- a/packages/core/src/bridge/apis/history-request-gate.ts +++ b/packages/core/src/bridge/apis/history-request-gate.ts @@ -1,11 +1,11 @@ export interface HistoryRequestGateClock { - now(): number; - sleep(ms: number, signal?: AbortSignal): Promise; + now(): number; + sleep(ms: number, signal?: AbortSignal): Promise; } const SYSTEM_CLOCK: HistoryRequestGateClock = { - now: () => Date.now(), - sleep: (ms, signal) => abortableSleep(ms, signal), + now: () => Date.now(), + sleep: (ms, signal) => abortableSleep(ms, signal), }; /** @@ -16,93 +16,95 @@ const SYSTEM_CLOCK: HistoryRequestGateClock = { * both sides of an automatic history-sync request. */ export class HistoryRequestGate { - private tail: Promise = Promise.resolve(); - private lastStartedAt: number | null = null; - private nextAllowedAt = 0; + private tail: Promise = Promise.resolve(); + private lastStartedAt: number | null = null; + private nextAllowedAt = 0; - constructor(private readonly clock: HistoryRequestGateClock = SYSTEM_CLOCK) {} + constructor(private readonly clock: HistoryRequestGateClock = SYSTEM_CLOCK) {} - run( - minimumGapMs: number, - operation: () => Promise, - signal?: AbortSignal, - ): Promise { - if (!Number.isSafeInteger(minimumGapMs) || minimumGapMs < 0) { - return Promise.reject(new Error(`history request gap is invalid: ${String(minimumGapMs)}`)); + run(minimumGapMs: number, operation: () => Promise, signal?: AbortSignal): Promise { + if (!Number.isSafeInteger(minimumGapMs) || minimumGapMs < 0) { + return Promise.reject( + new Error(`history request gap is invalid: ${String(minimumGapMs)}`), + ); + } + + let operationStarted = false; + const result = this.tail.then(async () => { + throwIfAborted(signal); + const now = this.clock.now(); + const requestedBoundary = + this.lastStartedAt === null ? now : this.lastStartedAt + minimumGapMs; + const wait = Math.max(this.nextAllowedAt, requestedBoundary) - now; + + if (wait > 0) { + await this.clock.sleep(wait, signal); + } + + throwIfAborted(signal); + const startedAt = this.clock.now(); + this.lastStartedAt = startedAt; + this.nextAllowedAt = startedAt + minimumGapMs; + operationStarted = true; + return operation(); + }); + + this.tail = result.then( + () => undefined, + () => undefined, + ); + return signal ? rejectWhileQueuedOnAbort(result, signal, () => operationStarted) : result; } - - let operationStarted = false; - const result = this.tail.then(async () => { - throwIfAborted(signal); - const now = this.clock.now(); - const requestedBoundary = this.lastStartedAt === null - ? now - : this.lastStartedAt + minimumGapMs; - const wait = Math.max(this.nextAllowedAt, requestedBoundary) - now; - if (wait > 0) await this.clock.sleep(wait, signal); - - throwIfAborted(signal); - const startedAt = this.clock.now(); - this.lastStartedAt = startedAt; - this.nextAllowedAt = startedAt + minimumGapMs; - operationStarted = true; - return operation(); - }); - - this.tail = result.then( - () => undefined, - () => undefined, - ); - return signal - ? rejectWhileQueuedOnAbort(result, signal, () => operationStarted) - : result; - } } function throwIfAborted(signal?: AbortSignal): void { - if (signal?.aborted) { - throw signal.reason ?? new Error('history request aborted'); - } + if (signal?.aborted) { + throw signal.reason ?? new Error('history request aborted'); + } } function abortableSleep(ms: number, signal?: AbortSignal): Promise { - throwIfAborted(signal); - if (!signal) { - return new Promise((resolve) => setTimeout(resolve, ms)); - } + throwIfAborted(signal); - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - signal.removeEventListener('abort', onAbort); - resolve(); - }, ms); - const onAbort = () => { - clearTimeout(timer); - signal.removeEventListener('abort', onAbort); - reject(signal.reason ?? new Error('history request aborted')); - }; - signal.addEventListener('abort', onAbort, { once: true }); - }); + if (!signal) { + return new Promise((resolve) => setTimeout(resolve, ms)); + } + + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + signal.removeEventListener('abort', onAbort); + resolve(); + }, ms); + + const onAbort = () => { + clearTimeout(timer); + signal.removeEventListener('abort', onAbort); + reject(signal.reason ?? new Error('history request aborted')); + }; + + signal.addEventListener('abort', onAbort, { once: true }); + }); } function rejectWhileQueuedOnAbort( - result: Promise, - signal: AbortSignal, - hasStarted: () => boolean, + result: Promise, + signal: AbortSignal, + hasStarted: () => boolean, ): Promise { - if (signal.aborted && !hasStarted()) { - return Promise.reject(signal.reason ?? new Error('history request aborted')); - } + if (signal.aborted && !hasStarted()) { + return Promise.reject(signal.reason ?? new Error('history request aborted')); + } - return new Promise((resolve, reject) => { - const onAbort = () => { - if (!hasStarted()) { - reject(signal.reason ?? new Error('history request aborted')); - } - }; - signal.addEventListener('abort', onAbort); - result.then(resolve, reject).finally(() => { - signal.removeEventListener('abort', onAbort); + return new Promise((resolve, reject) => { + const onAbort = () => { + if (!hasStarted()) { + reject(signal.reason ?? new Error('history request aborted')); + } + }; + + signal.addEventListener('abort', onAbort); + result.then(resolve, reject).finally(() => { + signal.removeEventListener('abort', onAbort); + }); }); - }); } diff --git a/packages/core/src/bridge/apis/index.ts b/packages/core/src/bridge/apis/index.ts index acd37f31..96b0050b 100644 --- a/packages/core/src/bridge/apis/index.ts +++ b/packages/core/src/bridge/apis/index.ts @@ -17,38 +17,38 @@ import { WebApi } from './web'; import { SystemFaceApi } from './system-face'; export interface ApiHub { - /** Personal QQ collections: authenticated list retrieval and pagination. */ - readonly collection: CollectionApi; - /** Send/recall/markRead operations across c2c + group + c2c-file. */ - readonly message: MessageApi; - /** Friend / group / member roster + user-profile + group-request-list + download-rkey. */ - readonly contacts: ContactsApi; - /** Group moderation: mute/kick/admin/card/name/title/leave + join-policy. */ - readonly groupAdmin: GroupAdminApi; - /** Group file CRUD + private (c2c) file upload + media URL resolvers. */ - readonly groupFile: GroupFileApi; - /** Group photo album: list/upload/comment/like/delete + media listing. */ - readonly groupAlbum: GroupAlbumApi; - /** Personal QQ-Zone (个人空间): 说说 list + (future) publish/like/comment. */ - readonly qzone: QzoneApi; - /** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */ - readonly interaction: InteractionApi; - /** Friend roster mutations: handleRequest / delete / setRemark. */ - readonly friend: FriendApi; - /** Personal profile: status / avatar / nickname / likes / custom-faces. */ - readonly profile: ProfileApi; - /** QQ 闪传(fileset 文件集): 上传/查询/分享/发送/删除/重命名。 */ - readonly flashTransfer: FlashTransferApi; - /** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */ - readonly forward: ForwardApi; - /** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */ - readonly misc: MiscApi; - /** Tier-2 napcat-parity: group todo / stranger status / AI voice. */ - readonly extras: ExtrasApi; - /** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */ - readonly web: WebApi; - /** QQ system-face directory: durable catalog, id lookup, and search. */ - readonly systemFace: SystemFaceApi; + /** Personal QQ collections: authenticated list retrieval and pagination. */ + readonly collection: CollectionApi; + /** Send/recall/markRead operations across c2c + group + c2c-file. */ + readonly message: MessageApi; + /** Friend / group / member roster + user-profile + group-request-list + download-rkey. */ + readonly contacts: ContactsApi; + /** Group moderation: mute/kick/admin/card/name/title/leave + join-policy. */ + readonly groupAdmin: GroupAdminApi; + /** Group file CRUD + private (c2c) file upload + media URL resolvers. */ + readonly groupFile: GroupFileApi; + /** Group photo album: list/upload/comment/like/delete + media listing. */ + readonly groupAlbum: GroupAlbumApi; + /** Personal QQ-Zone (个人空间): 说说 list + (future) publish/like/comment. */ + readonly qzone: QzoneApi; + /** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */ + readonly interaction: InteractionApi; + /** Friend roster mutations: handleRequest / delete / setRemark. */ + readonly friend: FriendApi; + /** Personal profile: status / avatar / nickname / likes / custom-faces. */ + readonly profile: ProfileApi; + /** QQ 闪传(fileset 文件集): 上传/查询/分享/发送/删除/重命名。 */ + readonly flashTransfer: FlashTransferApi; + /** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */ + readonly forward: ForwardApi; + /** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */ + readonly misc: MiscApi; + /** Tier-2 napcat-parity: group todo / stranger status / AI voice. */ + readonly extras: ExtrasApi; + /** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */ + readonly web: WebApi; + /** QQ system-face directory: durable catalog, id lookup, and search. */ + readonly systemFace: SystemFaceApi; } /** @@ -60,24 +60,24 @@ export interface ApiHub { * complexity for ~13 small classes. */ export function buildApiHub(ctx: BridgeContext): ApiHub { - return { - collection: new CollectionApi(ctx), - message: new MessageApi(ctx), - contacts: new ContactsApi(ctx), - groupAdmin: new GroupAdminApi(ctx), - groupFile: new GroupFileApi(ctx), - groupAlbum: new GroupAlbumApi(ctx), - qzone: new QzoneApi(ctx), - interaction: new InteractionApi(ctx), - friend: new FriendApi(ctx), - profile: new ProfileApi(ctx), - flashTransfer: new FlashTransferApi(ctx), - forward: new ForwardApi(ctx), - misc: new MiscApi(ctx), - extras: new ExtrasApi(ctx), - web: new WebApi(ctx), - systemFace: new SystemFaceApi(ctx), - }; + return { + collection: new CollectionApi(ctx), + message: new MessageApi(ctx), + contacts: new ContactsApi(ctx), + groupAdmin: new GroupAdminApi(ctx), + groupFile: new GroupFileApi(ctx), + groupAlbum: new GroupAlbumApi(ctx), + qzone: new QzoneApi(ctx), + interaction: new InteractionApi(ctx), + friend: new FriendApi(ctx), + profile: new ProfileApi(ctx), + flashTransfer: new FlashTransferApi(ctx), + forward: new ForwardApi(ctx), + misc: new MiscApi(ctx), + extras: new ExtrasApi(ctx), + web: new WebApi(ctx), + systemFace: new SystemFaceApi(ctx), + }; } // Re-export the Api classes themselves so callers can write @@ -93,12 +93,12 @@ export { GroupAlbumApi } from './group-album'; export { GroupFileApi } from './group-file'; export { InteractionApi } from './interaction'; export { - MessageApi, - LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS, - type GroupHistorySyncState, - type HistorySyncPrivateTarget, - type HistorySyncState, - type PrivateHistorySyncState, + MessageApi, + LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS, + type GroupHistorySyncState, + type HistorySyncPrivateTarget, + type HistorySyncState, + type PrivateHistorySyncState, } from './message'; export { MiscApi } from './misc'; export { ProfileApi } from './profile'; diff --git a/packages/core/src/bridge/apis/interaction.ts b/packages/core/src/bridge/apis/interaction.ts index 27c63fe4..4d170392 100644 --- a/packages/core/src/bridge/apis/interaction.ts +++ b/packages/core/src/bridge/apis/interaction.ts @@ -15,47 +15,56 @@ import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-react import type { BridgeContext } from '../bridge-context'; export class InteractionApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise { - return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin }); - } - - sendLike(userId: number, count: number): Promise { - return SendLike.invoke(this.ctx, { userId, count }); - } - - setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise { - return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet }); - } - - setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise { - return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable }); - } - - /** Fetch the reactor list for one emoji on a group message. */ - async getEmojiLikes( - groupId: number, - sequence: number, - emojiId: string, - emojiType = 1, - count = 10, - cookie = '', - ): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> { - try { - return await GetEmojiLikes.invoke(this.ctx, { groupId, sequence, emojiId, emojiType, count, cookie }); - } catch { - return { users: [], cookie: '', isLast: true }; + sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise { + return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin }); } - } - /** - * Recent-used emoji catalog (0x9084_1). Not a per-message reaction list. - */ - fetchReactionSummary( - groupId: number, - sequence: number, - ): Promise> { - return FetchReactionSummary.invoke(this.ctx, { groupId, sequence }); - } + sendLike(userId: number, count: number): Promise { + return SendLike.invoke(this.ctx, { userId, count }); + } + + setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise { + return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet }); + } + + setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise { + return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable }); + } + + /** Fetch the reactor list for one emoji on a group message. */ + async getEmojiLikes( + groupId: number, + sequence: number, + emojiId: string, + emojiType = 1, + count = 10, + cookie = '', + ): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> { + try { + return await GetEmojiLikes.invoke(this.ctx, { + groupId, + sequence, + emojiId, + emojiType, + count, + cookie, + }); + } catch { + return { users: [], cookie: '', isLast: true }; + } + } + + /** + * Recent-used emoji catalog (0x9084_1). Not a per-message reaction list. + */ + fetchReactionSummary( + groupId: number, + sequence: number, + ): Promise< + Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }> + > { + return FetchReactionSummary.invoke(this.ctx, { groupId, sequence }); + } } diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/bridge/apis/message.ts index 13b6f0db..d3a29e8c 100644 --- a/packages/core/src/bridge/apis/message.ts +++ b/packages/core/src/bridge/apis/message.ts @@ -1,32 +1,26 @@ -import type { - SendMessageRequest, - SendMessageResponse, -} from '@snowluma/proto-defs/action'; +import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action'; import type { FileExtra } from '@snowluma/proto-defs/message'; import type { - C2CReadedReportResponseItem, - C2CRecallRequest, - GroupReadedReportResponseItem, - GroupRecallRequest, - SsoReadedReportReq, - SsoReadedReportResp, + C2CReadedReportResponseItem, + C2CRecallRequest, + GroupReadedReportResponseItem, + GroupRecallRequest, + SsoReadedReportReq, + SsoReadedReportResp, } from '@snowluma/proto-defs/oidb-actions/base'; import { buildSendElems } from '@snowluma/protocol/element-builder'; import { assertWindowShakeSendPolicy } from '@snowluma/protocol/element-manifest'; import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file'; +import { datalineTextFromElements, encodeDatalineText } from '@snowluma/protocol/dataline/codec'; import { - datalineTextFromElements, - encodeDatalineText, -} from '@snowluma/protocol/dataline/codec'; -import { - findDatalineDeviceByUin, - type DatalineDeviceContact, + findDatalineDeviceByUin, + type DatalineDeviceContact, } from '@snowluma/protocol/dataline/device-contacts'; import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events'; import { - fetchC2cMessageRange, - fetchC2cRoamMessagePage, - fetchGroupMessageRange, + fetchC2cMessageRange, + fetchC2cRoamMessagePage, + fetchGroupMessageRange, } from '@snowluma/protocol/msg-push'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { createLogger } from '@snowluma/common/logger'; @@ -48,174 +42,210 @@ const SEND_MSG_CMD = 'MessageSvc.PbSendMsg'; const READ_REPORT_CMD = 'trpc.msg.msg_svc.MsgService.SsoReadedReport'; const READ_REPORT_BATCH_SIZE = 100; export const LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS = { - maxTargetsPerKind: READ_REPORT_BATCH_SIZE, - maxMessagesPerSession: 20, - minimumGapMs: 2_000, + maxTargetsPerKind: READ_REPORT_BATCH_SIZE, + maxMessagesPerSession: 20, + minimumGapMs: 2_000, } as const; const log = createLogger('Bridge.Message'); function decodeReadReportResponse(result: SendPacketResult, label: string): SsoReadedReportResp { - if (!result.success) { - throw new Error(result.errorMessage || `${label} transport failed`); - } - if (!result.gotResponse || !result.responseData || result.responseData.length === 0) { - throw new Error(`${label} response is empty`); - } + if (!result.success) { + throw new Error(result.errorMessage || `${label} transport failed`); + } - let response: SsoReadedReportResp; - try { - response = protobuf_decode(result.responseData); - } catch (error) { - throw new Error(`${label} response decode failed: ${error instanceof Error ? error.message : String(error)}`); - } + if (!result.gotResponse || !result.responseData || result.responseData.length === 0) { + throw new Error(`${label} response is empty`); + } - const resultCode = response.resultCode ?? 0; - if (resultCode !== 0) { - throw new Error(response.errorMessage || `${label} failed with result code ${resultCode}`); - } - return response; + let response: SsoReadedReportResp; + + try { + response = protobuf_decode(result.responseData); + } catch (error) { + throw new Error( + `${label} response decode failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } + + const resultCode = response.resultCode ?? 0; + + if (resultCode !== 0) { + throw new Error(response.errorMessage || `${label} failed with result code ${resultCode}`); + } + + return response; } interface C2CReadTarget { - userId: number; - uid: string; + userId: number; + uid: string; } export interface HistorySyncPrivateTarget { - userId: number; - uid: string; + userId: number; + uid: string; } export interface GroupHistorySyncState { - groupId: number; - readSeq: number; - latestSeq: number; + groupId: number; + readSeq: number; + latestSeq: number; } export interface PrivateHistorySyncState extends HistorySyncPrivateTarget { - readSeq: number; - latestSeq: number; - lastMsgTime: number; + readSeq: number; + latestSeq: number; + lastMsgTime: number; } export interface HistorySyncState { - groups: GroupHistorySyncState[]; - privateUsers: PrivateHistorySyncState[]; + groups: GroupHistorySyncState[]; + privateUsers: PrivateHistorySyncState[]; } interface ReadResponseItem { - resultCode?: number; - errorMessage?: string; + resultCode?: number; + errorMessage?: string; } function uniqueSessionIds(ids: readonly number[], label: string): number[] { - const result: number[] = []; - const seen = new Set(); - for (const id of ids) { - if (!Number.isSafeInteger(id) || id <= 0) { - throw new Error(`invalid ${label} read target ${String(id)}`); + const result: number[] = []; + const seen = new Set(); + + for (const id of ids) { + if (!Number.isSafeInteger(id) || id <= 0) { + throw new Error(`invalid ${label} read target ${String(id)}`); + } + + if (!seen.has(id)) { + seen.add(id); + result.push(id); + } } - if (!seen.has(id)) { - seen.add(id); - result.push(id); - } - } - return result; + + return result; } function uniqueHistorySyncPrivateTargets( - targets: readonly HistorySyncPrivateTarget[], + targets: readonly HistorySyncPrivateTarget[], ): HistorySyncPrivateTarget[] { - const result: HistorySyncPrivateTarget[] = []; - const userToUid = new Map(); - const uidToUser = new Map(); + const result: HistorySyncPrivateTarget[] = []; + const userToUid = new Map(); + const uidToUser = new Map(); - for (const target of targets) { - if (!Number.isSafeInteger(target.userId) || target.userId <= 0) { - throw new Error(`invalid private history sync target ${String(target.userId)}`); - } - if (typeof target.uid !== 'string' || target.uid.trim().length === 0) { - throw new Error(`private history sync target ${target.userId} has no uid`); + for (const target of targets) { + if (!Number.isSafeInteger(target.userId) || target.userId <= 0) { + throw new Error(`invalid private history sync target ${String(target.userId)}`); + } + + if (typeof target.uid !== 'string' || target.uid.trim().length === 0) { + throw new Error(`private history sync target ${target.userId} has no uid`); + } + + const uid = target.uid.trim(); + const knownUid = userToUid.get(target.userId); + + if (knownUid !== undefined) { + if (knownUid !== uid) { + throw new Error( + `private history sync target ${target.userId} maps to conflicting uids`, + ); + } + + continue; + } + + const knownUser = uidToUser.get(uid); + + if (knownUser !== undefined && knownUser !== target.userId) { + throw new Error(`private history sync uid ${uid} maps to conflicting users`); + } + + userToUid.set(target.userId, uid); + uidToUser.set(uid, target.userId); + result.push({ userId: target.userId, uid }); } - const uid = target.uid.trim(); - const knownUid = userToUid.get(target.userId); - if (knownUid !== undefined) { - if (knownUid !== uid) { - throw new Error( - `private history sync target ${target.userId} maps to conflicting uids`, - ); - } - continue; - } - - const knownUser = uidToUser.get(uid); - if (knownUser !== undefined && knownUser !== target.userId) { - throw new Error(`private history sync uid ${uid} maps to conflicting users`); - } - - userToUid.set(target.userId, uid); - uidToUser.set(uid, target.userId); - result.push({ userId: target.userId, uid }); - } - - return result; + return result; } function requireReadResponseItem( - items: readonly T[] | undefined, - index: number, - matches: (item: T) => boolean, - label: string, + items: readonly T[] | undefined, + index: number, + matches: (item: T) => boolean, + label: string, ): T { - const item = items?.find(matches) ?? items?.[index]; - if (!item) throw new Error(`${label} response item is missing`); + const item = items?.find(matches) ?? items?.[index]; - const resultCode = item.resultCode ?? 0; - if (resultCode !== 0) { - throw new Error(item.errorMessage || `${label} failed with result code ${resultCode}`); - } - if (!matches(item)) throw new Error(`${label} response identity does not match the request`); - return item; + if (!item) { + throw new Error(`${label} response item is missing`); + } + + const resultCode = item.resultCode ?? 0; + + if (resultCode !== 0) { + throw new Error(item.errorMessage || `${label} failed with result code ${resultCode}`); + } + + if (!matches(item)) { + throw new Error(`${label} response identity does not match the request`); + } + + return item; } function readUnsignedSequence(value: bigint | null | undefined, label: string): bigint { - // Proton represents an omitted protobuf scalar as null; protobuf semantics - // define that as the numeric default (zero), not a decode failure. - if (value == null) return 0n; - if (typeof value !== 'bigint' || value < 0n) throw new Error(`${label} is invalid`); - return value; + // Proton represents an omitted protobuf scalar as null; protobuf semantics + // define that as the numeric default (zero), not a decode failure. + if (value == null) { + return 0n; + } + + if (typeof value !== 'bigint' || value < 0n) { + throw new Error(`${label} is invalid`); + } + + return value; } function requirePositiveSequence(value: bigint | null | undefined, label: string): bigint { - const sequence = readUnsignedSequence(value, label); - if (sequence === 0n) throw new Error(`${label} is missing`); - return sequence; + const sequence = readUnsignedSequence(value, label); + + if (sequence === 0n) { + throw new Error(`${label} is missing`); + } + + return sequence; } function readSafeSequence(value: bigint | null | undefined, label: string): number { - const sequence = readUnsignedSequence(value, label); - if (sequence > BigInt(Number.MAX_SAFE_INTEGER)) { - throw new Error(`${label} exceeds the safe integer range`); - } - return Number(sequence); + const sequence = readUnsignedSequence(value, label); + + if (sequence > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error(`${label} exceeds the safe integer range`); + } + + return Number(sequence); } function validateHistorySyncRange(startSeq: number, endSeq: number, label: string): void { - if (!Number.isSafeInteger(startSeq) || startSeq <= 0) { - throw new Error(`${label} start sequence is invalid: ${String(startSeq)}`); - } - if (!Number.isSafeInteger(endSeq) || endSeq < startSeq || endSeq > HISTORY_MAX_SEQUENCE) { - throw new Error(`${label} end sequence is invalid: ${String(endSeq)}`); - } - const slots = endSeq - startSeq + 1; - if (slots > LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxMessagesPerSession) { - throw new Error( - `${label} may request at most ` - + `${LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxMessagesPerSession} sequence slots`, - ); - } + if (!Number.isSafeInteger(startSeq) || startSeq <= 0) { + throw new Error(`${label} start sequence is invalid: ${String(startSeq)}`); + } + + if (!Number.isSafeInteger(endSeq) || endSeq < startSeq || endSeq > HISTORY_MAX_SEQUENCE) { + throw new Error(`${label} end sequence is invalid: ${String(endSeq)}`); + } + + const slots = endSeq - startSeq + 1; + + if (slots > LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxMessagesPerSession) { + throw new Error( + `${label} may request at most ` + + `${LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxMessagesPerSession} sequence slots`, + ); + } } type GroupMessage = Extract; @@ -223,10 +253,10 @@ type FriendMessage = Extract; // ── Group-history fetch guards (the server frequency-limits / kicks abusive // pulls, so keep each request small, bound the loop, and space the sends). ── -const HISTORY_MAX_COUNT = 200; // hard cap on messages returned per call -const HISTORY_CHUNK_SEQ = 30; // sequence span per server request (small packet) -const HISTORY_MAX_REQUESTS = 12; // bound the walk-back loop -const HISTORY_MIN_GAP_MS = 300; // minimum spacing between SsoGetGroupMsg sends +const HISTORY_MAX_COUNT = 200; // hard cap on messages returned per call +const HISTORY_CHUNK_SEQ = 30; // sequence span per server request (small packet) +const HISTORY_MAX_REQUESTS = 12; // bound the walk-back loop +const HISTORY_MIN_GAP_MS = 300; // minimum spacing between SsoGetGroupMsg sends const HISTORY_MAX_SEQUENCE = 0xffff_ffff; // sequence fields are protobuf uint32 // Process-wide across every account and every history caller. Automatic login @@ -242,39 +272,53 @@ const historyRequestGate = new HistoryRequestGate(); * the newest `want` items oldest→newest. */ async function walkBackHistory( - endSeq: number, - count: number, - fetchWindow: (startSeq: number, endSeq: number) => Promise, - sequenceOf: (event: T) => number = (event) => event.msgSeq, + endSeq: number, + count: number, + fetchWindow: (startSeq: number, endSeq: number) => Promise, + sequenceOf: (event: T) => number = (event) => event.msgSeq, ): Promise { - if (!(endSeq > 0)) return []; - const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT); - - const collected = new Map(); // dedup by sequence - let curEnd = endSeq; - for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want && curEnd >= 1; i++) { - const start = Math.max(1, curEnd - HISTORY_CHUNK_SEQ + 1); - const batch = await historyRequestGate.run( - HISTORY_MIN_GAP_MS, - () => fetchWindow(start, curEnd), - ); - if (batch.length > 0) { - let minSeq = curEnd; - for (const ev of batch) { - const sequence = sequenceOf(ev); - if (!Number.isInteger(sequence) || sequence < start || sequence > curEnd) { - throw new Error(`history response sequence is outside requested range ${start}-${curEnd}`); - } - collected.set(sequence, ev); - if (sequence < minSeq) minSeq = sequence; - } - curEnd = minSeq - 1; // strictly below the oldest returned (covers short caps) - } else { - curEnd = start - 1; // empty window (recalled/absent seqs) — skip past it + if (!(endSeq > 0)) { + return []; } - } - const all = [...collected.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b)); - return all.slice(-want); // newest `want`, oldest→newest + + const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT); + + const collected = new Map(); // dedup by sequence + let curEnd = endSeq; + + for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want && curEnd >= 1; i++) { + const start = Math.max(1, curEnd - HISTORY_CHUNK_SEQ + 1); + const batch = await historyRequestGate.run(HISTORY_MIN_GAP_MS, () => + fetchWindow(start, curEnd), + ); + + if (batch.length > 0) { + let minSeq = curEnd; + + for (const ev of batch) { + const sequence = sequenceOf(ev); + + if (!Number.isInteger(sequence) || sequence < start || sequence > curEnd) { + throw new Error( + `history response sequence is outside requested range ${start}-${curEnd}`, + ); + } + + collected.set(sequence, ev); + + if (sequence < minSeq) { + minSeq = sequence; + } + } + + curEnd = minSeq - 1; // strictly below the oldest returned (covers short caps) + } else { + curEnd = start - 1; // empty window (recalled/absent seqs) — skip past it + } + } + + const all = [...collected.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b)); + return all.slice(-want); // newest `want`, oldest→newest } /** @@ -283,32 +327,43 @@ async function walkBackHistory( * the existing backward-history API shape. */ async function walkForwardHistory( - startSeq: number, - count: number, - fetchWindow: (startSeq: number, endSeq: number) => Promise, - sequenceOf: (event: T) => number = (event) => event.msgSeq, + startSeq: number, + count: number, + fetchWindow: (startSeq: number, endSeq: number) => Promise, + sequenceOf: (event: T) => number = (event) => event.msgSeq, ): Promise { - if (!(startSeq > 0) || startSeq > HISTORY_MAX_SEQUENCE) return []; - const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT); + if (!(startSeq > 0) || startSeq > HISTORY_MAX_SEQUENCE) { + return []; + } - const collected = new Map(); - const budget = { remaining: HISTORY_MAX_REQUESTS }; - let curStart = startSeq; - while (budget.remaining > 0 && collected.size < want && curStart <= HISTORY_MAX_SEQUENCE) { - const end = Math.min(HISTORY_MAX_SEQUENCE, curStart + HISTORY_CHUNK_SEQ - 1); - const window = await fetchForwardWindow(curStart, end, budget, fetchWindow, sequenceOf); - for (const event of window.messages) collected.set(sequenceOf(event), event); - if (!window.complete || end === HISTORY_MAX_SEQUENCE) break; - curStart = end + 1; - } + const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT); - const all = [...collected.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b)); - return all.slice(0, want); + const collected = new Map(); + const budget = { remaining: HISTORY_MAX_REQUESTS }; + let curStart = startSeq; + + while (budget.remaining > 0 && collected.size < want && curStart <= HISTORY_MAX_SEQUENCE) { + const end = Math.min(HISTORY_MAX_SEQUENCE, curStart + HISTORY_CHUNK_SEQ - 1); + const window = await fetchForwardWindow(curStart, end, budget, fetchWindow, sequenceOf); + + for (const event of window.messages) { + collected.set(sequenceOf(event), event); + } + + if (!window.complete || end === HISTORY_MAX_SEQUENCE) { + break; + } + + curStart = end + 1; + } + + const all = [...collected.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b)); + return all.slice(0, want); } interface ForwardWindowResult { - messages: T[]; - complete: boolean; + messages: T[]; + complete: boolean; } /** @@ -319,1089 +374,1301 @@ interface ForwardWindowResult { * later messages from being returned ahead of an unresolved prefix. */ async function fetchForwardWindow( - startSeq: number, - endSeq: number, - budget: { remaining: number }, - fetchWindow: (startSeq: number, endSeq: number) => Promise, - sequenceOf: (event: T) => number, + startSeq: number, + endSeq: number, + budget: { remaining: number }, + fetchWindow: (startSeq: number, endSeq: number) => Promise, + sequenceOf: (event: T) => number, ): Promise> { - if (budget.remaining <= 0) return { messages: [], complete: false }; - - budget.remaining--; - const batch = await historyRequestGate.run( - HISTORY_MIN_GAP_MS, - () => fetchWindow(startSeq, endSeq), - ); - if (batch.length === 0) return { messages: [], complete: true }; - - const messages = [...new Map(batch.map((event) => [sequenceOf(event), event])).values()] - .sort((a, b) => sequenceOf(a) - sequenceOf(b)); - for (const message of messages) { - const sequence = sequenceOf(message); - if (!Number.isInteger(sequence) || sequence < startSeq || sequence > endSeq) { - throw new Error(`history response sequence is outside requested range ${startSeq}-${endSeq}`); + if (budget.remaining <= 0) { + return { messages: [], complete: false }; } - } - const firstSequence = sequenceOf(messages[0]!); - if (firstSequence === startSeq) return { messages, complete: true }; - const prefix = await fetchForwardWindow( - startSeq, - firstSequence - 1, - budget, - fetchWindow, - sequenceOf, - ); - if (!prefix.complete) return prefix; - return { messages: [...prefix.messages, ...messages], complete: true }; + budget.remaining--; + const batch = await historyRequestGate.run(HISTORY_MIN_GAP_MS, () => + fetchWindow(startSeq, endSeq), + ); + + if (batch.length === 0) { + return { messages: [], complete: true }; + } + + const messages = [...new Map(batch.map((event) => [sequenceOf(event), event])).values()].sort( + (a, b) => sequenceOf(a) - sequenceOf(b), + ); + + for (const message of messages) { + const sequence = sequenceOf(message); + + if (!Number.isInteger(sequence) || sequence < startSeq || sequence > endSeq) { + throw new Error( + `history response sequence is outside requested range ${startSeq}-${endSeq}`, + ); + } + } + + const firstSequence = sequenceOf(messages[0]!); + + if (firstSequence === startSeq) { + return { messages, complete: true }; + } + + const prefix = await fetchForwardWindow( + startSeq, + firstSequence - 1, + budget, + fetchWindow, + sequenceOf, + ); + + if (!prefix.complete) { + return prefix; + } + + return { messages: [...prefix.messages, ...messages], complete: true }; } export class MessageApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - /** - * Send a message to a QQ group. - * - * Wraps `MessageSvc.PbSendMsg` with `routingHead.grp.groupCode`. - * Media elements (image / record / video) trigger highway uploads - * inside `buildSendElems` — see `element-builder.ts`. - * - * Returns a `SendMessageReceipt` carrying the assigned messageId, - * group sequence, and timestamps; callers cache this for later - * `recall` / reply lookups. - */ - async sendGroup(groupId: number, elements: MessageElement[]): Promise { - if (elements.length === 0) throw new Error('message is empty'); - - const protoElems = await buildSendElems(elements, { - bridge: this.ctx as unknown as Bridge, - groupId, - scene: 'group', - }); - const random = this.ctx.nextMessageRandom(); - - const request = protobuf_encode({ - routingHead: { - grp: { groupCode: BigInt(groupId) }, - }, - contentHead: { - type: 1, - }, - messageBody: { - richText: { - elems: protoElems, - }, - }, - clientSequence: 0, - random, - syncCookie: new Uint8Array(0), - via: 0, - dataStatist: 0, - multiSendSeq: 0, - }); - - const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`); - } - - const response = protobuf_decode(result.responseData); - if (!response) throw new Error('failed to decode SendMessageResponse'); - if (response.result != null && response.result !== 0) { - throw new Error(`send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`); - } - - const seq = response.groupSequence ?? 0; - if (seq <= 0) { - log.warn( - 'group message delivery unconfirmed: group=%d random=%d result=%s sequence=%s time=%s responseBytes=%d', - groupId, random, response.result, response.groupSequence, - response.timestamp1, result.responseData.length, - ); - throw new Error('group message delivery was not confirmed: QQ returned no message receipt; check the conversation before retrying'); - } - const messageId = (random & 0x7FFFFFFF) || seq; - const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); - return { messageId, sequence: seq, clientSequence: 0, random, timestamp }; - } - - /** - * Send a c2c (private) message. - * - * Resolves the recipient's UID only when the message carries media - * — text-only messages skip the lookup. Routes through `c2c.uin` - * (and optionally `c2c.uid` for the media case). - */ - async sendPrivate(userUin: number, elements: MessageElement[]): Promise { - const device = findDatalineDeviceByUin(userUin); - if (device) return this.sendDatalineText(device, elements); - if (elements.length === 0) throw new Error('message is empty'); - assertWindowShakeSendPolicy( - elements.filter((element) => element.type === 'poke').length, - elements.length, - 'direct-private', - ); - - let userUid = ''; - const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video'); - if (hasMedia) { - userUid = await this.ctx.resolveUserUid(userUin); - } - - const protoElems = await buildSendElems(elements, { - bridge: this.ctx as unknown as Bridge, - userUid, - scene: 'direct-private', - }); - const random = this.ctx.nextMessageRandom(); - const clientSeq = this.ctx.nextClientSequence(); - - const request = protobuf_encode({ - routingHead: { - c2c: { - uin: userUin, - ...(userUid ? { uid: userUid } : {}), - }, - }, - contentHead: { - type: 1, - subType: 0, - c2cCmd: 11, - }, - messageBody: { - richText: { - elems: protoElems, - }, - }, - clientSequence: clientSeq, - random, - syncCookie: new Uint8Array(0), - via: 0, - dataStatist: 0, - ctrl: { - msgFlag: Math.floor(Date.now() / 1000), - }, - multiSendSeq: 0, - }); - - const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`); - } - - const response = protobuf_decode(result.responseData); - if (!response) throw new Error('failed to decode SendMessageResponse'); - if (response.result != null && response.result !== 0) { - throw new Error(`send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`); - } - - const seq = response.privateSequence ?? 0; - const messageId = (random & 0x7FFFFFFF) || seq; - const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); - return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; - } - - /** - * Send text to an official my-device contact. These peers are not - * ordinary friends — they use the same trans0x211 send path as c2c - * files, with a device-chat body instead of FileExtra. - */ - private async sendDatalineText( - device: DatalineDeviceContact, - elements: MessageElement[], - ): Promise { - const text = datalineTextFromElements(elements); - const selfUin = parseInt(this.ctx.identity.uin, 10); - if (!Number.isSafeInteger(selfUin) || selfUin <= 0) { - throw new Error('self uin unavailable'); - } - - const random = this.ctx.nextMessageRandom(); - const clientSeq = this.ctx.nextClientSequence(); - const nowSec = Math.floor(Date.now() / 1000); - const request = protobuf_encode({ - routingHead: { - trans0x211: { - toUin: BigInt(selfUin), - ccCmd: 7, - uid: device.uid, - }, - }, - contentHead: { - type: 1, - subType: 0, - }, - messageBody: { - msgContent: encodeDatalineText({ - selfUin, - dstTerType: device.terType, - text, - }), - }, - clientSequence: clientSeq, - random, - syncCookie: new Uint8Array(0), - via: 0, - dataStatist: 0, - ctrl: { msgFlag: nowSec }, - multiSendSeq: 0, - }); - - const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(`send device message failed: ${result.errorMessage || 'no response'}`); - } - const response = protobuf_decode(result.responseData); - if (!response) throw new Error('failed to decode SendMessageResponse'); - if (response.result != null && response.result !== 0) { - throw new Error(`send device message rejected: result=${response.result} err=${response.errMsg ?? ''}`); - } - const seq = response.privateSequence ?? 0; - const messageId = (random & 0x7FFFFFFF) || seq; - const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); - return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; - } - - /** - * Reply into an existing group temp session (临时会话). Wire primitive only — - * it does NOT gate; the caller verifies the session before calling. Routes - * through `grpTmp` (RoutingHead field 3) with { groupUin, toUid } and a normal - * c2c content head. - */ - async sendGroupTempMessage( - userUin: number, - groupUin: number, - elements: MessageElement[], - ): Promise { - if (elements.length === 0) throw new Error('message is empty'); - assertWindowShakeSendPolicy( - elements.filter((element) => element.type === 'poke').length, - elements.length, - 'group-temp', - ); - - const userUid = await this.ctx.resolveUserUid(userUin); - const protoElems = await buildSendElems(elements, { - bridge: this.ctx as unknown as Bridge, - userUid, - scene: 'group-temp', - tempGroupId: groupUin, - }); - const random = this.ctx.nextMessageRandom(); - const clientSeq = this.ctx.nextClientSequence(); - - const request = protobuf_encode({ - routingHead: { - grpTmp: { groupUin: BigInt(groupUin), toUid: userUid }, - }, - contentHead: { type: 1, subType: 0, c2cCmd: 11 }, - messageBody: { richText: { elems: protoElems } }, - clientSequence: clientSeq, - random, - syncCookie: new Uint8Array(0), - via: 0, - dataStatist: 0, - ctrl: { msgFlag: Math.floor(Date.now() / 1000) }, - multiSendSeq: 0, - }); - - const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(`send temp message failed: ${result.errorMessage || 'no response'}`); - } - const response = protobuf_decode(result.responseData); - if (!response) throw new Error('failed to decode SendMessageResponse'); - if (response.result != null && response.result !== 0) { - throw new Error(`send temp message rejected: result=${response.result} err=${response.errMsg ?? ''}`); - } - const seq = response.privateSequence ?? 0; - const messageId = (random & 0x7FFFFFFF) || seq; - const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); - return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; - } - - /** - * Send a c2c file as a chat message. - * - * The wire shape isn't the same as a regular c2c message — the c2c - * file path uses three slots that differ from a normal text/image - * send (verified against `dev/Lagrange.Core/.../MessagePacker.cs: - * BuildPacketBase` + `FileEntity.PackMessageContent`): - * - * 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of - * `routingHead.c2c { uin, uid }`. The server rejects c2c file - * messages routed through the regular c2c slot. - * 2. `messageBody.msgContent` carries the serialised - * `FileExtra { file: NotOnlineFile }` bytes. NOT - * `richText.notOnlineFile` — the receiver doesn't read that - * slot for file metadata. - * 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The - * previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT - * server doesn't recognise. - * - * NotOnlineFile carries three required-on-send fields the receiver - * itself ignores but the server's intake validator checks: - * - `subcmd: 1` — c2c file send command code - * - `dangerEvel: 0` — virus-scan severity, always 0 client-side - * - `expireTime` — 7 days from now (Lagrange convention) - * - * `FileExtra.file` alone makes the file downloadable (verified on a live - * account). We ALSO attach `FileExtra.field6` — extra server-issued download - * routing from a best-effort 0xE37_800 finalize that mirrors NapCat and may - * help some receiver clients. The finalize is non-fatal: if it fails we send - * without field6 rather than failing the send (issue #157). - */ - async sendC2cFile( - userUin: number, - userUid: string, - info: { fileId: string; fileName: string; fileSize: number; fileMd5: Uint8Array; fileHash?: string }, - ): Promise { - const random = this.ctx.nextMessageRandom(); - const clientSeq = this.ctx.nextClientSequence(); - - // Resolve our own uid — needed both for the 0xE37_800 finalize and the - // `field6` download-routing the receiver reads. - const selfUid = await resolveSelfUid(this.ctx); - - // The file is already downloadable from the `NotOnlineFile` reference - // alone — verified on a live account: a plain c2c file send (no field6) - // downloads fine. `field6` is EXTRA server-issued download routing (from - // the 0xE37_800 finalize) that mirrors NapCat and may help some receiver - // clients. So fetch it BEST-EFFORT: if the finalize fails, send without - // field6 rather than failing the whole send. (issue #157 — the finalize - // was originally fatal, which could regress a send that would otherwise - // succeed.) - const fileHash = info.fileHash ?? ''; - let meta: Awaited> | null = null; - try { - meta = await FinalizeOfflineFile.invoke(this.ctx, { - senderUid: selfUid, - receiverUid: userUid, - fileUuid: info.fileId, - fileHash, - }); - } catch (err) { - log.warn('c2c file finalize (0xE37_800) failed, sending without field6: %s', - err instanceof Error ? err.message : String(err)); - } - - const nowSec = Math.floor(Date.now() / 1000); - const sevenDaysSec = 7 * 24 * 60 * 60; - const fileExtra: FileExtra = { - file: { - fileType: 0, - fileUuid: info.fileId, - fileMd5: info.fileMd5, - fileName: info.fileName, - fileSize: BigInt(info.fileSize), - subcmd: 1, - dangerEvel: 0, - expireTime: nowSec + sevenDaysSec, - fileHash, - }, - }; - if (meta) { - fileExtra.field6 = { - field2: { - field1: meta.field110, - fileUuid: info.fileId, - fileName: info.fileName, - field6: meta.field3, - field7: meta.field101, - field8: meta.field100, - timestamp1: meta.timestamp1, - fileHash, - selfUid, - destUid: userUid, - }, - }; - } - const fileExtraBytes = protobuf_encode(fileExtra); - - const request = protobuf_encode({ - routingHead: { - trans0x211: { ccCmd: 4, uid: userUid }, - }, - contentHead: { - type: 1, - subType: 0, - }, - messageBody: { - msgContent: fileExtraBytes, - }, - clientSequence: clientSeq, - random, - syncCookie: new Uint8Array(0), - via: 0, - dataStatist: 0, - ctrl: { msgFlag: nowSec }, - multiSendSeq: 0, - }); - - // `userUin` is part of the public contract (the OneBot layer - // threads it through for symmetry with `sendPrivate`) but the - // wire shape only needs the uid. Silence the unused-parameter - // lint without changing the signature. - void userUin; - - const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`); - } - const response = protobuf_decode(result.responseData); - if (!response) throw new Error('failed to decode SendMessageResponse'); - if (response.result != null && response.result !== 0) { - throw new Error(`send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`); - } - const seq = response.privateSequence ?? 0; - const messageId = (random & 0x7FFFFFFF) || seq; - const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); - return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; - } - - /** - * Recall (revoke) a group message by sequence number. Server-side - * the message ages out after the standard 2-minute window unless - * the user is an admin/owner. - */ - async recallGroup(groupId: number, sequence: number): Promise { - const request = protobuf_encode({ - type: 1, - groupUin: groupId, - info: { sequence, random: 0, field3: 0 }, - settings: { field1: 0 }, - }); - const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', request); - if (!result.success) throw new Error(result.errorMessage || 'recall group message failed'); - } - - /** - * Recall a c2c (private) message. Needs more positional info than - * the group variant because c2c messages are identified by the - * `(clientSequence, msgSequence, random, timestamp)` tuple rather - * than a single group-side sequence. - */ - async recallPrivate( - userUin: number, - clientSeq: number, - msgSeq: number, - random: number, - timestamp: number, - ): Promise { - const targetUid = await this.ctx.resolveUserUid(userUin); - const request = protobuf_encode({ - type: 1, - targetUid, - info: { - clientSequence: clientSeq, - random, - messageId: (0x01000000n << 32n) | BigInt(random >>> 0), - timestamp, - field5: 0, - messageSequence: msgSeq, - }, - settings: { field1: false, field2: false }, - field6: false, - }); - const result = await this.ctx.sendRawPacket('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', request); - if (!result.success) throw new Error(result.errorMessage || 'recall private message failed'); - } - - /** Mark the entire group conversation read, matching QQ NT's setMsgRead(peer). */ - async markGroupRead(groupId: number): Promise { - await this.markAllRead([groupId], []); - } - - /** Mark the entire private conversation read, matching QQ NT's setMsgRead(peer). */ - async markPrivateRead(userId: number): Promise { - await this.markAllRead([], [userId]); - } - - /** - * Mark every supplied conversation read through SsoReadedReport. - * - * Message-head sequences are not valid C2C read sequences. The first packet - * therefore reports zero for every conversation and reads the server's - * current read/latest pair from the response without moving the marker - * backwards. A second packet advances only conversations that are behind. - * QQ NT caps each packet at 100 C2C plus 100 group entries and waits for the - * response before sending the next page; mirror that strictly here. - */ - async markAllRead(groupIds: readonly number[], privateUserIds: readonly number[]): Promise { - const groups = uniqueSessionIds(groupIds, 'group'); - const privateUsers = uniqueSessionIds(privateUserIds, 'private'); - const c2cTargets: C2CReadTarget[] = []; - - // Keep UID resolution sequential. A cache miss may itself use the network, - // so Promise.all here would reintroduce the burst this method is designed - // to avoid. - for (const userId of privateUsers) { - const uid = await this.ctx.resolveUserUid(userId); - if (!uid) throw new Error(`failed to resolve uid for private read target ${userId}`); - c2cTargets.push({ userId, uid }); - } - - const totalBatches = Math.max( - Math.ceil(groups.length / READ_REPORT_BATCH_SIZE), - Math.ceil(c2cTargets.length / READ_REPORT_BATCH_SIZE), - ); - if (totalBatches === 0) return; - - log.debug( - 'mark-read start: groups=%d c2c=%d batches=%d', - groups.length, - c2cTargets.length, - totalBatches, - ); - - for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { - const start = batchIndex * READ_REPORT_BATCH_SIZE; - await this.markReadBatch( - groups.slice(start, start + READ_REPORT_BATCH_SIZE), - c2cTargets.slice(start, start + READ_REPORT_BATCH_SIZE), - batchIndex + 1, - totalBatches, - ); - } - - log.debug('mark-read complete: groups=%d c2c=%d', groups.length, c2cTargets.length); - } - - private async sendReadReport( - request: SsoReadedReportReq, - label: string, - minimumGapMs = HISTORY_MIN_GAP_MS, - signal?: AbortSignal, - ): Promise { - log.debug( - '%s send: groups=%d c2c=%d', - label, - request.groupList?.length ?? 0, - request.c2cList?.length ?? 0, - ); - const payload = protobuf_encode(request); - const result = await historyRequestGate.run( - minimumGapMs, - () => this.ctx.sendRawPacket(READ_REPORT_CMD, payload), - signal, - ); - const response = decodeReadReportResponse(result, label); - log.debug( - '%s response: groups=%d c2c=%d', - label, - response.groupList?.length ?? 0, - response.c2cList?.length ?? 0, - ); - return response; - } - - /** - * Read the server's current read/latest cursors without advancing any read - * marker. The zero-valued report fields are omitted on the wire by protobuf, - * matching QQ NT's read-only probe. Automatic login sync is deliberately - * limited to one probe with at most 100 group and 100 private targets. - */ - async probeHistorySyncState( - groupIds: readonly number[], - privateTargets: readonly HistorySyncPrivateTarget[], - signal?: AbortSignal, - ): Promise { - const groups = uniqueSessionIds(groupIds, 'group'); - const privateUsers = uniqueHistorySyncPrivateTargets(privateTargets); - const maxTargets = LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxTargetsPerKind; - - if (groups.length > maxTargets) { - throw new Error(`history sync probe accepts at most ${maxTargets} group targets`); - } - if (privateUsers.length > maxTargets) { - throw new Error(`history sync probe accepts at most ${maxTargets} private targets`); - } - if (groups.length === 0 && privateUsers.length === 0) { - return { groups: [], privateUsers: [] }; - } - - const label = 'login history sync probe'; - const response = await this.sendReadReport({ - groupList: groups.map(groupId => ({ groupUin: BigInt(groupId), lastReadSeq: 0n })), - c2cList: privateUsers.map(target => ({ - uid: target.uid, - lastReadTime: 0n, - lastReadSeq: 0n, - })), - }, label, LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs, signal); - - const groupState = groups.map((groupId, index): GroupHistorySyncState => { - const item = this.groupReadResponse(response, groupId, index, label); - const readSeq = readSafeSequence( - item.readSeq, - `${label} group ${groupId} read sequence`, - ); - const latestSeq = readSafeSequence( - item.latestSeq, - `${label} group ${groupId} latest sequence`, - ); - if (latestSeq < readSeq) { - throw new Error( - `${label} group ${groupId} latest sequence ${latestSeq} ` - + `is before read sequence ${readSeq}`, - ); - } - return { groupId, readSeq, latestSeq }; - }); - - const privateState = privateUsers.map((target, index): PrivateHistorySyncState => { - const item = this.c2cReadResponse(response, target, index, label); - const targetUin = readSafeSequence( - item.targetUin, - `${label} private user ${target.userId} target uin`, - ); - if (targetUin !== 0 && targetUin !== target.userId) { - throw new Error( - `${label} private user ${target.userId} response target ${targetUin} does not match`, - ); - } - const readSeq = readSafeSequence( - item.readSeq, - `${label} private user ${target.userId} read sequence`, - ); - const latestSeq = readSafeSequence( - item.latestSeq, - `${label} private user ${target.userId} latest sequence`, - ); - if (latestSeq < readSeq) { - throw new Error( - `${label} private user ${target.userId} latest sequence ${latestSeq} ` - + `is before read sequence ${readSeq}`, - ); - } - return { - ...target, - readSeq, - latestSeq, - lastMsgTime: readSafeSequence( - item.lastMsgTime, - `${label} private user ${target.userId} last message time`, - ), - }; - }); - - return { groups: groupState, privateUsers: privateState }; - } - - private groupReadResponse( - response: SsoReadedReportResp, - groupId: number, - index: number, - label: string, - ): GroupReadedReportResponseItem { - const groupUin = BigInt(groupId); - return requireReadResponseItem( - response.groupList, - index, - item => item.groupUin === groupUin, - `${label} group ${groupId}`, - ); - } - - private c2cReadResponse( - response: SsoReadedReportResp, - target: C2CReadTarget, - index: number, - label: string, - ): C2CReadedReportResponseItem { - return requireReadResponseItem( - response.c2cList, - index, - item => item.uid === target.uid, - `${label} private user ${target.userId}`, - ); - } - - private async markReadBatch( - groupIds: readonly number[], - c2cTargets: readonly C2CReadTarget[], - batchIndex: number, - totalBatches: number, - ): Promise { - const batchLabel = `mark-read batch ${batchIndex}/${totalBatches}`; - const probe = await this.sendReadReport({ - groupList: groupIds.map(groupId => ({ groupUin: BigInt(groupId), lastReadSeq: 0n })), - c2cList: c2cTargets.map(target => ({ uid: target.uid, lastReadTime: 0n, lastReadSeq: 0n })), - }, `${batchLabel} probe`); - - const groupList: NonNullable = []; - for (let i = 0; i < groupIds.length; i++) { - const groupId = groupIds[i]!; - const item = this.groupReadResponse(probe, groupId, i, `${batchLabel} probe`); - const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} group ${groupId} read sequence`); - const latestSeq = readUnsignedSequence(item.latestSeq, `${batchLabel} group ${groupId} latest sequence`); - if (latestSeq < readSeq) { - throw new Error(`${batchLabel} group ${groupId} latest sequence ${latestSeq} is before read sequence ${readSeq}`); - } - if (latestSeq > readSeq) groupList.push({ groupUin: BigInt(groupId), lastReadSeq: latestSeq }); - } - - const c2cList: NonNullable = []; - const c2cConfirmTargets: C2CReadTarget[] = []; - for (let i = 0; i < c2cTargets.length; i++) { - const target = c2cTargets[i]!; - const item = this.c2cReadResponse(probe, target, i, `${batchLabel} probe`); - const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} private user ${target.userId} read sequence`); - const latestSeq = readUnsignedSequence(item.latestSeq, `${batchLabel} private user ${target.userId} latest sequence`); - if (latestSeq < readSeq) { - throw new Error( - `${batchLabel} private user ${target.userId} latest sequence ${latestSeq} is before read sequence ${readSeq}`, - ); - } - if (latestSeq > readSeq) { - const lastMsgTime = requirePositiveSequence( - item.lastMsgTime, - `${batchLabel} private user ${target.userId} last message time`, - ); - c2cList.push({ uid: target.uid, lastReadTime: lastMsgTime, lastReadSeq: latestSeq }); - c2cConfirmTargets.push(target); - } - } - - if (groupList.length === 0 && c2cList.length === 0) { - log.debug('%s already current', batchLabel); - return; - } - - const confirm = await this.sendReadReport({ groupList, c2cList }, `${batchLabel} confirm`); - for (let i = 0; i < groupList.length; i++) { - const requested = groupList[i]!; - const groupId = Number(requested.groupUin); - const item = this.groupReadResponse(confirm, groupId, i, `${batchLabel} confirm`); - const readSeq = readUnsignedSequence(item.readSeq, `${batchLabel} group ${groupId} confirmed read sequence`); - if (readSeq < (requested.lastReadSeq ?? 0n)) { - throw new Error( - `${batchLabel} group ${groupId} confirmed sequence ${readSeq} before requested ${requested.lastReadSeq}`, - ); - } - } - for (let i = 0; i < c2cList.length; i++) { - const requested = c2cList[i]!; - const target = c2cConfirmTargets[i]!; - const item = this.c2cReadResponse(confirm, target, i, `${batchLabel} confirm`); - const readSeq = readUnsignedSequence( - item.readSeq, - `${batchLabel} private user ${target.userId} confirmed read sequence`, - ); - if (readSeq < (requested.lastReadSeq ?? 0n)) { - throw new Error( - `${batchLabel} private user ${target.userId} confirmed sequence ${readSeq} before requested ${requested.lastReadSeq}`, - ); - } - } - } - - /** - * Fetch real group history from the server (`SsoGetGroupMsg`), including the - * anchor and walking backward or forward in small windows. Rate-limited and - * capped so a hammering client cannot flood the server. Returns decoded - * `group_message` events oldest→newest regardless of query direction. - */ - async getGroupHistory( - groupUin: number, - anchorSeq: number, - count: number, - selfUin = 0, - reverseOrder = true, - ): Promise { - if (!(groupUin > 0)) return []; - const fetchWindow = (start: number, end: number) => - fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, start, end); - return reverseOrder - ? walkBackHistory(anchorSeq, count, fetchWindow) - : walkForwardHistory(anchorSeq, count, fetchWindow); - } - - /** - * Fetch exactly one bounded group-history window for automatic login sync. - * Unlike the public history action this method never paginates or retries. - */ - async getGroupHistorySyncPage( - groupUin: number, - startSeq: number, - endSeq: number, - selfUin = 0, - signal?: AbortSignal, - ): Promise { - if (!Number.isSafeInteger(groupUin) || groupUin <= 0) { - throw new Error(`group history sync target is invalid: ${String(groupUin)}`); - } - validateHistorySyncRange(startSeq, endSeq, `group ${groupUin} history sync`); - - const messages = await historyRequestGate.run( - LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs, - () => fetchGroupMessageRange( - this.ctx, - this.ctx.identity, - selfUin, - groupUin, - startSeq, - endSeq, - ), - signal, - ); - return this.validateHistorySyncPage( - messages, - message => message.msgSeq, - startSeq, - endSeq, - `group ${groupUin} history sync`, - ); - } - - /** - * Fetch real private history from the server (`SsoGetC2cMsg`), including the - * anchor in the requested direction. It shares the group variant's throttle - * and data-volume guards. Returns decoded events oldest→newest. - */ - async getC2cHistory( - friendUid: string, - anchorSeq: number, - count: number, - selfUin = 0, - reverseOrder = true, - ): Promise { - if (!friendUid) return []; - const fetchWindow = (start: number, end: number) => - fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end); - const serverSequence = (message: FriendMessage) => message.ntMsgSeq ?? 0; - return reverseOrder - ? walkBackHistory(anchorSeq, count, fetchWindow, serverSequence) - : walkForwardHistory(anchorSeq, count, fetchWindow, serverSequence); - } - - /** - * Fetch exactly one bounded private-history sequence window for automatic - * login sync. Sender-local message-head sequences are not valid here. - */ - async getC2cHistorySyncPage( - friendUid: string, - startSeq: number, - endSeq: number, - selfUin = 0, - signal?: AbortSignal, - ): Promise { - if (!friendUid.trim()) throw new Error('private history sync uid is required'); - validateHistorySyncRange(startSeq, endSeq, `private ${friendUid} history sync`); - - const messages = await historyRequestGate.run( - LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs, - () => fetchC2cMessageRange( - this.ctx, - this.ctx.identity, - selfUin, - friendUid, - startSeq, - endSeq, - ), - signal, - ); - return this.validateHistorySyncPage( - messages, - message => message.ntMsgSeq ?? 0, - startSeq, - endSeq, - `private ${friendUid} history sync`, - ); - } - - /** - * Fetch one latest private roaming page for a session without a local - * authoritative sequence. No cursor loop or retry is permitted. - */ - async getC2cLatestHistorySyncPage( - friendUid: string, - count: number, - selfUin = 0, - beforeTime = Math.floor(Date.now() / 1000) + 1, - signal?: AbortSignal, - ): Promise { - if (!friendUid.trim()) throw new Error('private history sync uid is required'); - const maxMessages = LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxMessagesPerSession; - if (!Number.isSafeInteger(count) || count < 1 || count > maxMessages) { - throw new Error(`private history sync may request at most ${maxMessages} messages`); - } - - const page = await historyRequestGate.run( - LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs, - () => fetchC2cRoamMessagePage( - this.ctx, - this.ctx.identity, - selfUin, - friendUid, - beforeTime, - count, - 0, - ), - signal, - ); - const messages = [...new Map(page.messages.map((message) => { - const sequence = message.ntMsgSeq ?? 0; - if (!Number.isSafeInteger(sequence) || sequence <= 0) { - throw new Error( - `private ${friendUid} history sync returned invalid NT sequence ${String(sequence)}`, - ); - } - return [sequence, message] as const; - })).values()] - .sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time); - if (messages.length > count) { - throw new Error( - `private ${friendUid} history sync returned ${messages.length} messages ` - + `for a ${count}-message request`, - ); - } - return messages; - } - - /** - * Fetch the latest private history page without relying on a locally cached - * sequence. C2C field-5 sequences are sender-local, so only SsoGetRoamMsg's - * timestamp cursor can safely bootstrap an unanchored conversation. - */ - async getC2cLatestHistory( - friendUid: string, - count: number, - selfUin = 0, - beforeTime = Math.floor(Date.now() / 1000) + 1, - ): Promise { - if (!friendUid) return []; - const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT); - const collected = new Map(); - let cursor = { time: beforeTime, random: 0 }; - const seenCursors = new Set([`${cursor.time}:${cursor.random}`]); - let reachedEnd = false; - - for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want; i++) { - const page = await historyRequestGate.run( - HISTORY_MIN_GAP_MS, - () => fetchC2cRoamMessagePage( - this.ctx, - this.ctx.identity, - selfUin, - friendUid, - cursor.time, - want - collected.size, - cursor.random, - ), - ); - for (const message of page.messages) { - const sequence = message.ntMsgSeq ?? 0; - if (!Number.isSafeInteger(sequence) || sequence <= 0) { - throw new Error(`private roam history returned invalid NT sequence ${String(sequence)}`); + /** + * Send a message to a QQ group. + * + * Wraps `MessageSvc.PbSendMsg` with `routingHead.grp.groupCode`. + * Media elements (image / record / video) trigger highway uploads + * inside `buildSendElems` — see `element-builder.ts`. + * + * Returns a `SendMessageReceipt` carrying the assigned messageId, + * group sequence, and timestamps; callers cache this for later + * `recall` / reply lookups. + */ + async sendGroup(groupId: number, elements: MessageElement[]): Promise { + if (elements.length === 0) { + throw new Error('message is empty'); } - collected.set(sequence, message); - } - if (collected.size >= want) break; - if (page.cursor.time === 0 && page.cursor.random === 0) { - reachedEnd = true; - break; - } - const nextCursorKey = `${page.cursor.time}:${page.cursor.random}`; - if (seenCursors.has(nextCursorKey)) { - if (page.messages.length === 0) { - reachedEnd = true; - break; + const protoElems = await buildSendElems(elements, { + bridge: this.ctx as unknown as Bridge, + groupId, + scene: 'group', + }); + const random = this.ctx.nextMessageRandom(); + + const request = protobuf_encode({ + routingHead: { + grp: { groupCode: BigInt(groupId) }, + }, + contentHead: { + type: 1, + }, + messageBody: { + richText: { + elems: protoElems, + }, + }, + clientSequence: 0, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + multiSendSeq: 0, + }); + + const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send group message failed: ${result.errorMessage || 'no response'}`); } - throw new Error( - `private roam history cursor did not advance from ${cursor.time}/${cursor.random}`, + + const response = protobuf_decode(result.responseData); + + if (!response) { + throw new Error('failed to decode SendMessageResponse'); + } + + if (response.result != null && response.result !== 0) { + throw new Error( + `send group message rejected: result=${response.result} err=${response.errMsg ?? ''}`, + ); + } + + const seq = response.groupSequence ?? 0; + + if (seq <= 0) { + log.warn( + 'group message delivery unconfirmed: group=%d random=%d result=%s sequence=%s time=%s responseBytes=%d', + groupId, + random, + response.result, + response.groupSequence, + response.timestamp1, + result.responseData.length, + ); + throw new Error( + 'group message delivery was not confirmed: QQ returned no message receipt; check the conversation before retrying', + ); + } + + const messageId = random & 0x7fffffff || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + return { messageId, sequence: seq, clientSequence: 0, random, timestamp }; + } + + /** + * Send a c2c (private) message. + * + * Resolves the recipient's UID only when the message carries media + * — text-only messages skip the lookup. Routes through `c2c.uin` + * (and optionally `c2c.uid` for the media case). + */ + async sendPrivate(userUin: number, elements: MessageElement[]): Promise { + const device = findDatalineDeviceByUin(userUin); + + if (device) { + return this.sendDatalineText(device, elements); + } + + if (elements.length === 0) { + throw new Error('message is empty'); + } + + assertWindowShakeSendPolicy( + elements.filter((element) => element.type === 'poke').length, + elements.length, + 'direct-private', ); - } - seenCursors.add(nextCursorKey); - cursor = page.cursor; - } - if (collected.size < want && !reachedEnd) { - throw new Error( - `private roam history request budget exhausted after ${HISTORY_MAX_REQUESTS} pages ` - + `(requested=${want}, collected=${collected.size})`, - ); - } - - return [...collected.values()] - .sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time) - .slice(-want); - } - - /** - * Fetch a single group message by its exact sequence — `SsoGetGroupMsg` over a - * 1-wide `[seq, seq]` range, through the shared history throttle gate. Used to - * back-fill a replied-to message the local store never saw. Returns the - * matching `group_message`, or null if absent / on error. - */ - async getGroupMessageBySeq(groupUin: number, seq: number, selfUin = 0): Promise { - if (!(groupUin > 0) || !(seq > 0)) return null; - try { - const batch = await historyRequestGate.run( - HISTORY_MIN_GAP_MS, - () => fetchGroupMessageRange( - this.ctx, - this.ctx.identity, - selfUin, - groupUin, - seq, - seq, - ), - ); - return batch.find((m) => m.msgSeq === seq) ?? null; - } catch { - return null; - } - } - - /** - * Fetch a single c2c message by its exact conversation-wide NT sequence — - * `SsoGetC2cMsg` over a 1-wide `[seq, seq]` range, through the same throttle - * gate. Sender-local reply/recall sequences must not be passed here. - */ - async getC2cMessageBySeq(friendUid: string, seq: number, selfUin = 0): Promise { - if (!friendUid || !(seq > 0)) return null; - try { - const batch = await historyRequestGate.run( - HISTORY_MIN_GAP_MS, - () => fetchC2cMessageRange( - this.ctx, - this.ctx.identity, - selfUin, - friendUid, - seq, - seq, - ), - ); - return batch.find((m) => m.ntMsgSeq === seq) ?? null; - } catch { - return null; - } - } - - private validateHistorySyncPage( - messages: readonly T[], - sequenceOf: (message: T) => number, - startSeq: number, - endSeq: number, - label: string, - ): T[] { - const bySequence = new Map(); - for (const message of messages) { - const sequence = sequenceOf(message); - if ( - !Number.isSafeInteger(sequence) - || sequence < startSeq - || sequence > endSeq - ) { - throw new Error( - `${label} returned sequence ${String(sequence)} outside ` - + `requested range ${startSeq}-${endSeq}`, + let userUid = ''; + const hasMedia = elements.some( + (e) => e.type === 'image' || e.type === 'record' || e.type === 'video', ); - } - bySequence.set(sequence, message); + + if (hasMedia) { + userUid = await this.ctx.resolveUserUid(userUin); + } + + const protoElems = await buildSendElems(elements, { + bridge: this.ctx as unknown as Bridge, + userUid, + scene: 'direct-private', + }); + const random = this.ctx.nextMessageRandom(); + const clientSeq = this.ctx.nextClientSequence(); + + const request = protobuf_encode({ + routingHead: { + c2c: { + uin: userUin, + ...(userUid ? { uid: userUid } : {}), + }, + }, + contentHead: { + type: 1, + subType: 0, + c2cCmd: 11, + }, + messageBody: { + richText: { + elems: protoElems, + }, + }, + clientSequence: clientSeq, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + ctrl: { + msgFlag: Math.floor(Date.now() / 1000), + }, + multiSendSeq: 0, + }); + + const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send private message failed: ${result.errorMessage || 'no response'}`); + } + + const response = protobuf_decode(result.responseData); + + if (!response) { + throw new Error('failed to decode SendMessageResponse'); + } + + if (response.result != null && response.result !== 0) { + throw new Error( + `send private message rejected: result=${response.result} err=${response.errMsg ?? ''}`, + ); + } + + const seq = response.privateSequence ?? 0; + const messageId = random & 0x7fffffff || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; + } + + /** + * Send text to an official my-device contact. These peers are not + * ordinary friends — they use the same trans0x211 send path as c2c + * files, with a device-chat body instead of FileExtra. + */ + private async sendDatalineText( + device: DatalineDeviceContact, + elements: MessageElement[], + ): Promise { + const text = datalineTextFromElements(elements); + const selfUin = parseInt(this.ctx.identity.uin, 10); + + if (!Number.isSafeInteger(selfUin) || selfUin <= 0) { + throw new Error('self uin unavailable'); + } + + const random = this.ctx.nextMessageRandom(); + const clientSeq = this.ctx.nextClientSequence(); + const nowSec = Math.floor(Date.now() / 1000); + const request = protobuf_encode({ + routingHead: { + trans0x211: { + toUin: BigInt(selfUin), + ccCmd: 7, + uid: device.uid, + }, + }, + contentHead: { + type: 1, + subType: 0, + }, + messageBody: { + msgContent: encodeDatalineText({ + selfUin, + dstTerType: device.terType, + text, + }), + }, + clientSequence: clientSeq, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + ctrl: { msgFlag: nowSec }, + multiSendSeq: 0, + }); + + const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send device message failed: ${result.errorMessage || 'no response'}`); + } + + const response = protobuf_decode(result.responseData); + + if (!response) { + throw new Error('failed to decode SendMessageResponse'); + } + + if (response.result != null && response.result !== 0) { + throw new Error( + `send device message rejected: result=${response.result} err=${response.errMsg ?? ''}`, + ); + } + + const seq = response.privateSequence ?? 0; + const messageId = random & 0x7fffffff || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; + } + + /** + * Reply into an existing group temp session (临时会话). Wire primitive only — + * it does NOT gate; the caller verifies the session before calling. Routes + * through `grpTmp` (RoutingHead field 3) with { groupUin, toUid } and a normal + * c2c content head. + */ + async sendGroupTempMessage( + userUin: number, + groupUin: number, + elements: MessageElement[], + ): Promise { + if (elements.length === 0) { + throw new Error('message is empty'); + } + + assertWindowShakeSendPolicy( + elements.filter((element) => element.type === 'poke').length, + elements.length, + 'group-temp', + ); + + const userUid = await this.ctx.resolveUserUid(userUin); + const protoElems = await buildSendElems(elements, { + bridge: this.ctx as unknown as Bridge, + userUid, + scene: 'group-temp', + tempGroupId: groupUin, + }); + const random = this.ctx.nextMessageRandom(); + const clientSeq = this.ctx.nextClientSequence(); + + const request = protobuf_encode({ + routingHead: { + grpTmp: { groupUin: BigInt(groupUin), toUid: userUid }, + }, + contentHead: { type: 1, subType: 0, c2cCmd: 11 }, + messageBody: { richText: { elems: protoElems } }, + clientSequence: clientSeq, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + ctrl: { msgFlag: Math.floor(Date.now() / 1000) }, + multiSendSeq: 0, + }); + + const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send temp message failed: ${result.errorMessage || 'no response'}`); + } + + const response = protobuf_decode(result.responseData); + + if (!response) { + throw new Error('failed to decode SendMessageResponse'); + } + + if (response.result != null && response.result !== 0) { + throw new Error( + `send temp message rejected: result=${response.result} err=${response.errMsg ?? ''}`, + ); + } + + const seq = response.privateSequence ?? 0; + const messageId = random & 0x7fffffff || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; + } + + /** + * Send a c2c file as a chat message. + * + * The wire shape isn't the same as a regular c2c message — the c2c + * file path uses three slots that differ from a normal text/image + * send (verified against `dev/Lagrange.Core/.../MessagePacker.cs: + * BuildPacketBase` + `FileEntity.PackMessageContent`): + * + * 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of + * `routingHead.c2c { uin, uid }`. The server rejects c2c file + * messages routed through the regular c2c slot. + * 2. `messageBody.msgContent` carries the serialised + * `FileExtra { file: NotOnlineFile }` bytes. NOT + * `richText.notOnlineFile` — the receiver doesn't read that + * slot for file metadata. + * 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The + * previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT + * server doesn't recognise. + * + * NotOnlineFile carries three required-on-send fields the receiver + * itself ignores but the server's intake validator checks: + * - `subcmd: 1` — c2c file send command code + * - `dangerEvel: 0` — virus-scan severity, always 0 client-side + * - `expireTime` — 7 days from now (Lagrange convention) + * + * `FileExtra.file` alone makes the file downloadable (verified on a live + * account). We ALSO attach `FileExtra.field6` — extra server-issued download + * routing from a best-effort 0xE37_800 finalize that mirrors NapCat and may + * help some receiver clients. The finalize is non-fatal: if it fails we send + * without field6 rather than failing the send (issue #157). + */ + async sendC2cFile( + userUin: number, + userUid: string, + info: { + fileId: string; + fileName: string; + fileSize: number; + fileMd5: Uint8Array; + fileHash?: string; + }, + ): Promise { + const random = this.ctx.nextMessageRandom(); + const clientSeq = this.ctx.nextClientSequence(); + + // Resolve our own uid — needed both for the 0xE37_800 finalize and the + // `field6` download-routing the receiver reads. + const selfUid = await resolveSelfUid(this.ctx); + + // The file is already downloadable from the `NotOnlineFile` reference + // alone — verified on a live account: a plain c2c file send (no field6) + // downloads fine. `field6` is EXTRA server-issued download routing (from + // the 0xE37_800 finalize) that mirrors NapCat and may help some receiver + // clients. So fetch it BEST-EFFORT: if the finalize fails, send without + // field6 rather than failing the whole send. (issue #157 — the finalize + // was originally fatal, which could regress a send that would otherwise + // succeed.) + const fileHash = info.fileHash ?? ''; + let meta: Awaited> | null = null; + + try { + meta = await FinalizeOfflineFile.invoke(this.ctx, { + senderUid: selfUid, + receiverUid: userUid, + fileUuid: info.fileId, + fileHash, + }); + } catch (err) { + log.warn( + 'c2c file finalize (0xE37_800) failed, sending without field6: %s', + err instanceof Error ? err.message : String(err), + ); + } + + const nowSec = Math.floor(Date.now() / 1000); + const sevenDaysSec = 7 * 24 * 60 * 60; + const fileExtra: FileExtra = { + file: { + fileType: 0, + fileUuid: info.fileId, + fileMd5: info.fileMd5, + fileName: info.fileName, + fileSize: BigInt(info.fileSize), + subcmd: 1, + dangerEvel: 0, + expireTime: nowSec + sevenDaysSec, + fileHash, + }, + }; + + if (meta) { + fileExtra.field6 = { + field2: { + field1: meta.field110, + fileUuid: info.fileId, + fileName: info.fileName, + field6: meta.field3, + field7: meta.field101, + field8: meta.field100, + timestamp1: meta.timestamp1, + fileHash, + selfUid, + destUid: userUid, + }, + }; + } + + const fileExtraBytes = protobuf_encode(fileExtra); + + const request = protobuf_encode({ + routingHead: { + trans0x211: { ccCmd: 4, uid: userUid }, + }, + contentHead: { + type: 1, + subType: 0, + }, + messageBody: { + msgContent: fileExtraBytes, + }, + clientSequence: clientSeq, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + ctrl: { msgFlag: nowSec }, + multiSendSeq: 0, + }); + + // `userUin` is part of the public contract (the OneBot layer + // threads it through for symmetry with `sendPrivate`) but the + // wire shape only needs the uid. Silence the unused-parameter + // lint without changing the signature. + void userUin; + + const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); + + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error( + `send c2c file message failed: ${result.errorMessage || 'no response'}`, + ); + } + + const response = protobuf_decode(result.responseData); + + if (!response) { + throw new Error('failed to decode SendMessageResponse'); + } + + if (response.result != null && response.result !== 0) { + throw new Error( + `send c2c file message rejected: result=${response.result} err=${response.errMsg ?? ''}`, + ); + } + + const seq = response.privateSequence ?? 0; + const messageId = random & 0x7fffffff || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; + } + + /** + * Recall (revoke) a group message by sequence number. Server-side + * the message ages out after the standard 2-minute window unless + * the user is an admin/owner. + */ + async recallGroup(groupId: number, sequence: number): Promise { + const request = protobuf_encode({ + type: 1, + groupUin: groupId, + info: { sequence, random: 0, field3: 0 }, + settings: { field1: 0 }, + }); + const result = await this.ctx.sendRawPacket( + 'trpc.msg.msg_svc.MsgService.SsoGroupRecallMsg', + request, + ); + + if (!result.success) { + throw new Error(result.errorMessage || 'recall group message failed'); + } + } + + /** + * Recall a c2c (private) message. Needs more positional info than + * the group variant because c2c messages are identified by the + * `(clientSequence, msgSequence, random, timestamp)` tuple rather + * than a single group-side sequence. + */ + async recallPrivate( + userUin: number, + clientSeq: number, + msgSeq: number, + random: number, + timestamp: number, + ): Promise { + const targetUid = await this.ctx.resolveUserUid(userUin); + const request = protobuf_encode({ + type: 1, + targetUid, + info: { + clientSequence: clientSeq, + random, + messageId: (0x01000000n << 32n) | BigInt(random >>> 0), + timestamp, + field5: 0, + messageSequence: msgSeq, + }, + settings: { field1: false, field2: false }, + field6: false, + }); + const result = await this.ctx.sendRawPacket( + 'trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg', + request, + ); + + if (!result.success) { + throw new Error(result.errorMessage || 'recall private message failed'); + } + } + + /** Mark the entire group conversation read, matching QQ NT's setMsgRead(peer). */ + async markGroupRead(groupId: number): Promise { + await this.markAllRead([groupId], []); + } + + /** Mark the entire private conversation read, matching QQ NT's setMsgRead(peer). */ + async markPrivateRead(userId: number): Promise { + await this.markAllRead([], [userId]); + } + + /** + * Mark every supplied conversation read through SsoReadedReport. + * + * Message-head sequences are not valid C2C read sequences. The first packet + * therefore reports zero for every conversation and reads the server's + * current read/latest pair from the response without moving the marker + * backwards. A second packet advances only conversations that are behind. + * QQ NT caps each packet at 100 C2C plus 100 group entries and waits for the + * response before sending the next page; mirror that strictly here. + */ + async markAllRead( + groupIds: readonly number[], + privateUserIds: readonly number[], + ): Promise { + const groups = uniqueSessionIds(groupIds, 'group'); + const privateUsers = uniqueSessionIds(privateUserIds, 'private'); + const c2cTargets: C2CReadTarget[] = []; + + // Keep UID resolution sequential. A cache miss may itself use the network, + // so Promise.all here would reintroduce the burst this method is designed + // to avoid. + for (const userId of privateUsers) { + const uid = await this.ctx.resolveUserUid(userId); + + if (!uid) { + throw new Error(`failed to resolve uid for private read target ${userId}`); + } + + c2cTargets.push({ userId, uid }); + } + + const totalBatches = Math.max( + Math.ceil(groups.length / READ_REPORT_BATCH_SIZE), + Math.ceil(c2cTargets.length / READ_REPORT_BATCH_SIZE), + ); + + if (totalBatches === 0) { + return; + } + + log.debug( + 'mark-read start: groups=%d c2c=%d batches=%d', + groups.length, + c2cTargets.length, + totalBatches, + ); + + for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) { + const start = batchIndex * READ_REPORT_BATCH_SIZE; + await this.markReadBatch( + groups.slice(start, start + READ_REPORT_BATCH_SIZE), + c2cTargets.slice(start, start + READ_REPORT_BATCH_SIZE), + batchIndex + 1, + totalBatches, + ); + } + + log.debug('mark-read complete: groups=%d c2c=%d', groups.length, c2cTargets.length); + } + + private async sendReadReport( + request: SsoReadedReportReq, + label: string, + minimumGapMs = HISTORY_MIN_GAP_MS, + signal?: AbortSignal, + ): Promise { + log.debug( + '%s send: groups=%d c2c=%d', + label, + request.groupList?.length ?? 0, + request.c2cList?.length ?? 0, + ); + const payload = protobuf_encode(request); + const result = await historyRequestGate.run( + minimumGapMs, + () => this.ctx.sendRawPacket(READ_REPORT_CMD, payload), + signal, + ); + const response = decodeReadReportResponse(result, label); + log.debug( + '%s response: groups=%d c2c=%d', + label, + response.groupList?.length ?? 0, + response.c2cList?.length ?? 0, + ); + return response; + } + + /** + * Read the server's current read/latest cursors without advancing any read + * marker. The zero-valued report fields are omitted on the wire by protobuf, + * matching QQ NT's read-only probe. Automatic login sync is deliberately + * limited to one probe with at most 100 group and 100 private targets. + */ + async probeHistorySyncState( + groupIds: readonly number[], + privateTargets: readonly HistorySyncPrivateTarget[], + signal?: AbortSignal, + ): Promise { + const groups = uniqueSessionIds(groupIds, 'group'); + const privateUsers = uniqueHistorySyncPrivateTargets(privateTargets); + const maxTargets = LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxTargetsPerKind; + + if (groups.length > maxTargets) { + throw new Error(`history sync probe accepts at most ${maxTargets} group targets`); + } + + if (privateUsers.length > maxTargets) { + throw new Error(`history sync probe accepts at most ${maxTargets} private targets`); + } + + if (groups.length === 0 && privateUsers.length === 0) { + return { groups: [], privateUsers: [] }; + } + + const label = 'login history sync probe'; + const response = await this.sendReadReport( + { + groupList: groups.map((groupId) => ({ + groupUin: BigInt(groupId), + lastReadSeq: 0n, + })), + c2cList: privateUsers.map((target) => ({ + uid: target.uid, + lastReadTime: 0n, + lastReadSeq: 0n, + })), + }, + label, + LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs, + signal, + ); + + const groupState = groups.map((groupId, index): GroupHistorySyncState => { + const item = this.groupReadResponse(response, groupId, index, label); + const readSeq = readSafeSequence( + item.readSeq, + `${label} group ${groupId} read sequence`, + ); + const latestSeq = readSafeSequence( + item.latestSeq, + `${label} group ${groupId} latest sequence`, + ); + + if (latestSeq < readSeq) { + throw new Error( + `${label} group ${groupId} latest sequence ${latestSeq} ` + + `is before read sequence ${readSeq}`, + ); + } + + return { groupId, readSeq, latestSeq }; + }); + + const privateState = privateUsers.map((target, index): PrivateHistorySyncState => { + const item = this.c2cReadResponse(response, target, index, label); + const targetUin = readSafeSequence( + item.targetUin, + `${label} private user ${target.userId} target uin`, + ); + + if (targetUin !== 0 && targetUin !== target.userId) { + throw new Error( + `${label} private user ${target.userId} response target ${targetUin} does not match`, + ); + } + + const readSeq = readSafeSequence( + item.readSeq, + `${label} private user ${target.userId} read sequence`, + ); + const latestSeq = readSafeSequence( + item.latestSeq, + `${label} private user ${target.userId} latest sequence`, + ); + + if (latestSeq < readSeq) { + throw new Error( + `${label} private user ${target.userId} latest sequence ${latestSeq} ` + + `is before read sequence ${readSeq}`, + ); + } + + return { + ...target, + readSeq, + latestSeq, + lastMsgTime: readSafeSequence( + item.lastMsgTime, + `${label} private user ${target.userId} last message time`, + ), + }; + }); + + return { groups: groupState, privateUsers: privateState }; + } + + private groupReadResponse( + response: SsoReadedReportResp, + groupId: number, + index: number, + label: string, + ): GroupReadedReportResponseItem { + const groupUin = BigInt(groupId); + return requireReadResponseItem( + response.groupList, + index, + (item) => item.groupUin === groupUin, + `${label} group ${groupId}`, + ); + } + + private c2cReadResponse( + response: SsoReadedReportResp, + target: C2CReadTarget, + index: number, + label: string, + ): C2CReadedReportResponseItem { + return requireReadResponseItem( + response.c2cList, + index, + (item) => item.uid === target.uid, + `${label} private user ${target.userId}`, + ); + } + + private async markReadBatch( + groupIds: readonly number[], + c2cTargets: readonly C2CReadTarget[], + batchIndex: number, + totalBatches: number, + ): Promise { + const batchLabel = `mark-read batch ${batchIndex}/${totalBatches}`; + const probe = await this.sendReadReport( + { + groupList: groupIds.map((groupId) => ({ + groupUin: BigInt(groupId), + lastReadSeq: 0n, + })), + c2cList: c2cTargets.map((target) => ({ + uid: target.uid, + lastReadTime: 0n, + lastReadSeq: 0n, + })), + }, + `${batchLabel} probe`, + ); + + const groupList: NonNullable = []; + + for (let i = 0; i < groupIds.length; i++) { + const groupId = groupIds[i]!; + const item = this.groupReadResponse(probe, groupId, i, `${batchLabel} probe`); + const readSeq = readUnsignedSequence( + item.readSeq, + `${batchLabel} group ${groupId} read sequence`, + ); + const latestSeq = readUnsignedSequence( + item.latestSeq, + `${batchLabel} group ${groupId} latest sequence`, + ); + + if (latestSeq < readSeq) { + throw new Error( + `${batchLabel} group ${groupId} latest sequence ${latestSeq} is before read sequence ${readSeq}`, + ); + } + + if (latestSeq > readSeq) { + groupList.push({ groupUin: BigInt(groupId), lastReadSeq: latestSeq }); + } + } + + const c2cList: NonNullable = []; + const c2cConfirmTargets: C2CReadTarget[] = []; + + for (let i = 0; i < c2cTargets.length; i++) { + const target = c2cTargets[i]!; + const item = this.c2cReadResponse(probe, target, i, `${batchLabel} probe`); + const readSeq = readUnsignedSequence( + item.readSeq, + `${batchLabel} private user ${target.userId} read sequence`, + ); + const latestSeq = readUnsignedSequence( + item.latestSeq, + `${batchLabel} private user ${target.userId} latest sequence`, + ); + + if (latestSeq < readSeq) { + throw new Error( + `${batchLabel} private user ${target.userId} latest sequence ${latestSeq} is before read sequence ${readSeq}`, + ); + } + + if (latestSeq > readSeq) { + const lastMsgTime = requirePositiveSequence( + item.lastMsgTime, + `${batchLabel} private user ${target.userId} last message time`, + ); + c2cList.push({ + uid: target.uid, + lastReadTime: lastMsgTime, + lastReadSeq: latestSeq, + }); + c2cConfirmTargets.push(target); + } + } + + if (groupList.length === 0 && c2cList.length === 0) { + log.debug('%s already current', batchLabel); + return; + } + + const confirm = await this.sendReadReport({ groupList, c2cList }, `${batchLabel} confirm`); + + for (let i = 0; i < groupList.length; i++) { + const requested = groupList[i]!; + const groupId = Number(requested.groupUin); + const item = this.groupReadResponse(confirm, groupId, i, `${batchLabel} confirm`); + const readSeq = readUnsignedSequence( + item.readSeq, + `${batchLabel} group ${groupId} confirmed read sequence`, + ); + + if (readSeq < (requested.lastReadSeq ?? 0n)) { + throw new Error( + `${batchLabel} group ${groupId} confirmed sequence ${readSeq} before requested ${requested.lastReadSeq}`, + ); + } + } + + for (let i = 0; i < c2cList.length; i++) { + const requested = c2cList[i]!; + const target = c2cConfirmTargets[i]!; + const item = this.c2cReadResponse(confirm, target, i, `${batchLabel} confirm`); + const readSeq = readUnsignedSequence( + item.readSeq, + `${batchLabel} private user ${target.userId} confirmed read sequence`, + ); + + if (readSeq < (requested.lastReadSeq ?? 0n)) { + throw new Error( + `${batchLabel} private user ${target.userId} confirmed sequence ${readSeq} before requested ${requested.lastReadSeq}`, + ); + } + } + } + + /** + * Fetch real group history from the server (`SsoGetGroupMsg`), including the + * anchor and walking backward or forward in small windows. Rate-limited and + * capped so a hammering client cannot flood the server. Returns decoded + * `group_message` events oldest→newest regardless of query direction. + */ + async getGroupHistory( + groupUin: number, + anchorSeq: number, + count: number, + selfUin = 0, + reverseOrder = true, + ): Promise { + if (!(groupUin > 0)) { + return []; + } + + const fetchWindow = (start: number, end: number) => + fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, start, end); + return reverseOrder + ? walkBackHistory(anchorSeq, count, fetchWindow) + : walkForwardHistory(anchorSeq, count, fetchWindow); + } + + /** + * Fetch exactly one bounded group-history window for automatic login sync. + * Unlike the public history action this method never paginates or retries. + */ + async getGroupHistorySyncPage( + groupUin: number, + startSeq: number, + endSeq: number, + selfUin = 0, + signal?: AbortSignal, + ): Promise { + if (!Number.isSafeInteger(groupUin) || groupUin <= 0) { + throw new Error(`group history sync target is invalid: ${String(groupUin)}`); + } + + validateHistorySyncRange(startSeq, endSeq, `group ${groupUin} history sync`); + + const messages = await historyRequestGate.run( + LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs, + () => + fetchGroupMessageRange( + this.ctx, + this.ctx.identity, + selfUin, + groupUin, + startSeq, + endSeq, + ), + signal, + ); + return this.validateHistorySyncPage( + messages, + (message) => message.msgSeq, + startSeq, + endSeq, + `group ${groupUin} history sync`, + ); + } + + /** + * Fetch real private history from the server (`SsoGetC2cMsg`), including the + * anchor in the requested direction. It shares the group variant's throttle + * and data-volume guards. Returns decoded events oldest→newest. + */ + async getC2cHistory( + friendUid: string, + anchorSeq: number, + count: number, + selfUin = 0, + reverseOrder = true, + ): Promise { + if (!friendUid) { + return []; + } + + const fetchWindow = (start: number, end: number) => + fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end); + const serverSequence = (message: FriendMessage) => message.ntMsgSeq ?? 0; + return reverseOrder + ? walkBackHistory(anchorSeq, count, fetchWindow, serverSequence) + : walkForwardHistory(anchorSeq, count, fetchWindow, serverSequence); + } + + /** + * Fetch exactly one bounded private-history sequence window for automatic + * login sync. Sender-local message-head sequences are not valid here. + */ + async getC2cHistorySyncPage( + friendUid: string, + startSeq: number, + endSeq: number, + selfUin = 0, + signal?: AbortSignal, + ): Promise { + if (!friendUid.trim()) { + throw new Error('private history sync uid is required'); + } + + validateHistorySyncRange(startSeq, endSeq, `private ${friendUid} history sync`); + + const messages = await historyRequestGate.run( + LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs, + () => + fetchC2cMessageRange( + this.ctx, + this.ctx.identity, + selfUin, + friendUid, + startSeq, + endSeq, + ), + signal, + ); + return this.validateHistorySyncPage( + messages, + (message) => message.ntMsgSeq ?? 0, + startSeq, + endSeq, + `private ${friendUid} history sync`, + ); + } + + /** + * Fetch one latest private roaming page for a session without a local + * authoritative sequence. No cursor loop or retry is permitted. + */ + async getC2cLatestHistorySyncPage( + friendUid: string, + count: number, + selfUin = 0, + beforeTime = Math.floor(Date.now() / 1000) + 1, + signal?: AbortSignal, + ): Promise { + if (!friendUid.trim()) { + throw new Error('private history sync uid is required'); + } + + const maxMessages = LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.maxMessagesPerSession; + + if (!Number.isSafeInteger(count) || count < 1 || count > maxMessages) { + throw new Error(`private history sync may request at most ${maxMessages} messages`); + } + + const page = await historyRequestGate.run( + LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS.minimumGapMs, + () => + fetchC2cRoamMessagePage( + this.ctx, + this.ctx.identity, + selfUin, + friendUid, + beforeTime, + count, + 0, + ), + signal, + ); + const messages = [ + ...new Map( + page.messages.map((message) => { + const sequence = message.ntMsgSeq ?? 0; + + if (!Number.isSafeInteger(sequence) || sequence <= 0) { + throw new Error( + `private ${friendUid} history sync returned invalid NT sequence ${String(sequence)}`, + ); + } + + return [sequence, message] as const; + }), + ).values(), + ].sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time); + + if (messages.length > count) { + throw new Error( + `private ${friendUid} history sync returned ${messages.length} messages ` + + `for a ${count}-message request`, + ); + } + + return messages; + } + + /** + * Fetch the latest private history page without relying on a locally cached + * sequence. C2C field-5 sequences are sender-local, so only SsoGetRoamMsg's + * timestamp cursor can safely bootstrap an unanchored conversation. + */ + async getC2cLatestHistory( + friendUid: string, + count: number, + selfUin = 0, + beforeTime = Math.floor(Date.now() / 1000) + 1, + ): Promise { + if (!friendUid) { + return []; + } + + const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT); + const collected = new Map(); + let cursor = { time: beforeTime, random: 0 }; + const seenCursors = new Set([`${cursor.time}:${cursor.random}`]); + let reachedEnd = false; + + for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want; i++) { + const page = await historyRequestGate.run(HISTORY_MIN_GAP_MS, () => + fetchC2cRoamMessagePage( + this.ctx, + this.ctx.identity, + selfUin, + friendUid, + cursor.time, + want - collected.size, + cursor.random, + ), + ); + + for (const message of page.messages) { + const sequence = message.ntMsgSeq ?? 0; + + if (!Number.isSafeInteger(sequence) || sequence <= 0) { + throw new Error( + `private roam history returned invalid NT sequence ${String(sequence)}`, + ); + } + + collected.set(sequence, message); + } + + if (collected.size >= want) { + break; + } + + if (page.cursor.time === 0 && page.cursor.random === 0) { + reachedEnd = true; + break; + } + + const nextCursorKey = `${page.cursor.time}:${page.cursor.random}`; + + if (seenCursors.has(nextCursorKey)) { + if (page.messages.length === 0) { + reachedEnd = true; + break; + } + + throw new Error( + `private roam history cursor did not advance from ${cursor.time}/${cursor.random}`, + ); + } + + seenCursors.add(nextCursorKey); + cursor = page.cursor; + } + + if (collected.size < want && !reachedEnd) { + throw new Error( + `private roam history request budget exhausted after ${HISTORY_MAX_REQUESTS} pages ` + + `(requested=${want}, collected=${collected.size})`, + ); + } + + return [...collected.values()] + .sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time) + .slice(-want); + } + + /** + * Fetch a single group message by its exact sequence — `SsoGetGroupMsg` over a + * 1-wide `[seq, seq]` range, through the shared history throttle gate. Used to + * back-fill a replied-to message the local store never saw. Returns the + * matching `group_message`, or null if absent / on error. + */ + async getGroupMessageBySeq( + groupUin: number, + seq: number, + selfUin = 0, + ): Promise { + if (!(groupUin > 0) || !(seq > 0)) { + return null; + } + + try { + const batch = await historyRequestGate.run(HISTORY_MIN_GAP_MS, () => + fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, seq, seq), + ); + return batch.find((m) => m.msgSeq === seq) ?? null; + } catch { + return null; + } + } + + /** + * Fetch a single c2c message by its exact conversation-wide NT sequence — + * `SsoGetC2cMsg` over a 1-wide `[seq, seq]` range, through the same throttle + * gate. Sender-local reply/recall sequences must not be passed here. + */ + async getC2cMessageBySeq( + friendUid: string, + seq: number, + selfUin = 0, + ): Promise { + if (!friendUid || !(seq > 0)) { + return null; + } + + try { + const batch = await historyRequestGate.run(HISTORY_MIN_GAP_MS, () => + fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, seq, seq), + ); + return batch.find((m) => m.ntMsgSeq === seq) ?? null; + } catch { + return null; + } + } + + private validateHistorySyncPage( + messages: readonly T[], + sequenceOf: (message: T) => number, + startSeq: number, + endSeq: number, + label: string, + ): T[] { + const bySequence = new Map(); + + for (const message of messages) { + const sequence = sequenceOf(message); + + if (!Number.isSafeInteger(sequence) || sequence < startSeq || sequence > endSeq) { + throw new Error( + `${label} returned sequence ${String(sequence)} outside ` + + `requested range ${startSeq}-${endSeq}`, + ); + } + + bySequence.set(sequence, message); + } + + return [...bySequence.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b)); } - return [...bySequence.values()].sort((a, b) => sequenceOf(a) - sequenceOf(b)); - } } diff --git a/packages/core/src/bridge/apis/misc.ts b/packages/core/src/bridge/apis/misc.ts index ce126781..12b13164 100644 --- a/packages/core/src/bridge/apis/misc.ts +++ b/packages/core/src/bridge/apis/misc.ts @@ -1,8 +1,5 @@ import type { JsonObject, JsonValue } from '@snowluma/common/json'; -import type { - MiniAppShareReq, - MiniAppShareResp, -} from '@snowluma/proto-defs/oidb-actions/base'; +import type { MiniAppShareReq, MiniAppShareResp } from '@snowluma/proto-defs/oidb-actions/base'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { BridgeContext } from '../bridge-context'; // Migrated OIDB cmds — facade methods are one-line forwarders. @@ -13,83 +10,108 @@ import { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decr import { ImageOcr, type OcrResult } from '@snowluma/protocol/oidb-services/misc/image-ocr'; export class MiscApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - translateEn2Zh(words: string[]): Promise { - 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'; - - if (type === 'weibo') { - appid = '1109224783'; - iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg'; - } else if (type !== 'bili') { - throw new Error(`unsupported type: ${type}, only support bili and weibo`); + translateEn2Zh(words: string[]): Promise { + return TranslateEnToZh.invoke(this.ctx, { words }); } - const request = protobuf_encode({ - sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A', - body: { appid, title, desc, picUrl, jumpUrl, iconUrl }, - }); - - const result = await this.ctx.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request); - - if (!result.success || !result.responseData) { - throw new Error(result.errorMessage || 'get mini app ark failed'); + ocrImage(imageUrl: string): Promise { + return ImageOcr.invoke(this.ctx, { imageUrl }); } - const decoded = protobuf_decode(result.responseData); - const jsonStr = decoded?.body?.jsonStr; + 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'; - if (!jsonStr) { - throw new Error('mini app share json empty'); + if (type === 'weibo') { + appid = '1109224783'; + iconUrl = + 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg'; + } else if (type !== 'bili') { + throw new Error(`unsupported type: ${type}, only support bili and weibo`); + } + + const request = protobuf_encode({ + sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A', + body: { appid, title, desc, picUrl, jumpUrl, iconUrl }, + }); + + const result = await this.ctx.sendRawPacket( + 'LightAppSvc.mini_app_share.AdaptShareInfo', + request, + ); + + if (!result.success || !result.responseData) { + throw new Error(result.errorMessage || 'get mini app ark failed'); + } + + const decoded = protobuf_decode(result.responseData); + const jsonStr = decoded?.body?.jsonStr; + + if (!jsonStr) { + throw new Error('mini app share json empty'); + } + + const parsed = JSON.parse(jsonStr) as Record< + string, + JsonObject | string | number | boolean | null + >; + + return { + data: { + ver: parsed.ver, + prompt: parsed.prompt, + config: parsed.config, + app: parsed.appName, + view: parsed.appView, + meta: parsed.metaData, + miniappShareOrigin: 3, + miniappOpenRefer: '10002', + }, + }; } - const parsed = JSON.parse(jsonStr) as Record; - - return { - data: { - ver: parsed.ver, - prompt: parsed.prompt, - config: parsed.config, - app: parsed.appName, - view: parsed.appView, - meta: parsed.metaData, - miniappShareOrigin: 3, - miniappOpenRefer: '10002', - }, - }; - } - - clickInlineKeyboardButton( - groupId: number, - botAppid: number, - buttonId: string, - callbackData: string, - msgSeq: number, - ): Promise { - return ClickInlineKeyboardButton.invoke(this.ctx, { groupId, botAppid, buttonId, callbackData, msgSeq }); - } - - sendGroupSign(groupId: number): Promise { - return SendGroupSign.invoke(this.ctx, { groupId }); - } - - async getDecryptKey(dbSalt: string): Promise { - const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt }); - if (!result.success) { - throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`); + clickInlineKeyboardButton( + groupId: number, + botAppid: number, + buttonId: string, + callbackData: string, + msgSeq: number, + ): Promise { + return ClickInlineKeyboardButton.invoke(this.ctx, { + groupId, + botAppid, + buttonId, + callbackData, + msgSeq, + }); } - if (!result.dbKey) { - throw new Error('Decrypt key is empty'); + + sendGroupSign(groupId: number): Promise { + return SendGroupSign.invoke(this.ctx, { groupId }); + } + + async getDecryptKey(dbSalt: string): Promise { + const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt }); + + if (!result.success) { + throw new Error( + result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`, + ); + } + + if (!result.dbKey) { + throw new Error('Decrypt key is empty'); + } + + return result.dbKey; } - return result.dbKey; - } } diff --git a/packages/core/src/bridge/apis/profile.ts b/packages/core/src/bridge/apis/profile.ts index 16971ec7..d7ee764a 100644 --- a/packages/core/src/bridge/apis/profile.ts +++ b/packages/core/src/bridge/apis/profile.ts @@ -1,7 +1,7 @@ import type { - GroupAvatarExtra, - SetStatusReq, - SetStatusResp, + GroupAvatarExtra, + SetStatusReq, + SetStatusResp, } from '@snowluma/proto-defs/oidb-actions/base'; import { AddCustomFace } from '@snowluma/protocol/oidb-services/custom-face/add-custom-face'; import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/delete-custom-face'; @@ -10,10 +10,17 @@ import { FetchCustomFaceList } from '@snowluma/protocol/oidb-services/custom-fac import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face'; import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face'; import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face'; -import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway'; +import { + BufferChunkSource, + fetchHighwaySession, + uploadHighwayHttp, +} from '@snowluma/protocol/highway'; import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils'; import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like'; -import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list'; +import { + GetUnidirectionalFriendList, + type UnidirectionalFriendEntry, +} from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list'; import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status'; import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile'; import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick'; @@ -21,226 +28,273 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { Bridge } from '../bridge'; import type { BridgeContext } from '../bridge-context'; -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } +function asBridge(ctx: BridgeContext): Bridge { + return ctx as unknown as Bridge; +} export interface CustomFaceDetail { - emojiId: string; - url: string; - md5: string; - desc: string; + emojiId: string; + url: string; + md5: string; + desc: string; } export class ProfileApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - // ─────────────── status / profile setters ─────────────── + // ─────────────── status / profile setters ─────────────── - async setOnlineStatus(status: number, extStatus = 0, batteryStatus = 100): Promise { - await this.dispatchSetStatus({ status, extStatus, batteryStatus }); - } - - /** - * DIY (custom) online status. napcat fixes status=10 / extStatus=2000 - * — the values QQ associates with "I have a custom status string" — - * and threads the faceId / wording / faceType through the customExt - * sub-message of the same SetStatus wire call. - */ - async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise { - await this.dispatchSetStatus({ - status: 10, - extStatus: 2000, - batteryStatus: 0, - customExt: { faceId, text: wording, faceType }, - }); - } - - private async dispatchSetStatus(value: { - status: number; - extStatus: number; - batteryStatus: number; - customExt?: { faceId: number; text: string; faceType: number }; - }): Promise { - const request = protobuf_encode(value); - const result = await this.ctx.sendRawPacket( - 'trpc.qq_new_tech.status_svc.StatusService.SetStatus', - request, - ); - - if (!result.success) { - throw new Error(result.errorMessage || 'set online status failed (network/timeout)'); + async setOnlineStatus(status: number, extStatus = 0, batteryStatus = 100): Promise { + await this.dispatchSetStatus({ status, extStatus, batteryStatus }); } - if (result.responseData && result.responseData.length > 0) { - const resp = protobuf_decode(result.responseData); - if (!resp) { - throw new Error(result.errorMessage || 'set online status failed (network/timeout)'); - } - const message = resp.errMsg ?? ''; - if (message !== '' && message !== 'set status success') { - throw new Error(message); - } + /** + * DIY (custom) online status. napcat fixes status=10 / extStatus=2000 + * — the values QQ associates with "I have a custom status string" — + * and threads the faceId / wording / faceType through the customExt + * sub-message of the same SetStatus wire call. + */ + async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise { + await this.dispatchSetStatus({ + status: 10, + extStatus: 2000, + batteryStatus: 0, + customExt: { faceId, text: wording, faceType }, + }); } - } - setProfile(nickname?: string, personalNote?: string, sex?: number): Promise { - return SetProfile.invoke(this.ctx, { nickname, personalNote, sex }); - } + private async dispatchSetStatus(value: { + status: number; + extStatus: number; + batteryStatus: number; + customExt?: { faceId: number; text: string; faceType: number }; + }): Promise { + const request = protobuf_encode(value); + const result = await this.ctx.sendRawPacket( + 'trpc.qq_new_tech.status_svc.StatusService.SetStatus', + request, + ); - setSelfLongNick(longNick: string): Promise { - return SetSelfLongNick.invoke(this.ctx, { longNick }); - } + if (!result.success) { + throw new Error(result.errorMessage || 'set online status failed (network/timeout)'); + } - setInputStatus(userId: number, eventType: number): Promise { - return SetInputStatus.invoke(this.ctx, { userId, eventType }); - } + if (result.responseData && result.responseData.length > 0) { + const resp = protobuf_decode(result.responseData); - async setAvatar(source: string): Promise { - const bridge = asBridge(this.ctx); - const loaded = await loadBinarySource(source, 'avatar'); - if (!loaded.bytes.length) throw new Error('avatar file is empty'); + if (!resp) { + throw new Error( + result.errorMessage || 'set online status failed (network/timeout)', + ); + } - const hashes = computeHashes(loaded.bytes); - const session = await fetchHighwaySession(bridge); - await uploadHighwayHttp(bridge, session, 90, new BufferChunkSource(loaded.bytes), hashes.md5, new Uint8Array(0)); - } + const message = resp.errMsg ?? ''; - /** - * Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar: - * - same highway HTTP upload as personal avatar - * - cmdId 3000 (instead of 90) - * - GroupAvatarExtra proto carried as the `extend` blob, with the - * four protocol-prescribed constants (type=101, field5=3, field6=1, - * field3.field1=1) and the target groupUin. - * - * Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar. - */ - async setGroupAvatar(groupId: number, source: string): Promise { - const bridge = asBridge(this.ctx); - const loaded = await loadBinarySource(source, 'group-avatar'); - if (!loaded.bytes.length) throw new Error('group avatar file is empty'); - - const hashes = computeHashes(loaded.bytes); - const session = await fetchHighwaySession(bridge); - const extra = protobuf_encode({ - type: 101, - groupUin: groupId, - field3: { field1: 1 }, - field5: 3, - field6: 1, - }); - await uploadHighwayHttp(bridge, session, 3000, new BufferChunkSource(loaded.bytes), hashes.md5, extra); - } - - // ─────────────── queries on me / my contacts ─────────────── - - getLike(userId?: number, start = 0, limit = 10): Promise { - return GetLike.invoke(this.ctx, { userId, start, limit }); - } - - getUnidirectionalFriendList(): Promise { - return GetUnidirectionalFriendList.invoke(this.ctx); - } - - async fetchCustomFace(count = 10): Promise { - const faceIds = await this.fetchCustomFaceIds(count); - return faceIds.map((id) => this.customFaceUrl(id)); - } - - async fetchCustomFaceDetails(count = 10): Promise { - const faceIds = await this.fetchCustomFaceIds(count); - if (faceIds.length === 0) return []; - - const emojis = faceIds.map((emojiId) => ({ - emojiId, - md5: md5FromEmojiId(emojiId), - })); - const details = await FetchCustomFaceDetail.invoke(this.ctx, { emojis }); - const descriptions = new Map(details.map((detail) => [detail.emojiId, detail.desc])); - - return emojis.map(({ emojiId, md5 }) => ({ - emojiId, - url: this.customFaceUrl(emojiId), - md5, - // The detail response may omit entries which have never had a remark. - desc: descriptions.get(emojiId) ?? '', - })); - } - - async fetchCustomFaceIds(count = 10): Promise { - if (!Number.isInteger(count) || count < 0) { - throw new Error('custom face count must be a non-negative integer'); + if (message !== '' && message !== 'set status success') { + throw new Error(message); + } + } } - if (count === 0) return []; - const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin }); - return faceIds.slice(0, count); - } + setProfile(nickname?: string, personalNote?: string, sex?: number): Promise { + return SetProfile.invoke(this.ctx, { nickname, personalNote, sex }); + } - private customFaceUrl(emojiId: string): string { - return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`; - } + setSelfLongNick(longNick: string): Promise { + return SetSelfLongNick.invoke(this.ctx, { longNick }); + } - /** Resolve an existing saved sticker by its resource id or content MD5. */ - async resolveCustomFace(identifier: string): Promise> { - const wanted = identifier.trim(); - if (!wanted) throw new Error('custom face identifier is empty'); - const ids = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin }); - const byMd5 = /^[a-fA-F0-9]{32}$/.test(wanted); - const emojiId = ids.find((id) => byMd5 - ? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase() - : id === wanted); - if (!emojiId) throw new Error('custom face is not in the saved sticker list'); - return { emojiId, url: this.customFaceUrl(emojiId), md5: md5FromEmojiId(emojiId) }; - } + setInputStatus(userId: number, eventType: number): Promise { + return SetInputStatus.invoke(this.ctx, { userId, eventType }); + } - /** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */ - deleteCustomFace(emojiId: string): Promise { - return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId }); - } + async setAvatar(source: string): Promise { + const bridge = asBridge(this.ctx); + const loaded = await loadBinarySource(source, 'avatar'); - /** - * 添加收藏表情(custom face)。imageSource 支持 file:///、base64://、http(s):// - * (复用 highway utils 的 loadBinarySource)。返回新 emoji_id。 - */ - async addCustomFace(imageSource: string): Promise { - const { bytes } = await loadBinarySource(imageSource, 'custom-face'); - return AddCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, imageBytes: bytes }); - } + if (!loaded.bytes.length) { + throw new Error('avatar file is empty'); + } - /** - * 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id - * 中段解析,无需调用方单独提供。desc 为空串则清空备注。 - */ - modifyCustomFace(emojiId: string, desc: string): Promise { - return ModifyCustomFace.invoke(this.ctx, { - emojiId, - md5: md5FromEmojiId(emojiId), - desc, - }); - } + const hashes = computeHashes(loaded.bytes); + const session = await fetchHighwaySession(bridge); + await uploadHighwayHttp( + bridge, + session, + 90, + new BufferChunkSource(loaded.bytes), + hashes.md5, + new Uint8Array(0), + ); + } - /** - * 收藏表情(custom face)移到最前。QQ 客户端只有"移动到最前",协议层 - * (0x902f 的 f3=1)也只支持最前,不支持移到其他位置。两步流程:先 0x902f - * 移动指令,再 0x902e opType=2 上传新顺序(fetch 当前列表把目标挪到第一)。 - * 两步都发才生效。 - */ - async moveCustomFaceToFront(emojiId: string): Promise { - // 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序) - const ids = await this.fetchCustomFaceIds(1000); - const idx = ids.indexOf(emojiId); - if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`); - // 新顺序:目标挪到第一,其余按原顺序 - const reordered = ids.slice(); - reordered.splice(idx, 1); - reordered.unshift(emojiId); - // 2. 0x902f 移动指令(f3=1 = 移到最前) - await OrderCustomFace.invoke(this.ctx, { emojiId, position: 1 }); - // 3. 0x902e opType=2 上传新顺序 - await MoveCustomFace.invoke(this.ctx, { - emojis: reordered.map((id) => ({ emojiId: id, md5: md5FromEmojiId(id) })), - }); - } + /** + * Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar: + * - same highway HTTP upload as personal avatar + * - cmdId 3000 (instead of 90) + * - GroupAvatarExtra proto carried as the `extend` blob, with the + * four protocol-prescribed constants (type=101, field5=3, field6=1, + * field3.field1=1) and the target groupUin. + * + * Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar. + */ + async setGroupAvatar(groupId: number, source: string): Promise { + const bridge = asBridge(this.ctx); + const loaded = await loadBinarySource(source, 'group-avatar'); + + if (!loaded.bytes.length) { + throw new Error('group avatar file is empty'); + } + + const hashes = computeHashes(loaded.bytes); + const session = await fetchHighwaySession(bridge); + const extra = protobuf_encode({ + type: 101, + groupUin: groupId, + field3: { field1: 1 }, + field5: 3, + field6: 1, + }); + await uploadHighwayHttp( + bridge, + session, + 3000, + new BufferChunkSource(loaded.bytes), + hashes.md5, + extra, + ); + } + + // ─────────────── queries on me / my contacts ─────────────── + + getLike(userId?: number, start = 0, limit = 10): Promise { + return GetLike.invoke(this.ctx, { userId, start, limit }); + } + + getUnidirectionalFriendList(): Promise { + return GetUnidirectionalFriendList.invoke(this.ctx); + } + + async fetchCustomFace(count = 10): Promise { + const faceIds = await this.fetchCustomFaceIds(count); + return faceIds.map((id) => this.customFaceUrl(id)); + } + + async fetchCustomFaceDetails(count = 10): Promise { + const faceIds = await this.fetchCustomFaceIds(count); + + if (faceIds.length === 0) { + return []; + } + + const emojis = faceIds.map((emojiId) => ({ + emojiId, + md5: md5FromEmojiId(emojiId), + })); + const details = await FetchCustomFaceDetail.invoke(this.ctx, { emojis }); + const descriptions = new Map(details.map((detail) => [detail.emojiId, detail.desc])); + + return emojis.map(({ emojiId, md5 }) => ({ + emojiId, + url: this.customFaceUrl(emojiId), + md5, + // The detail response may omit entries which have never had a remark. + desc: descriptions.get(emojiId) ?? '', + })); + } + + async fetchCustomFaceIds(count = 10): Promise { + if (!Number.isInteger(count) || count < 0) { + throw new Error('custom face count must be a non-negative integer'); + } + + if (count === 0) { + return []; + } + + const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin }); + return faceIds.slice(0, count); + } + + private customFaceUrl(emojiId: string): string { + return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`; + } + + /** Resolve an existing saved sticker by its resource id or content MD5. */ + async resolveCustomFace( + identifier: string, + ): Promise> { + const wanted = identifier.trim(); + + if (!wanted) { + throw new Error('custom face identifier is empty'); + } + + const ids = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin }); + const byMd5 = /^[a-fA-F0-9]{32}$/.test(wanted); + const emojiId = ids.find((id) => + byMd5 ? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase() : id === wanted, + ); + + if (!emojiId) { + throw new Error('custom face is not in the saved sticker list'); + } + + return { emojiId, url: this.customFaceUrl(emojiId), md5: md5FromEmojiId(emojiId) }; + } + + /** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */ + deleteCustomFace(emojiId: string): Promise { + return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId }); + } + + /** + * 添加收藏表情(custom face)。imageSource 支持 file:///、base64://、http(s):// + * (复用 highway utils 的 loadBinarySource)。返回新 emoji_id。 + */ + async addCustomFace(imageSource: string): Promise { + const { bytes } = await loadBinarySource(imageSource, 'custom-face'); + return AddCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, imageBytes: bytes }); + } + + /** + * 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id + * 中段解析,无需调用方单独提供。desc 为空串则清空备注。 + */ + modifyCustomFace(emojiId: string, desc: string): Promise { + return ModifyCustomFace.invoke(this.ctx, { + emojiId, + md5: md5FromEmojiId(emojiId), + desc, + }); + } + + /** + * 收藏表情(custom face)移到最前。QQ 客户端只有"移动到最前",协议层 + * (0x902f 的 f3=1)也只支持最前,不支持移到其他位置。两步流程:先 0x902f + * 移动指令,再 0x902e opType=2 上传新顺序(fetch 当前列表把目标挪到第一)。 + * 两步都发才生效。 + */ + async moveCustomFaceToFront(emojiId: string): Promise { + // 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序) + const ids = await this.fetchCustomFaceIds(1000); + const idx = ids.indexOf(emojiId); + + if (idx < 0) { + throw new Error(`emoji_id not in list: ${emojiId}`); + } + + // 新顺序:目标挪到第一,其余按原顺序 + const reordered = ids.slice(); + reordered.splice(idx, 1); + reordered.unshift(emojiId); + // 2. 0x902f 移动指令(f3=1 = 移到最前) + await OrderCustomFace.invoke(this.ctx, { emojiId, position: 1 }); + // 3. 0x902e opType=2 上传新顺序 + await MoveCustomFace.invoke(this.ctx, { + emojis: reordered.map((id) => ({ emojiId: id, md5: md5FromEmojiId(id) })), + }); + } } /** @@ -249,11 +303,13 @@ export class ProfileApi { * 传空串让服务端拒绝更早定位问题。 */ function md5FromEmojiId(emojiId: string): string { - const parts = emojiId.split('_'); - // 期望形如 `_0_0_0__0_0`,共 7 段,md5 在 index 4。 - const md5 = parts[4]; - if (!md5 || md5.length !== 32 || !/^[0-9a-fA-F]{32}$/.test(md5)) { - throw new Error(`invalid emoji_id (cannot extract md5): ${emojiId}`); - } - return md5.toUpperCase(); + const parts = emojiId.split('_'); + // 期望形如 `_0_0_0__0_0`,共 7 段,md5 在 index 4。 + const md5 = parts[4]; + + if (!md5 || md5.length !== 32 || !/^[0-9a-fA-F]{32}$/.test(md5)) { + throw new Error(`invalid emoji_id (cannot extract md5): ${emojiId}`); + } + + return md5.toUpperCase(); } diff --git a/packages/core/src/bridge/apis/qzone.ts b/packages/core/src/bridge/apis/qzone.ts index 37f3553e..cc463083 100644 --- a/packages/core/src/bridge/apis/qzone.ts +++ b/packages/core/src/bridge/apis/qzone.ts @@ -1,19 +1,19 @@ import { - commentQzoneMsg, - deleteQzoneMsg, - getQzoneFeeds, - getQzoneMsgList, - publishQzoneMsg, - setQzoneBlack, - setQzoneLike, - updateQzoneMsgRight, - uploadQzoneImageFromSource, - type QzoneCommentResult, - type QzoneFeedsResult, - type QzoneMsgListResult, - type QzonePublishResult, - type QzoneUpdateRightResult, - type QzoneUploadImageResult, + commentQzoneMsg, + deleteQzoneMsg, + getQzoneFeeds, + getQzoneMsgList, + publishQzoneMsg, + setQzoneBlack, + setQzoneLike, + updateQzoneMsgRight, + uploadQzoneImageFromSource, + type QzoneCommentResult, + type QzoneFeedsResult, + type QzoneMsgListResult, + type QzonePublishResult, + type QzoneUpdateRightResult, + type QzoneUploadImageResult, } from '@snowluma/protocol/web/qzone'; import type { BridgeContext } from '../bridge-context'; @@ -24,105 +24,122 @@ import type { BridgeContext } from '../bridge-context'; * Distinct from the group-album surface, which lives on GroupAlbumApi. */ export class QzoneApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - /** - * 获取说说列表。`targetUin` 省略时取机器人自己的空间。 - * `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。 - */ - async getMsgList(targetUin?: number, pos = 0, num = 20): Promise { - const uin = targetUin && targetUin > 0 ? targetUin.toString() : this.ctx.identity.uin; - const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - return getQzoneMsgList(cookieObject, uin, pos, num); - } + /** + * 获取说说列表。`targetUin` 省略时取机器人自己的空间。 + * `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。 + */ + async getMsgList(targetUin?: number, pos = 0, num = 20): Promise { + const uin = targetUin && targetUin > 0 ? targetUin.toString() : this.ctx.identity.uin; + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + return getQzoneMsgList(cookieObject, uin, pos, num); + } - /** - * 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。 - * 始终以机器人自己的身份拉取好友动态。 - */ - async getFeeds(pageNum = 1, count = 10): Promise { - const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count); - } + /** + * 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。 + * 始终以机器人自己的身份拉取好友动态。 + */ + async getFeeds(pageNum = 1, count = 10): Promise { + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count); + } - /** - * 从来源上传图片到 QQ 空间。 - * `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据 - */ - async uploadImageFromSource(source: string): Promise { - const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source); - } + /** + * 从来源上传图片到 QQ 空间。 + * `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据 + */ + async uploadImageFromSource(source: string): Promise { + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source); + } - /** - * 发表说说,返回新说说的 tid。始终发到机器人自己的空间。 - * `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串 - * (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。 - * `ugcRight` / `targetUins`: 查看权限及其作用名单(ugcRight=16/128 时必填)。 - */ - async publish( - content: string, - richType?: number, - richval?: string, - ugcRight = 1, - targetUins?: string, - ): Promise { - const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval, ugcRight, targetUins); - } + /** + * 发表说说,返回新说说的 tid。始终发到机器人自己的空间。 + * `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串 + * (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。 + * `ugcRight` / `targetUins`: 查看权限及其作用名单(ugcRight=16/128 时必填)。 + */ + async publish( + content: string, + richType?: number, + richval?: string, + ugcRight = 1, + targetUins?: string, + ): Promise { + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + return publishQzoneMsg( + cookieObject, + this.ctx.identity.uin, + content, + richType, + richval, + ugcRight, + targetUins, + ); + } - /** 删除机器人自己空间的一条说说(按 tid)。 */ - async delete(tid: string): Promise { - const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid); - } + /** 删除机器人自己空间的一条说说(按 tid)。 */ + async delete(tid: string): Promise { + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid); + } - /** - * 修改机器人自己空间一条已发说说的查看权限(按 tid)。 - * `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。 - */ - async updateRight(tid: string, ugcRight: number, targetUins?: string): Promise { - const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins); - } + /** + * 修改机器人自己空间一条已发说说的查看权限(按 tid)。 + * `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。 + */ + async updateRight( + tid: string, + ugcRight: number, + targetUins?: string, + ): Promise { + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins); + } - /** - * 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说; - * 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。 - */ - async like(tid: string, targetUin: number | undefined, like: boolean, abstime = 0): Promise { - const selfUin = this.ctx.identity.uin; - const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin; - const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - await setQzoneLike(cookieObject, selfUin, owner, tid, like, abstime); - } + /** + * 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说; + * 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。 + */ + async like( + tid: string, + targetUin: number | undefined, + like: boolean, + abstime = 0, + ): Promise { + const selfUin = this.ctx.identity.uin; + const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin; + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + await setQzoneLike(cookieObject, selfUin, owner, tid, like, abstime); + } - /** - * 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间); - * 始终以机器人身份发表评论。返回新评论 id(尽力而为)。 - * `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL - * (从 uploadImageFromSource 的 url 字段获取)。 - */ - async comment( - tid: string, - content: string, - targetUin: number | undefined, - richType?: number, - richval?: string, - ): Promise { - const selfUin = this.ctx.identity.uin; - const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin; - const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval); - } + /** + * 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间); + * 始终以机器人身份发表评论。返回新评论 id(尽力而为)。 + * `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL + * (从 uploadImageFromSource 的 url 字段获取)。 + */ + async comment( + tid: string, + content: string, + targetUin: number | undefined, + richType?: number, + richval?: string, + ): Promise { + const selfUin = this.ctx.identity.uin; + const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin; + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval); + } - /** - * 拉黑或解除拉黑某人(修改机器人自身 QQ 空间黑名单)。 - * `ban=true` 拉黑,`ban=false` 解除拉黑。 - */ - async setBlack(targetUin: number, ban: boolean): Promise { - const selfUin = this.ctx.identity.uin; - const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - await setQzoneBlack(cookieObject, selfUin, targetUin.toString(), ban); - } + /** + * 拉黑或解除拉黑某人(修改机器人自身 QQ 空间黑名单)。 + * `ban=true` 拉黑,`ban=false` 解除拉黑。 + */ + async setBlack(targetUin: number, ban: boolean): Promise { + const selfUin = this.ctx.identity.uin; + const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); + await setQzoneBlack(cookieObject, selfUin, targetUin.toString(), ban); + } } diff --git a/packages/core/src/bridge/apis/shared.ts b/packages/core/src/bridge/apis/shared.ts index 0927dc5d..f47c39f2 100644 --- a/packages/core/src/bridge/apis/shared.ts +++ b/packages/core/src/bridge/apis/shared.ts @@ -1,14 +1,19 @@ export function toInt(value: unknown): number { - if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); - if (typeof value === 'bigint') { - const n = Number(value); - return Number.isFinite(n) ? Math.trunc(n) : 0; - } - if (typeof value === 'string' && value.trim()) { - const n = Number(value); - return Number.isFinite(n) ? Math.trunc(n) : 0; - } - return 0; + if (typeof value === 'number' && Number.isFinite(value)) { + return Math.trunc(value); + } + + if (typeof value === 'bigint') { + const n = Number(value); + return Number.isFinite(n) ? Math.trunc(n) : 0; + } + + if (typeof value === 'string' && value.trim()) { + const n = Number(value); + return Number.isFinite(n) ? Math.trunc(n) : 0; + } + + return 0; } // The bot's-own-UID resolver is the single source of truth in @snowluma/protocol @@ -22,25 +27,25 @@ export { resolveSelfUid } from '@snowluma/protocol/self-uid'; * fetchers in group-file.ts. */ export interface MediaIndexNode { - info?: { - fileSize?: number; - fileHash?: string; - fileSha1?: string; - fileName?: string; - width?: number; - height?: number; - time?: number; - original?: number; - type?: { - type?: number; - picFormat?: number; - videoFormat?: number; - voiceFormat?: number; + info?: { + fileSize?: number; + fileHash?: string; + fileSha1?: string; + fileName?: string; + width?: number; + height?: number; + time?: number; + original?: number; + type?: { + type?: number; + picFormat?: number; + videoFormat?: number; + voiceFormat?: number; + }; }; - }; - fileUuid?: string; - storeId?: number; - uploadTime?: number; - ttl?: number; - subType?: number; + fileUuid?: string; + storeId?: number; + uploadTime?: number; + ttl?: number; + subType?: number; } diff --git a/packages/core/src/bridge/apis/system-face.ts b/packages/core/src/bridge/apis/system-face.ts index 6a1964be..921a74b1 100644 --- a/packages/core/src/bridge/apis/system-face.ts +++ b/packages/core/src/bridge/apis/system-face.ts @@ -1,7 +1,7 @@ import { - sysFaceStore, - type SysFaceEntry, - type SysFacePackEntry, + sysFaceStore, + type SysFaceEntry, + type SysFacePackEntry, } from '@snowluma/protocol/sys-face-store'; import { isSuperFaceEntry } from '@snowluma/protocol/oidb-services/sys-faces/fetch-sys-faces'; import type { BridgeContext } from '../bridge-context'; @@ -9,27 +9,28 @@ import type { BridgeContext } from '../bridge-context'; /** QQ's account-independent system-face directory. The shared store owns * persistence and refresh coalescing; this API binds it to one live sender. */ export class SystemFaceApi { - constructor(private readonly ctx: BridgeContext) {} + constructor(private readonly ctx: BridgeContext) {} - fetchCatalog(refresh = false): Promise { - return sysFaceStore.getCatalog(this.ctx, refresh); - } - - async fetchFace(faceId: number, refresh = false): Promise { - if (refresh) { - await sysFaceStore.refresh(this.ctx); - return sysFaceStore.lookup(faceId); + fetchCatalog(refresh = false): Promise { + return sysFaceStore.getCatalog(this.ctx, refresh); } - return sysFaceStore.resolve(this.ctx, faceId); - } - async search(query: string): Promise { - await sysFaceStore.ensureReady(this.ctx); - return sysFaceStore.search(query); - } + async fetchFace(faceId: number, refresh = false): Promise { + if (refresh) { + await sysFaceStore.refresh(this.ctx); + return sysFaceStore.lookup(faceId); + } - async isSuper(faceId: number, refresh = false): Promise { - const face = await this.fetchFace(faceId, refresh); - return face !== null && isSuperFaceEntry(face); - } + return sysFaceStore.resolve(this.ctx, faceId); + } + + async search(query: string): Promise { + await sysFaceStore.ensureReady(this.ctx); + return sysFaceStore.search(query); + } + + async isSuper(faceId: number, refresh = false): Promise { + const face = await this.fetchFace(faceId, refresh); + return face !== null && isSuperFaceEntry(face); + } } diff --git a/packages/core/src/bridge/apis/web.ts b/packages/core/src/bridge/apis/web.ts index eacf7eda..edd00a27 100644 --- a/packages/core/src/bridge/apis/web.ts +++ b/packages/core/src/bridge/apis/web.ts @@ -1,226 +1,288 @@ import { loadBinarySource } from '@snowluma/protocol/highway/utils'; -import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key'; +import { + ForceFetchClientKey, + type ClientKeyInfo as NamespaceClientKeyInfo, +} from '@snowluma/protocol/oidb-services/web/force-fetch-client-key'; import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey'; -import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence'; +import { + getGroupEssenceMsg, + getGroupEssenceMsgAll, + type GroupEssenceMsgRet, +} from '@snowluma/protocol/web/group-essence'; import { getFriendDressWebAPI, type WebFriendDress } from '@snowluma/protocol/web/friend-dress'; -import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor'; +import { + getHonorListWebAPI, + WebHonorType, + type WebHonorItem, +} from '@snowluma/protocol/web/group-honor'; import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin'; import { - deleteGroupNotice as deleteGroupNoticeHttp, - GROUP_NOTICE_TYPE_NEW_MEMBERS, - GROUP_NOTICE_TYPE_NORMAL, - getGroupNoticeWebAPI, - groupNoticeImageUrl, - setGroupNoticeWebAPI, - uploadGroupNoticeImage, - type SetNoticeRetSuccess, - type WebApiGroupNoticeCollection, - type WebApiGroupNoticeFeed, - type WebApiGroupNoticeRet, + deleteGroupNotice as deleteGroupNoticeHttp, + GROUP_NOTICE_TYPE_NEW_MEMBERS, + GROUP_NOTICE_TYPE_NORMAL, + getGroupNoticeWebAPI, + groupNoticeImageUrl, + setGroupNoticeWebAPI, + uploadGroupNoticeImage, + type SetNoticeRetSuccess, + type WebApiGroupNoticeCollection, + type WebApiGroupNoticeFeed, + type WebApiGroupNoticeRet, } from '@snowluma/protocol/web/group-notice'; import { RequestUtil } from '@snowluma/protocol/web/request-util'; import type { Bridge } from '../bridge'; import type { BridgeContext } from '../bridge-context'; -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } +function asBridge(ctx: BridgeContext): Bridge { + return ctx as unknown as Bridge; +} export type ClientKeyInfo = NamespaceClientKeyInfo; export interface WebHonorInfo { - [key: string]: import('@snowluma/common/json').JsonValue; - group_id: number; - current_talkative: WebHonorItem | null; - talkative_list: WebHonorItem[]; - performer_list: WebHonorItem[]; - legend_list: WebHonorItem[]; - emotion_list: WebHonorItem[]; - strong_newbie_list: WebHonorItem[]; + [key: string]: import('@snowluma/common/json').JsonValue; + group_id: number; + current_talkative: WebHonorItem | null; + talkative_list: WebHonorItem[]; + performer_list: WebHonorItem[]; + legend_list: WebHonorItem[]; + emotion_list: WebHonorItem[]; + strong_newbie_list: WebHonorItem[]; } export interface WebNoticeInfo { - [key: string]: import('@snowluma/common/json').JsonValue; - notice_id: string; - sender_id: number; - publish_time: number; - message: { - text: string; - image: Array<{ id: string; url: string; height: number; width: number }>; - images: Array<{ id: string; url: string; height: number; width: number }>; - }; - settings: import('@snowluma/common/json').JsonValue; - read_num: number; - /** Server response type. Regular notices are commonly returned as 6. */ - type: number; - pinned: number; - send_to_new_members: boolean; + [key: string]: import('@snowluma/common/json').JsonValue; + notice_id: string; + sender_id: number; + publish_time: number; + message: { + text: string; + image: Array<{ id: string; url: string; height: number; width: number }>; + images: Array<{ id: string; url: string; height: number; width: number }>; + }; + settings: import('@snowluma/common/json').JsonValue; + read_num: number; + /** Server response type. Regular notices are commonly returned as 6. */ + type: number; + pinned: number; + send_to_new_members: boolean; } export interface SendNoticeOptions { - image?: string; - pinned?: number; - type?: number; - sendToNewMembers?: boolean; - isShowEditCard?: number; - tipWindowType?: number; - confirmRequired?: number; + image?: string; + pinned?: number; + type?: number; + sendToNewMembers?: boolean; + isShowEditCard?: number; + tipWindowType?: number; + confirmRequired?: number; } function finiteNumber(value: unknown, field: string): number { - const parsed = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN; - if (!Number.isFinite(parsed)) { - throw new Error(`invalid group notice response: ${field} must be a finite number`); - } - return parsed; + const parsed = + typeof value === 'number' + ? value + : typeof value === 'string' && value.trim() !== '' + ? Number(value) + : Number.NaN; + + if (!Number.isFinite(parsed)) { + throw new Error(`invalid group notice response: ${field} must be a finite number`); + } + + return parsed; } function collectionValues( - collection: WebApiGroupNoticeCollection | undefined, - field: 'feeds' | 'inst', + collection: WebApiGroupNoticeCollection | undefined, + field: 'feeds' | 'inst', ): WebApiGroupNoticeFeed[] { - if (collection === undefined) return []; - if (Array.isArray(collection)) return collection; - if (collection === null || typeof collection !== 'object') { - throw new Error(`invalid group notice response: ${field} must be an array or object`); - } - return Object.values(collection); + if (collection === undefined) { + return []; + } + + if (Array.isArray(collection)) { + return collection; + } + + if (collection === null || typeof collection !== 'object') { + throw new Error(`invalid group notice response: ${field} must be an array or object`); + } + + return Object.values(collection); } function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boolean): WebNoticeInfo { - if (!feed || typeof feed !== 'object') { - throw new Error('invalid group notice response: feed must be an object'); - } - if (typeof feed.fid !== 'string' || feed.fid.length === 0) { - throw new Error('invalid group notice response: feed.fid must be a non-empty string'); - } - if (!feed.msg || typeof feed.msg !== 'object' || typeof feed.msg.text !== 'string') { - throw new Error(`invalid group notice response: feed ${feed.fid} has no message text`); - } - if (feed.settings === undefined) { - throw new Error(`invalid group notice response: feed ${feed.fid} has no settings`); - } - - const image = (feed.msg.pics ?? []).map((pic, index) => { - if (!pic || typeof pic !== 'object' || typeof pic.id !== 'string') { - throw new Error(`invalid group notice response: feed ${feed.fid} image ${index} is malformed`); + if (!feed || typeof feed !== 'object') { + throw new Error('invalid group notice response: feed must be an object'); } - return { - id: pic.id, - url: groupNoticeImageUrl(pic.id), - height: finiteNumber(pic.h, `feed ${feed.fid} image ${index}.h`), - width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`), - }; - }); - const responseType = feed.type === undefined - ? sendToNewMembers ? GROUP_NOTICE_TYPE_NEW_MEMBERS : GROUP_NOTICE_TYPE_NORMAL - : finiteNumber(feed.type, `feed ${feed.fid}.type`); - return { - notice_id: feed.fid, - sender_id: finiteNumber(feed.u, `feed ${feed.fid}.u`), - publish_time: finiteNumber(feed.pubt, `feed ${feed.fid}.pubt`), - message: { - text: feed.msg.text, - image, - images: image, - }, - settings: feed.settings, - read_num: finiteNumber(feed.read_num, `feed ${feed.fid}.read_num`), - type: responseType, - pinned: feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`), - send_to_new_members: sendToNewMembers || responseType === GROUP_NOTICE_TYPE_NEW_MEMBERS, - }; + if (typeof feed.fid !== 'string' || feed.fid.length === 0) { + throw new Error('invalid group notice response: feed.fid must be a non-empty string'); + } + + if (!feed.msg || typeof feed.msg !== 'object' || typeof feed.msg.text !== 'string') { + throw new Error(`invalid group notice response: feed ${feed.fid} has no message text`); + } + + if (feed.settings === undefined) { + throw new Error(`invalid group notice response: feed ${feed.fid} has no settings`); + } + + const image = (feed.msg.pics ?? []).map((pic, index) => { + if (!pic || typeof pic !== 'object' || typeof pic.id !== 'string') { + throw new Error( + `invalid group notice response: feed ${feed.fid} image ${index} is malformed`, + ); + } + + return { + id: pic.id, + url: groupNoticeImageUrl(pic.id), + height: finiteNumber(pic.h, `feed ${feed.fid} image ${index}.h`), + width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`), + }; + }); + const responseType = + feed.type === undefined + ? sendToNewMembers + ? GROUP_NOTICE_TYPE_NEW_MEMBERS + : GROUP_NOTICE_TYPE_NORMAL + : finiteNumber(feed.type, `feed ${feed.fid}.type`); + + return { + notice_id: feed.fid, + sender_id: finiteNumber(feed.u, `feed ${feed.fid}.u`), + publish_time: finiteNumber(feed.pubt, `feed ${feed.fid}.pubt`), + message: { + text: feed.msg.text, + image, + images: image, + }, + settings: feed.settings, + read_num: finiteNumber(feed.read_num, `feed ${feed.fid}.read_num`), + type: responseType, + pinned: + feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`), + send_to_new_members: sendToNewMembers || responseType === GROUP_NOTICE_TYPE_NEW_MEMBERS, + }; } /** Merge QQ's regular (`feeds`) and new-member (`inst`) announcement lists. */ export function mapGroupNoticeResponse(ret: WebApiGroupNoticeRet): WebNoticeInfo[] { - if (ret.ec !== 0) { - throw new Error(`获取公告失败: ec=${ret.ec}, em=${ret.em ?? 'missing'}`); - } - - const notices: WebNoticeInfo[] = []; - const indexByNoticeId = new Map(); - const append = (collection: WebApiGroupNoticeCollection | undefined, sendToNewMembers: boolean, field: 'feeds' | 'inst') => { - for (const feed of collectionValues(collection, field)) { - const mapped = mapGroupNoticeFeed(feed, sendToNewMembers); - const existingIndex = indexByNoticeId.get(mapped.notice_id); - if (existingIndex === undefined) { - indexByNoticeId.set(mapped.notice_id, notices.length); - notices.push(mapped); - } else if (sendToNewMembers) { - // If QQ returns the same item in both collections, `inst` is the - // authoritative signal that it targets new members. - notices[existingIndex] = mapped; - } + if (ret.ec !== 0) { + throw new Error(`获取公告失败: ec=${ret.ec}, em=${ret.em ?? 'missing'}`); } - }; - append(ret.feeds, false, 'feeds'); - append(ret.inst, true, 'inst'); - return notices; + const notices: WebNoticeInfo[] = []; + const indexByNoticeId = new Map(); + + const append = ( + collection: WebApiGroupNoticeCollection | undefined, + sendToNewMembers: boolean, + field: 'feeds' | 'inst', + ) => { + for (const feed of collectionValues(collection, field)) { + const mapped = mapGroupNoticeFeed(feed, sendToNewMembers); + const existingIndex = indexByNoticeId.get(mapped.notice_id); + + if (existingIndex === undefined) { + indexByNoticeId.set(mapped.notice_id, notices.length); + notices.push(mapped); + } else if (sendToNewMembers) { + // If QQ returns the same item in both collections, `inst` is the + // authoritative signal that it targets new members. + notices[existingIndex] = mapped; + } + } + }; + + append(ret.feeds, false, 'feeds'); + append(ret.inst, true, 'inst'); + return notices; } // ─────────────── private helpers (cookie acquisition) ─────────────── function forceFetchClientKeyInner(bridge: Bridge): Promise { - return ForceFetchClientKey.invoke(bridge); + return ForceFetchClientKey.invoke(bridge); } -function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map }> { - return GetPskey.invoke(bridge, { domainList }); +function getPSkey( + bridge: Bridge, + domainList: string[], +): Promise<{ domainPskeyMap: Map }> { + return GetPskey.invoke(bridge, { domainList }); } async function getCookies(bridge: Bridge, domain: string): Promise> { - const ClientKeyData = await forceFetchClientKeyInner(bridge); + const ClientKeyData = await forceFetchClientKeyInner(bridge); - // Build the ptlogin2 jump URL: this is the canonical way for the - // bot to swap its clientKey for cookie-jar entries on a given - // qq.com subdomain. - const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin + - '&clientkey=' + ClientKeyData.clientKey + - '&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex; + // Build the ptlogin2 jump URL: this is the canonical way for the + // bot to swap its clientKey for cookie-jar entries on a given + // qq.com subdomain. + const requestUrl = + 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + + bridge.identity.uin + + '&clientkey=' + + ClientKeyData.clientKey + + '&u1=https%3A%2F%2F' + + domain + + '%2F' + + bridge.identity.uin + + '%2Finfocenter&keyindex=' + + ClientKeyData.keyIndex; - const data = await RequestUtil.HttpsGetCookies(requestUrl); + const data = await RequestUtil.HttpsGetCookies(requestUrl); - if (!data['p_skey'] || data['p_skey'].length === 0) { - // ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey - // for the same domain. Errors are swallowed so the caller can - // still proceed with whatever cookies it did get. - try { - const pskeyData = await getPSkey(bridge, [domain]); - const pskey = pskeyData.domainPskeyMap.get(domain); - if (pskey) { - data['p_skey'] = pskey; - } - } catch { - return data; + if (!data['p_skey'] || data['p_skey'].length === 0) { + // ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey + // for the same domain. Errors are swallowed so the caller can + // still proceed with whatever cookies it did get. + try { + const pskeyData = await getPSkey(bridge, [domain]); + const pskey = pskeyData.domainPskeyMap.get(domain); + + if (pskey) { + data['p_skey'] = pskey; + } + } catch { + return data; + } } - } - return data; + return data; } async function getSKey(bridge: Bridge): Promise { - const ClientKeyData = await forceFetchClientKeyInner(bridge); + const ClientKeyData = await forceFetchClientKeyInner(bridge); - if (!ClientKeyData.clientKey) { - throw new Error('getClientKey Error: clientKey is empty'); - } + if (!ClientKeyData.clientKey) { + throw new Error('getClientKey Error: clientKey is empty'); + } - const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0'); - const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' + - '&clientuin=' + bridge.identity.uin + - '&clientkey=' + ClientKeyData.clientKey + - '&u1=' + u1 + - '&keyindex=' + ClientKeyData.keyIndex; + const u1 = encodeURIComponent( + 'https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0', + ); + const requestUrl = + 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' + + '&clientuin=' + + bridge.identity.uin + + '&clientkey=' + + ClientKeyData.clientKey + + '&u1=' + + u1 + + '&keyindex=' + + ClientKeyData.keyIndex; - const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl); - const skey = cookies['skey']; + const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl); + const skey = cookies['skey']; - if (!skey) { - throw new Error('SKey is Empty'); - } + if (!skey) { + throw new Error('SKey is Empty'); + } - return skey; + return skey; } /** @@ -228,207 +290,213 @@ async function getSKey(bridge: Bridge): Promise { * skey or p_skey. djb2 hash truncated to 31 bits. */ function getBknFromSKey(skey: string): number { - let hash = 5381; - for (let i = 0; i < skey.length; i++) { - hash += (hash << 5) + skey.charCodeAt(i); - } - return hash & 2147483647; + let hash = 5381; + + for (let i = 0; i < skey.length; i++) { + hash += (hash << 5) + skey.charCodeAt(i); + } + + return hash & 2147483647; } export class WebApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: BridgeContext) {} - // ─────────────── cookie / token primitives ─────────────── + // ─────────────── cookie / token primitives ─────────────── - async forceFetchClientKey(): Promise { - return forceFetchClientKeyInner(asBridge(this.ctx)); - } - - /** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi - * (qzone.qq.com) and by every other web helper here. */ - async getCookies(domain: string): Promise> { - return getCookies(asBridge(this.ctx), domain); - } - - /** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */ - async getCookiesStr(domain: string): Promise { - const cookieObject = await getCookies(asBridge(this.ctx), domain); - return Object.entries(cookieObject) - .map(([key, value]) => `${key}=${value}`) - .join('; '); - } - - /** CSRF token == bkn(skey) — used by qzone / qun web APIs. */ - async getCsrfToken(): Promise { - const skey = await getSKey(asBridge(this.ctx)); - if (!skey) { - throw new Error('SKey is Empty'); - } - return getBknFromSKey(skey); - } - - /** Returns the OneBot `get_credentials` payload (cookie string + bkn). */ - async getCredentials(domain: string): Promise<{ cookies: string; token: number; csrf_token: number }> { - const cookieObject = await getCookies(asBridge(this.ctx), domain); - const cookiesStr = Object.entries(cookieObject) - .map(([key, value]) => `${key}=${value}`) - .join('; '); - - const skey = cookieObject['p_skey'] || cookieObject['skey'] || ''; - const token = skey ? getBknFromSKey(skey) : 0; - - return { - cookies: cookiesStr, - token, - csrf_token: token, - }; - } - - // ─────────────── group essence ─────────────── - - /** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */ - async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise { - const bridge = asBridge(this.ctx); - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit); - return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } }; - } - - /** Walks every page and returns the concatenated result. */ - async getEssenceAll(groupId: number): Promise { - const bridge = asBridge(this.ctx); - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - return await getGroupEssenceMsgAll(cookieObject, groupCode); - } - - // ─────────────── group honor ─────────────── - - async getHonorInfo(groupId: number, type: WebHonorType | string): Promise { - const bridge = asBridge(this.ctx); - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - - const honorInfo: WebHonorInfo = { - group_id: groupId, - current_talkative: null, - talkative_list: [], - performer_list: [], - legend_list: [], - emotion_list: [], - strong_newbie_list: [], - }; - - if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) { - const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1); - if (talkativeList.length > 0) { - honorInfo.current_talkative = talkativeList[0]; - honorInfo.talkative_list = talkativeList; - } + async forceFetchClientKey(): Promise { + return forceFetchClientKeyInner(asBridge(this.ctx)); } - if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) { - honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2); + /** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi + * (qzone.qq.com) and by every other web helper here. */ + async getCookies(domain: string): Promise> { + return getCookies(asBridge(this.ctx), domain); } - if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) { - honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3); + /** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */ + async getCookiesStr(domain: string): Promise { + const cookieObject = await getCookies(asBridge(this.ctx), domain); + return Object.entries(cookieObject) + .map(([key, value]) => `${key}=${value}`) + .join('; '); } - if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) { - honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6); + /** CSRF token == bkn(skey) — used by qzone / qun web APIs. */ + async getCsrfToken(): Promise { + const skey = await getSKey(asBridge(this.ctx)); + + if (!skey) { + throw new Error('SKey is Empty'); + } + + return getBknFromSKey(skey); } - return honorInfo; - } + /** Returns the OneBot `get_credentials` payload (cookie string + bkn). */ + async getCredentials( + domain: string, + ): Promise<{ cookies: string; token: number; csrf_token: number }> { + const cookieObject = await getCookies(asBridge(this.ctx), domain); + const cookiesStr = Object.entries(cookieObject) + .map(([key, value]) => `${key}=${value}`) + .join('; '); - // ─────────────── group sign-in (打卡) ─────────────── + const skey = cookieObject['p_skey'] || cookieObject['skey'] || ''; + const token = skey ? getBknFromSKey(skey) : 0; - /** Today's group sign-in list via qun.qq.com. [] when the group has no - * sign-ins; THROWS on transport / auth failure (caller maps to failed). */ - async getSignedList(groupId: number): Promise { - const bridge = asBridge(this.ctx); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - return getDaySignedListWebAPI(cookieObject, groupId.toString(), bridge.identity.uin.toString()); - } - - // ─────────────── group notice ─────────────── - - async sendNotice( - groupId: number, - content: string, - options?: SendNoticeOptions, - ): Promise { - const bridge = asBridge(this.ctx); - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - - let picId = ''; - let imgWidth = 540; - let imgHeight = 300; - - if (options?.image) { - // Route through loadBinarySource so the group-notice image download - // gets the same browser-UA + Referer-retry hardening as every other - // media fetch — and http/file/base64 source handling for free. - const loaded = await loadBinarySource(options.image, 'group-notice image'); - const imageBuffer = Buffer.from(loaded.bytes); - - const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer); - picId = picInfo.id; - imgWidth = picInfo.width; - imgHeight = picInfo.height; + return { + cookies: cookiesStr, + token, + csrf_token: token, + }; } - const ret = await setGroupNoticeWebAPI( - cookieObject, - groupCode, - content, - { - pinned: options?.pinned, - type: options?.type, - sendToNewMembers: options?.sendToNewMembers, - isShowEditCard: options?.isShowEditCard, - tipWindowType: options?.tipWindowType, - confirmRequired: options?.confirmRequired, - picId, - imgWidth, - imgHeight, - }, - ); + // ─────────────── group essence ─────────────── - if (ret.ec !== 0) { - throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`); + /** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */ + async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit); + return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } }; } - return ret; - } + /** Walks every page and returns the concatenated result. */ + async getEssenceAll(groupId: number): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + return await getGroupEssenceMsgAll(cookieObject, groupCode); + } - async getNotice(groupId: number): Promise { - const bridge = asBridge(this.ctx); - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); + // ─────────────── group honor ─────────────── - const ret = await getGroupNoticeWebAPI(cookieObject, groupCode); - return mapGroupNoticeResponse(ret); - } + async getHonorInfo(groupId: number, type: WebHonorType | string): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); - async deleteNotice(groupId: number, fid: string): Promise { - const bridge = asBridge(this.ctx); - const groupCode = groupId.toString(); - const cookieObject = await getCookies(bridge, 'qun.qq.com'); - return await deleteGroupNoticeHttp(cookieObject, groupCode, fid); - } + const honorInfo: WebHonorInfo = { + group_id: groupId, + current_talkative: null, + talkative_list: [], + performer_list: [], + legend_list: [], + emotion_list: [], + strong_newbie_list: [], + }; - // ─────────────── friend dress (好友装扮) ─────────────── + if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) { + const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1); - /** 查某人正在用的好友装扮(挂件/名片/来电/输入状态等)。走 vip.qq.com 域, - * 纯 cookie 鉴权、抓 SSR HTML。「查到但没装扮」返回空 items;网络/未登录态/ - * 风控/页面改版/串号数据抛 FriendDressError(kind 区分具体环节)。 */ - async getFriendDress(targetUin: number): Promise { - const bridge = asBridge(this.ctx); - const cookieObject = await getCookies(bridge, 'vip.qq.com'); - return getFriendDressWebAPI(cookieObject, targetUin.toString()); - } + if (talkativeList.length > 0) { + honorInfo.current_talkative = talkativeList[0]; + honorInfo.talkative_list = talkativeList; + } + } + + if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) { + honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2); + } + + if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) { + honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3); + } + + if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) { + honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6); + } + + return honorInfo; + } + + // ─────────────── group sign-in (打卡) ─────────────── + + /** Today's group sign-in list via qun.qq.com. [] when the group has no + * sign-ins; THROWS on transport / auth failure (caller maps to failed). */ + async getSignedList(groupId: number): Promise { + const bridge = asBridge(this.ctx); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + return getDaySignedListWebAPI( + cookieObject, + groupId.toString(), + bridge.identity.uin.toString(), + ); + } + + // ─────────────── group notice ─────────────── + + async sendNotice( + groupId: number, + content: string, + options?: SendNoticeOptions, + ): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + + let picId = ''; + let imgWidth = 540; + let imgHeight = 300; + + if (options?.image) { + // Route through loadBinarySource so the group-notice image download + // gets the same browser-UA + Referer-retry hardening as every other + // media fetch — and http/file/base64 source handling for free. + const loaded = await loadBinarySource(options.image, 'group-notice image'); + const imageBuffer = Buffer.from(loaded.bytes); + + const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer); + picId = picInfo.id; + imgWidth = picInfo.width; + imgHeight = picInfo.height; + } + + const ret = await setGroupNoticeWebAPI(cookieObject, groupCode, content, { + pinned: options?.pinned, + type: options?.type, + sendToNewMembers: options?.sendToNewMembers, + isShowEditCard: options?.isShowEditCard, + tipWindowType: options?.tipWindowType, + confirmRequired: options?.confirmRequired, + picId, + imgWidth, + imgHeight, + }); + + if (ret.ec !== 0) { + throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`); + } + + return ret; + } + + async getNotice(groupId: number): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + + const ret = await getGroupNoticeWebAPI(cookieObject, groupCode); + return mapGroupNoticeResponse(ret); + } + + async deleteNotice(groupId: number, fid: string): Promise { + const bridge = asBridge(this.ctx); + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + return await deleteGroupNoticeHttp(cookieObject, groupCode, fid); + } + + // ─────────────── friend dress (好友装扮) ─────────────── + + /** 查某人正在用的好友装扮(挂件/名片/来电/输入状态等)。走 vip.qq.com 域, + * 纯 cookie 鉴权、抓 SSR HTML。「查到但没装扮」返回空 items;网络/未登录态/ + * 风控/页面改版/串号数据抛 FriendDressError(kind 区分具体环节)。 */ + async getFriendDress(targetUin: number): Promise { + const bridge = asBridge(this.ctx); + const cookieObject = await getCookies(bridge, 'vip.qq.com'); + return getFriendDressWebAPI(cookieObject, targetUin.toString()); + } } diff --git a/packages/core/src/bridge/bridge-context.ts b/packages/core/src/bridge/bridge-context.ts index ef146e85..275c3ca7 100644 --- a/packages/core/src/bridge/bridge-context.ts +++ b/packages/core/src/bridge/bridge-context.ts @@ -2,7 +2,6 @@ import type { BridgeContext as BaseBridgeContext } from '@snowluma/protocol/brid import type { ApiHub } from './apis'; export interface BridgeContext extends BaseBridgeContext { - readonly apis: ApiHub; + readonly apis: ApiHub; } export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context'; - diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index ab0b4034..38648787 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -2,18 +2,18 @@ import type { OnlineDeviceInfo } from '@snowluma/protocol/events'; import type { BridgeContext } from './bridge-context'; export interface RosterWarmupResult { - friendsLoaded: boolean; - groupsLoaded: boolean; + friendsLoaded: boolean; + groupsLoaded: boolean; } export interface BridgeInterface extends BridgeContext { - readonly activePid: number | null; - /** Settles once for this Bridge session after first-login roster fetch. */ - whenRosterWarmupSettled(): Promise; - /** False only when every attached QQ process has a confirmed receive or - * request-path failure. An unarmed watchdog remains true for compatibility. */ - readonly receiveHealthy: boolean; - /** Latest device snapshot observed on this Bridge lifecycle. `null` means - * QQ has not emitted its cache notification since SnowLuma attached. */ - getOnlineClients(): readonly Readonly[] | null; + readonly activePid: number | null; + /** Settles once for this Bridge session after first-login roster fetch. */ + whenRosterWarmupSettled(): Promise; + /** False only when every attached QQ process has a confirmed receive or + * request-path failure. An unarmed watchdog remains true for compatibility. */ + readonly receiveHealthy: boolean; + /** Latest device snapshot observed on this Bridge lifecycle. `null` means + * QQ has not emitted its cache notification since SnowLuma attached. */ + getOnlineClients(): readonly Readonly[] | null; } diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 185817db..f93c10e0 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -1,27 +1,15 @@ -import { - createLogger, - renderTraceBytes, - runWithTraceRequest, -} from '@snowluma/common/logger'; +import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger'; import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout'; import type { PacketInfo } from '@snowluma/common/protocol-types'; import { BridgeEventBus } from '@snowluma/protocol/event-bus'; import { IdentityService } from '@snowluma/protocol/identity-service'; -import { - MSG_PUSH_CMD, - parseMsgPushOrThrow, - SysMsgDedup, -} from '@snowluma/protocol/msg-push'; +import { MSG_PUSH_CMD, parseMsgPushOrThrow, SysMsgDedup } from '@snowluma/protocol/msg-push'; import { KICK_NT_CMD, parseKickNT } from '@snowluma/protocol/kick-nt'; import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline'; import type { OnlineDeviceInfo } from '@snowluma/protocol/events'; import { buildApiHub, type ApiHub } from './apis'; -import { - AiVoiceChatType, - type AiVoiceCategory, - type StrangerStatus, -} from './apis/extras'; +import { AiVoiceChatType, type AiVoiceCategory, type StrangerStatus } from './apis/extras'; import type { BridgeInterface, RosterWarmupResult } from './bridge-interface'; const log = createLogger('Bridge'); @@ -29,517 +17,685 @@ const runtimeLog = createLogger('Bridge.Runtime'); const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1'; export class Bridge implements BridgeInterface { - readonly identity: IdentityService; - private pids_ = new Set(); - private readonly receiveHealthByPid_ = new Map(); - /** Packet senders keyed by their owning QQ process. Keeping the sender and - * PID together is what makes disconnect fallback deterministic: a sender - * can never outlive the PID that supplied it. */ - private readonly packetClientsByPid_ = new Map(); - readonly events = new BridgeEventBus(); - readonly apis: ApiHub; - private readonly pipeline: IncomingPacketPipeline; - private packetClient_: PacketSender | null = null; - private packetClientPid_: number | null = null; - private static readonly UPLOADED_FILE_CACHE_MAX = 1024; - private uploadedFileMeta_ = new Map(); - private clientSeq_ = 100000000 + (Date.now() % 1000000000); - private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0; - // Per-account dedup for QQ NT's already-deduped system pushes (#137). - private readonly sysMsgDedup_ = new SysMsgDedup(); - private onlineClients_: readonly Readonly[] | null = null; - private disposed_ = false; - private rosterWarmupStarted_ = false; - private rosterWarmupSettled_ = false; - private rosterWarmupResult_: RosterWarmupResult | null = null; - private readonly rosterWarmupWaiters_: Array<(result: RosterWarmupResult) => void> = []; + readonly identity: IdentityService; + private pids_ = new Set(); + private readonly receiveHealthByPid_ = new Map(); + /** Packet senders keyed by their owning QQ process. Keeping the sender and + * PID together is what makes disconnect fallback deterministic: a sender + * can never outlive the PID that supplied it. */ + private readonly packetClientsByPid_ = new Map(); + readonly events = new BridgeEventBus(); + readonly apis: ApiHub; + private readonly pipeline: IncomingPacketPipeline; + private packetClient_: PacketSender | null = null; + private packetClientPid_: number | null = null; + private static readonly UPLOADED_FILE_CACHE_MAX = 1024; + private uploadedFileMeta_ = new Map(); + private clientSeq_ = 100000000 + (Date.now() % 1000000000); + private msgRandom_ = (Date.now() & 0xffffffff) >>> 0; + // Per-account dedup for QQ NT's already-deduped system pushes (#137). + private readonly sysMsgDedup_ = new SysMsgDedup(); + private onlineClients_: readonly Readonly[] | null = null; + private disposed_ = false; + private rosterWarmupStarted_ = false; + private rosterWarmupSettled_ = false; + private rosterWarmupResult_: RosterWarmupResult | null = null; + private readonly rosterWarmupWaiters_: Array<(result: RosterWarmupResult) => void> = []; - constructor(identity: IdentityService) { - this.identity = identity; - this.apis = buildApiHub(this); - this.identity.setFetcher({ - fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin), - fetchProfileByUid: (uid) => this.apis.contacts.fetchUserProfileByUid(uid), - fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid), - }); - this.pipeline = new IncomingPacketPipeline({ - identity: this.identity, - events: this.events, - fetchGroupList: async () => { - await this.apis.contacts.fetchGroupList(); - }, - fetchGroupMemberList: async (groupId) => { - await this.apis.contacts.fetchGroupMemberList(groupId); - }, - resolveGroupJoinRequest: async (groupId, uid, subType) => { - const [main, filtered] = await Promise.allSettled([ - this.apis.contacts.fetchGroupRequestsByUid(false), - this.apis.contacts.fetchGroupRequestsByUid(true), - ]); - if (main.status === 'rejected') { - log.warn('group-request enrichment main inbox failed: group=%d uid=%s err=%s', - groupId, uid, main.reason instanceof Error ? main.reason.message : String(main.reason)); - } - if (filtered.status === 'rejected') { - log.warn('group-request enrichment filtered inbox failed: group=%d uid=%s err=%s', - groupId, uid, filtered.reason instanceof Error ? filtered.reason.message : String(filtered.reason)); - } - if (main.status === 'rejected' && filtered.status === 'rejected') { - throw new Error('failed to fetch group requests from both inboxes'); - } - const requests = [ - ...(main.status === 'fulfilled' ? main.value : []), - ...(filtered.status === 'fulfilled' ? filtered.value : []), - ]; - const matches = requests.filter((r) => { - if (r.groupId !== groupId) return false; - return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid; + constructor(identity: IdentityService) { + this.identity = identity; + this.apis = buildApiHub(this); + this.identity.setFetcher({ + fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin), + fetchProfileByUid: (uid) => this.apis.contacts.fetchUserProfileByUid(uid), + fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid), }); - if (subType === 'invite') { - return matches.find((r) => r.notifyType === 1) ?? matches[0] ?? null; - } - return matches.find((r) => r.notifyType === 7) ?? matches[0] ?? null; - }, - resolveGroupInviteCardSequence: async (groupId) => { - const deadline = Date.now() + 1_000; - do { - const sequence = this.apis.contacts.getGroupInviteCardSequence(groupId); - if (sequence) return sequence; - await new Promise(resolve => setTimeout(resolve, 25)); - } while (Date.now() < deadline); - return null; - }, - rememberGroupInviteCardSequence: (groupUin, sequence) => { - this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence); - }, - }); - this.pipeline.registerCmd( - MSG_PUSH_CMD, - (pkt, identity) => parseMsgPushOrThrow( - pkt, - identity, - this.sysMsgDedup_, - ), - ); - this.pipeline.registerCmd(KICK_NT_CMD, parseKickNT); - this.events.on('online_devices_changed', (event) => { - const snapshot = event.devices.map((device) => Object.freeze({ ...device })); - this.onlineClients_ = Object.freeze(snapshot); - log.debug('online-device snapshot updated: uin=%s clients=%d types=%s', - this.identity.uin, snapshot.length, - snapshot.map((device) => device.clientType).join(',')); - }); - } + this.pipeline = new IncomingPacketPipeline({ + identity: this.identity, + events: this.events, + fetchGroupList: async () => { + await this.apis.contacts.fetchGroupList(); + }, + fetchGroupMemberList: async (groupId) => { + await this.apis.contacts.fetchGroupMemberList(groupId); + }, + resolveGroupJoinRequest: async (groupId, uid, subType) => { + const [main, filtered] = await Promise.allSettled([ + this.apis.contacts.fetchGroupRequestsByUid(false), + this.apis.contacts.fetchGroupRequestsByUid(true), + ]); - dispose(): void { - this.disposed_ = true; - this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false }); - this.pids_.clear(); - this.receiveHealthByPid_.clear(); - this.packetClientsByPid_.clear(); - this.packetClient_ = null; - this.packetClientPid_ = null; - this.onlineClients_ = null; - try { - this.identity.close(); - } finally { - // A close failure must remain visible to the caller, but must not leave - // event subscribers attached to a Bridge that Manager already removed. - this.events.clear(); + if (main.status === 'rejected') { + log.warn( + 'group-request enrichment main inbox failed: group=%d uid=%s err=%s', + groupId, + uid, + main.reason instanceof Error ? main.reason.message : String(main.reason), + ); + } + + if (filtered.status === 'rejected') { + log.warn( + 'group-request enrichment filtered inbox failed: group=%d uid=%s err=%s', + groupId, + uid, + filtered.reason instanceof Error + ? filtered.reason.message + : String(filtered.reason), + ); + } + + if (main.status === 'rejected' && filtered.status === 'rejected') { + throw new Error('failed to fetch group requests from both inboxes'); + } + + const requests = [ + ...(main.status === 'fulfilled' ? main.value : []), + ...(filtered.status === 'fulfilled' ? filtered.value : []), + ]; + const matches = requests.filter((r) => { + if (r.groupId !== groupId) { + return false; + } + + return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid; + }); + + if (subType === 'invite') { + return matches.find((r) => r.notifyType === 1) ?? matches[0] ?? null; + } + + return matches.find((r) => r.notifyType === 7) ?? matches[0] ?? null; + }, + resolveGroupInviteCardSequence: async (groupId) => { + const deadline = Date.now() + 1_000; + + do { + const sequence = this.apis.contacts.getGroupInviteCardSequence(groupId); + + if (sequence) { + return sequence; + } + + await new Promise((resolve) => setTimeout(resolve, 25)); + } while (Date.now() < deadline); + + return null; + }, + rememberGroupInviteCardSequence: (groupUin, sequence) => { + this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence); + }, + }); + this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) => + parseMsgPushOrThrow(pkt, identity, this.sysMsgDedup_), + ); + this.pipeline.registerCmd(KICK_NT_CMD, parseKickNT); + this.events.on('online_devices_changed', (event) => { + const snapshot = event.devices.map((device) => Object.freeze({ ...device })); + this.onlineClients_ = Object.freeze(snapshot); + log.debug( + 'online-device snapshot updated: uin=%s clients=%d types=%s', + this.identity.uin, + snapshot.length, + snapshot.map((device) => device.clientType).join(','), + ); + }); } - } - /** Legacy two-step setter retained for external compatibility. It assigns - * the sender to the most recently attached PID when one exists. New - * BridgeManager code uses bindPid() for an atomic transition. */ - setPacketClient(client: PacketSender): void { - this.packetClient_ = client; - const pids = [...this.pids_]; - const pid = pids.length > 0 ? pids[pids.length - 1]! : null; - this.packetClientPid_ = pid; - if (pid !== null) this.packetClientsByPid_.set(pid, client); - this.maybeStartRosterWarmup(); - } - - registerCmd(cmd: string, parser: CmdParser): void { - this.pipeline.registerCmd(cmd, parser); - } - - handlesCmd(cmd: string): boolean { - return this.pipeline.handlesCmd(cmd); - } - - /** Attach a process without a sender. Retained for compatibility; the - * manager uses bindPid() for the atomic PID+sender transition. Re-attaching - * deliberately refreshes recency. */ - attachPid(pid: number): void { - this.pids_.delete(pid); - this.pids_.add(pid); - // A fresh/rebound login starts UNKNOWN-but-compatible. The receive - // watchdog only flips this false after observing QQ's own heartbeat and - // then missing the full stale + confirmation window. - this.receiveHealthByPid_.set(pid, true); - } - - /** Atomically attach a process and make its sender the active sender. - * Set insertion order is the recency order used for fallback. */ - bindPid(pid: number, client: PacketSender): void { - const previousPid = this.packetClientPid_; - const previousClient = this.packetClient_; - this.attachPid(pid); - this.packetClientsByPid_.set(pid, client); - this.packetClient_ = client; - this.packetClientPid_ = pid; - if (previousPid !== pid || previousClient !== client) { - runtimeLog.trace( - 'bridge_sender_fact event=selected uin=%j pid=%d previousPid=%j', - this.identity.uin, - pid, - previousPid, - ); - } - this.maybeStartRosterWarmup(); - } - - /** @internal BridgeManager lookup used when an incoming packet is the first - * observation that a live PID changed UIN. */ - packetClientForPid(pid: number): PacketSender | null { - return this.packetClientsByPid_.get(pid) ?? null; - } - - detachPid(pid: number): void { - this.pids_.delete(pid); - this.receiveHealthByPid_.delete(pid); - this.packetClientsByPid_.delete(pid); - - if (this.packetClientPid_ !== pid) { - // An unscoped legacy sender cannot be associated with a particular PID. - // It is safe to retain while another PID exists, but never after the - // Bridge becomes empty. - if (this.pids_.size === 0) { + dispose(): void { + this.disposed_ = true; + this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false }); + this.pids_.clear(); + this.receiveHealthByPid_.clear(); + this.packetClientsByPid_.clear(); this.packetClient_ = null; this.packetClientPid_ = null; - } - return; + this.onlineClients_ = null; + + try { + this.identity.close(); + } finally { + // A close failure must remain visible to the caller, but must not leave + // event subscribers attached to a Bridge that Manager already removed. + this.events.clear(); + } } - this.selectFallbackPacketClient(pid); - } - hasPid(pid: number): boolean { return this.pids_.has(pid); } - get empty(): boolean { return this.pids_.size === 0; } - get activePid(): number | null { - if (this.packetClientPid_ !== null && this.pids_.has(this.packetClientPid_)) { - return this.packetClientPid_; + /** Legacy two-step setter retained for external compatibility. It assigns + * the sender to the most recently attached PID when one exists. New + * BridgeManager code uses bindPid() for an atomic transition. */ + setPacketClient(client: PacketSender): void { + this.packetClient_ = client; + const pids = [...this.pids_]; + const pid = pids.length > 0 ? pids[pids.length - 1]! : null; + this.packetClientPid_ = pid; + + if (pid !== null) { + this.packetClientsByPid_.set(pid, client); + } + + this.maybeStartRosterWarmup(); } - const pids = [...this.pids_]; - return pids.length > 0 ? pids[pids.length - 1]! : null; - } - get receiveHealthy(): boolean { - for (const pid of this.pids_) { - const healthy = this.receiveHealthByPid_.get(pid); - if (healthy === undefined) { - const message = `Bridge receive-health invariant violated: PID=${pid} has no health state`; - log.error(message); - throw new Error(message); - } - if (healthy) return true; + + registerCmd(cmd: string, parser: CmdParser): void { + this.pipeline.registerCmd(cmd, parser); } - return false; - } - setPidReceiveHealthy(pid: number, healthy: boolean): void { - if (!this.pids_.has(pid)) { - throw new Error(`Bridge receive-health invariant violated: PID=${pid} is not attached`); + + handlesCmd(cmd: string): boolean { + return this.pipeline.handlesCmd(cmd); } - this.receiveHealthByPid_.set(pid, healthy); - } - getOnlineClients(): readonly Readonly[] | null { - return this.onlineClients_; - } - whenRosterWarmupSettled(): Promise { - if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) { - return Promise.resolve(this.rosterWarmupResult_); + /** Attach a process without a sender. Retained for compatibility; the + * manager uses bindPid() for the atomic PID+sender transition. Re-attaching + * deliberately refreshes recency. */ + attachPid(pid: number): void { + this.pids_.delete(pid); + this.pids_.add(pid); + // A fresh/rebound login starts UNKNOWN-but-compatible. The receive + // watchdog only flips this false after observing QQ's own heartbeat and + // then missing the full stale + confirmation window. + this.receiveHealthByPid_.set(pid, true); } - this.maybeStartRosterWarmup(); - return new Promise((resolve) => { - if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) { - resolve(this.rosterWarmupResult_); - return; - } - this.rosterWarmupWaiters_.push(resolve); - }); - } - onPacket(pkt: PacketInfo): Promise { - return this.pipeline.process(pkt); - } + /** Atomically attach a process and make its sender the active sender. + * Set insertion order is the recency order used for fallback. */ + bindPid(pid: number, client: PacketSender): void { + const previousPid = this.packetClientPid_; + const previousClient = this.packetClient_; + this.attachPid(pid); + this.packetClientsByPid_.set(pid, client); + this.packetClient_ = client; + this.packetClientPid_ = pid; - rememberUploadedFile(meta: UploadedFileMeta): void { - if (!meta.fileId) return; - if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) { - // Map iteration order is insertion order — drop the oldest. - const oldest = this.uploadedFileMeta_.keys().next().value; - if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest); + if (previousPid !== pid || previousClient !== client) { + runtimeLog.trace( + 'bridge_sender_fact event=selected uin=%j pid=%d previousPid=%j', + this.identity.uin, + pid, + previousPid, + ); + } + + this.maybeStartRosterWarmup(); } - this.uploadedFileMeta_.set(meta.fileId, meta); - } - recallUploadedFile(fileId: string): UploadedFileMeta | undefined { - if (!fileId) return undefined; - return this.uploadedFileMeta_.get(fileId); - } + /** @internal BridgeManager lookup used when an incoming packet is the first + * observation that a live PID changed UIN. */ + packetClientForPid(pid: number): PacketSender | null { + return this.packetClientsByPid_.get(pid) ?? null; + } - nextClientSequence(): number { - return ++this.clientSeq_; - } + detachPid(pid: number): void { + this.pids_.delete(pid); + this.receiveHealthByPid_.delete(pid); + this.packetClientsByPid_.delete(pid); + + if (this.packetClientPid_ !== pid) { + // An unscoped legacy sender cannot be associated with a particular PID. + // It is safe to retain while another PID exists, but never after the + // Bridge becomes empty. + if (this.pids_.size === 0) { + this.packetClient_ = null; + this.packetClientPid_ = null; + } + + return; + } + + this.selectFallbackPacketClient(pid); + } + hasPid(pid: number): boolean { + return this.pids_.has(pid); + } + get empty(): boolean { + return this.pids_.size === 0; + } + get activePid(): number | null { + if (this.packetClientPid_ !== null && this.pids_.has(this.packetClientPid_)) { + return this.packetClientPid_; + } + + const pids = [...this.pids_]; + return pids.length > 0 ? pids[pids.length - 1]! : null; + } + get receiveHealthy(): boolean { + for (const pid of this.pids_) { + const healthy = this.receiveHealthByPid_.get(pid); + + if (healthy === undefined) { + const message = `Bridge receive-health invariant violated: PID=${pid} has no health state`; + log.error(message); + throw new Error(message); + } + + if (healthy) { + return true; + } + } + + return false; + } + setPidReceiveHealthy(pid: number, healthy: boolean): void { + if (!this.pids_.has(pid)) { + throw new Error(`Bridge receive-health invariant violated: PID=${pid} is not attached`); + } + + this.receiveHealthByPid_.set(pid, healthy); + } + getOnlineClients(): readonly Readonly[] | null { + return this.onlineClients_; + } + + whenRosterWarmupSettled(): Promise { + if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) { + return Promise.resolve(this.rosterWarmupResult_); + } + + this.maybeStartRosterWarmup(); + return new Promise((resolve) => { + if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) { + resolve(this.rosterWarmupResult_); + return; + } + + this.rosterWarmupWaiters_.push(resolve); + }); + } + + onPacket(pkt: PacketInfo): Promise { + return this.pipeline.process(pkt); + } + + rememberUploadedFile(meta: UploadedFileMeta): void { + if (!meta.fileId) { + return; + } + + if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) { + // Map iteration order is insertion order — drop the oldest. + const oldest = this.uploadedFileMeta_.keys().next().value; + + if (oldest !== undefined) { + this.uploadedFileMeta_.delete(oldest); + } + } + + this.uploadedFileMeta_.set(meta.fileId, meta); + } + + recallUploadedFile(fileId: string): UploadedFileMeta | undefined { + if (!fileId) { + return undefined; + } + + return this.uploadedFileMeta_.get(fileId); + } + + nextClientSequence(): number { + return ++this.clientSeq_; + } + + nextMessageRandom(): number { + this.msgRandom_ = (this.msgRandom_ + 0x9e3779b9) >>> 0; + return this.msgRandom_ & 0x7fffffff; + } + async sendRawPacket( + serviceCmd: string, + body: Uint8Array, + timeoutMs = packetTimeoutMs(), + ): Promise { + if (!this.packetClient_) { + return runWithTraceRequest(() => { + const startedAt = Date.now(); + runtimeLog.trace(() => [ + 'bridge_send_start serviceCmd=%j uin=%j activePid=%j timeoutMs=%d length=%d body=%s', + serviceCmd, + this.identity.uin, + this.activePid, + timeoutMs, + body.byteLength, + renderTraceBytes(body), + ]); + log.warn('packet %s dropped: no packet sender attached', serviceCmd); + runtimeLog.trace(() => [ + 'bridge_send_terminal serviceCmd=%j uin=%j activePid=%j outcome=dropped reason=no_sender length=%d body=%s elapsedMs=%d', + serviceCmd, + this.identity.uin, + this.activePid, + body.byteLength, + renderTraceBytes(body), + Date.now() - startedAt, + ]); + return { + success: false, + gotResponse: false, + errorCode: -1, + errorMessage: 'no packet sender attached', + responseData: null, + }; + }); + } - nextMessageRandom(): number { - this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0; - return this.msgRandom_ & 0x7FFFFFFF; - } - async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = packetTimeoutMs()): Promise { - if (!this.packetClient_) { - return runWithTraceRequest(() => { const startedAt = Date.now(); - runtimeLog.trace(() => [ - 'bridge_send_start serviceCmd=%j uin=%j activePid=%j timeoutMs=%d length=%d body=%s', - serviceCmd, - this.identity.uin, - this.activePid, - timeoutMs, - body.byteLength, - renderTraceBytes(body), - ]); - log.warn('packet %s dropped: no packet sender attached', serviceCmd); - runtimeLog.trace(() => [ - 'bridge_send_terminal serviceCmd=%j uin=%j activePid=%j outcome=dropped reason=no_sender length=%d body=%s elapsedMs=%d', - serviceCmd, - this.identity.uin, - this.activePid, - body.byteLength, - renderTraceBytes(body), - Date.now() - startedAt, - ]); - return { - success: false, gotResponse: false, errorCode: -1, - errorMessage: 'no packet sender attached', responseData: null, - }; - }); - } - const startedAt = Date.now(); - const result = await this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs); - const elapsed = Date.now() - startedAt; - const respLen = result.responseData ? result.responseData.length : 0; - if (!result.success || result.errorCode !== 0) { - // QQ-side rejection or transport failure — the usual root cause when an - // action misbehaves. Warn (persisted) with cmd + code so a user's log - // shows exactly where the chain broke. - log.warn('packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)', - serviceCmd, result.errorCode, result.gotResponse, - result.errorMessage ?? '', this.identity.uin, body.length, elapsed); - } else { - // Happy path — memory-only trace so the full chain shows under the - // request's [req#N] when debugging, without flooding disk. - log.trace(() => [`packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`]); - } - return result; - } - - private selectFallbackPacketClient(detachedPid: number): void { - const pids = [...this.pids_]; - for (let index = pids.length - 1; index >= 0; index -= 1) { - const fallbackPid = pids[index]!; - const fallback = this.packetClientsByPid_.get(fallbackPid); - if (!fallback) continue; - - this.packetClient_ = fallback; - this.packetClientPid_ = fallbackPid; - runtimeLog.trace( - 'bridge_sender_fact event=fallback uin=%j detachedPid=%d fallbackPid=%d', - this.identity.uin, - detachedPid, - fallbackPid, - ); - log.debug( - 'packet sender fallback: UIN=%s detached PID=%d fallback PID=%d', - this.identity.uin, - detachedPid, - fallbackPid, - ); - return; - } - - this.packetClient_ = null; - this.packetClientPid_ = null; - if (this.pids_.size > 0) { - log.warn( - 'packet sender unavailable after PID detach: UIN=%s detached PID=%d remaining PIDs=%d', - this.identity.uin, - detachedPid, - this.pids_.size, - ); - } - } - async resolveUserUid(uin: number, groupId?: number): Promise { - return this.identity.resolveUid(uin, groupId); - } - - private maybeStartRosterWarmup(): void { - if (this.disposed_ || this.rosterWarmupStarted_ || !this.packetClient_) return; - this.rosterWarmupStarted_ = true; - if (!this.identity.nickname) this.identity.nickname = this.identity.uin; - void this.runRosterWarmup().then( - (result) => this.settleRosterWarmup(this.disposed_ ? { friendsLoaded: false, groupsLoaded: false } : result), - (err) => { - log.warn( - 'roster warmup failed: uin=%s err=%s', - this.identity.uin, - err instanceof Error ? (err.stack ?? err.message) : String(err), + const result = await this.packetClient_.sendPacket( + serviceCmd, + Buffer.from(body), + timeoutMs, ); - this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false }); - }, - ); - } + const elapsed = Date.now() - startedAt; + const respLen = result.responseData ? result.responseData.length : 0; - private settleRosterWarmup(result: RosterWarmupResult): void { - if (this.rosterWarmupSettled_) return; - this.rosterWarmupSettled_ = true; - this.rosterWarmupResult_ = result; - const waiters = this.rosterWarmupWaiters_.splice(0); - for (const resolve of waiters) resolve(result); - } - - private stillOpen(): boolean { - return !this.disposed_; - } - - private async runRosterWarmup(): Promise { - const uin = this.identity.uin; - const selfUin = parseInt(uin, 10) || 0; - let selfResolved = false; - let friendsLoaded = false; - - try { - const friends = await this.apis.contacts.fetchFriendList(); - if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false }; - friendsLoaded = true; - log.info('friends loaded: UIN=%s count=%d', uin, friends.length); - - for (const friend of friends) { - if (friend.uin === selfUin) { - this.identity.setSelfProfile({ - uin: friend.uin, uid: friend.uid, - nickname: friend.nickname || uin, - remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0, - qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0, - }); - this.identity.nickname = friend.nickname || uin; - log.debug('self info: UIN=%s uid=%s nickname=%s', uin, friend.uid, friend.nickname ?? ''); - selfResolved = true; - break; + if (!result.success || result.errorCode !== 0) { + // QQ-side rejection or transport failure — the usual root cause when an + // action misbehaves. Warn (persisted) with cmd + code so a user's log + // shows exactly where the chain broke. + log.warn( + 'packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)', + serviceCmd, + result.errorCode, + result.gotResponse, + result.errorMessage ?? '', + this.identity.uin, + body.length, + elapsed, + ); + } else { + // Happy path — memory-only trace so the full chain shows under the + // request's [req#N] when debugging, without flooding disk. + log.trace(() => [ + `packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`, + ]); } - } - } catch (e) { - if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false }; - log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e)); + + return result; } - if (!selfResolved && selfUin > 0 && this.stillOpen()) { - try { - const profile = await this.apis.contacts.fetchUserProfile(selfUin); - if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false }; - this.identity.setSelfProfile(profile); - this.identity.nickname = profile.nickname || uin; - log.debug('self info via profile: UIN=%s uid=%s nickname=%s', - uin, profile.uid, profile.nickname); - } catch (e) { - if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false }; - log.warn('failed to load self profile for UIN %s: %s', - uin, e instanceof Error ? e.message : String(e)); - } - } + private selectFallbackPacketClient(detachedPid: number): void { + const pids = [...this.pids_]; - let groups: { groupId: number }[] = []; - let groupsLoaded = false; - try { - groups = await this.apis.contacts.fetchGroupList(); - if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false }; - groupsLoaded = true; - log.info('groups loaded: UIN=%s count=%d', uin, groups.length); - } catch (e) { - if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false }; - log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e)); - } + for (let index = pids.length - 1; index >= 0; index -= 1) { + const fallbackPid = pids[index]!; + const fallback = this.packetClientsByPid_.get(fallbackPid); - let loadedGroupCount = 0; - let loadedMemberCount = 0; - let failedGroupCount = 0; - for (const group of groups) { - if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false }; - try { - const members = await this.apis.contacts.fetchGroupMemberList(group.groupId); - if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false }; - loadedGroupCount += 1; - loadedMemberCount += members.length; - if (VERBOSE_WARMUP) { - log.debug('members loaded: group=%d count=%d', group.groupId, members.length); + if (!fallback) { + continue; + } + + this.packetClient_ = fallback; + this.packetClientPid_ = fallbackPid; + runtimeLog.trace( + 'bridge_sender_fact event=fallback uin=%j detachedPid=%d fallbackPid=%d', + this.identity.uin, + detachedPid, + fallbackPid, + ); + log.debug( + 'packet sender fallback: UIN=%s detached PID=%d fallback PID=%d', + this.identity.uin, + detachedPid, + fallbackPid, + ); + return; } - } catch (e) { - if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false }; - failedGroupCount += 1; - log.warn('failed to load members for group %d: %s', group.groupId, e instanceof Error ? e.message : String(e)); - } + + this.packetClient_ = null; + this.packetClientPid_ = null; + + if (this.pids_.size > 0) { + log.warn( + 'packet sender unavailable after PID detach: UIN=%s detached PID=%d remaining PIDs=%d', + this.identity.uin, + detachedPid, + this.pids_.size, + ); + } + } + async resolveUserUid(uin: number, groupId?: number): Promise { + return this.identity.resolveUid(uin, groupId); } - if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false }; - log.info( - 'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d', - uin, - loadedGroupCount, - groups.length, - loadedMemberCount, - failedGroupCount, - ); - return { friendsLoaded, groupsLoaded }; - } + private maybeStartRosterWarmup(): void { + if (this.disposed_ || this.rosterWarmupStarted_ || !this.packetClient_) { + return; + } + + this.rosterWarmupStarted_ = true; + + if (!this.identity.nickname) { + this.identity.nickname = this.identity.uin; + } + + void this.runRosterWarmup().then( + (result) => + this.settleRosterWarmup( + this.disposed_ ? { friendsLoaded: false, groupsLoaded: false } : result, + ), + (err) => { + log.warn( + 'roster warmup failed: uin=%s err=%s', + this.identity.uin, + err instanceof Error ? (err.stack ?? err.message) : String(err), + ); + this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false }); + }, + ); + } + + private settleRosterWarmup(result: RosterWarmupResult): void { + if (this.rosterWarmupSettled_) { + return; + } + + this.rosterWarmupSettled_ = true; + this.rosterWarmupResult_ = result; + const waiters = this.rosterWarmupWaiters_.splice(0); + + for (const resolve of waiters) { + resolve(result); + } + } + + private stillOpen(): boolean { + return !this.disposed_; + } + + private async runRosterWarmup(): Promise { + const uin = this.identity.uin; + const selfUin = parseInt(uin, 10) || 0; + let selfResolved = false; + let friendsLoaded = false; + + try { + const friends = await this.apis.contacts.fetchFriendList(); + + if (!this.stillOpen()) { + return { friendsLoaded: false, groupsLoaded: false }; + } + + friendsLoaded = true; + log.info('friends loaded: UIN=%s count=%d', uin, friends.length); + + for (const friend of friends) { + if (friend.uin === selfUin) { + this.identity.setSelfProfile({ + uin: friend.uin, + uid: friend.uid, + nickname: friend.nickname || uin, + remark: '', + qid: '', + sex: 'unknown', + age: 0, + sign: '', + avatar: '', + level: 0, + qidianMasterFlag: 0, + qidianCrewFlag: 0, + qidianCrewFlag2: 0, + }); + this.identity.nickname = friend.nickname || uin; + log.debug( + 'self info: UIN=%s uid=%s nickname=%s', + uin, + friend.uid, + friend.nickname ?? '', + ); + selfResolved = true; + break; + } + } + } catch (e) { + if (!this.stillOpen()) { + return { friendsLoaded: false, groupsLoaded: false }; + } + + log.warn( + 'failed to load friends for UIN %s: %s', + uin, + e instanceof Error ? e.message : String(e), + ); + } + + if (!selfResolved && selfUin > 0 && this.stillOpen()) { + try { + const profile = await this.apis.contacts.fetchUserProfile(selfUin); + + if (!this.stillOpen()) { + return { friendsLoaded: false, groupsLoaded: false }; + } + + this.identity.setSelfProfile(profile); + this.identity.nickname = profile.nickname || uin; + log.debug( + 'self info via profile: UIN=%s uid=%s nickname=%s', + uin, + profile.uid, + profile.nickname, + ); + } catch (e) { + if (!this.stillOpen()) { + return { friendsLoaded: false, groupsLoaded: false }; + } + + log.warn( + 'failed to load self profile for UIN %s: %s', + uin, + e instanceof Error ? e.message : String(e), + ); + } + } + + let groups: { groupId: number }[] = []; + let groupsLoaded = false; + + try { + groups = await this.apis.contacts.fetchGroupList(); + + if (!this.stillOpen()) { + return { friendsLoaded: false, groupsLoaded: false }; + } + + groupsLoaded = true; + log.info('groups loaded: UIN=%s count=%d', uin, groups.length); + } catch (e) { + if (!this.stillOpen()) { + return { friendsLoaded: false, groupsLoaded: false }; + } + + log.warn( + 'failed to load groups for UIN %s: %s', + uin, + e instanceof Error ? e.message : String(e), + ); + } + + let loadedGroupCount = 0; + let loadedMemberCount = 0; + let failedGroupCount = 0; + + for (const group of groups) { + if (!this.stillOpen()) { + return { friendsLoaded: false, groupsLoaded: false }; + } + + try { + const members = await this.apis.contacts.fetchGroupMemberList(group.groupId); + + if (!this.stillOpen()) { + return { friendsLoaded: false, groupsLoaded: false }; + } + + loadedGroupCount += 1; + loadedMemberCount += members.length; + + if (VERBOSE_WARMUP) { + log.debug('members loaded: group=%d count=%d', group.groupId, members.length); + } + } catch (e) { + if (!this.stillOpen()) { + return { friendsLoaded: false, groupsLoaded: false }; + } + + failedGroupCount += 1; + log.warn( + 'failed to load members for group %d: %s', + group.groupId, + e instanceof Error ? e.message : String(e), + ); + } + } + + if (!this.stillOpen()) { + return { friendsLoaded: false, groupsLoaded: false }; + } + + log.info( + 'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d', + uin, + loadedGroupCount, + groups.length, + loadedMemberCount, + failedGroupCount, + ); + return { friendsLoaded, groupsLoaded }; + } } export interface SendMessageReceipt { - messageId: number; - sequence: number; - clientSequence: number; - random: number; - timestamp: number; + messageId: number; + sequence: number; + clientSequence: number; + random: number; + timestamp: number; } export interface UploadedFileMeta { - fileId: string; - scope: 'group' | 'private'; - /** Group id if scope='group', else `undefined`. */ - groupId?: number; - /** Friend uin if scope='private', else `undefined`. */ - userId?: number; - fileName: string; - fileSize: number; - fileMd5: Uint8Array; - fileSha1: Uint8Array; - /** Server-issued hash returned alongside the upload (private only). */ - fileHash?: string; - /** Insert time — used to evict the oldest entry when the cache fills. */ - rememberedAt: number; + fileId: string; + scope: 'group' | 'private'; + /** Group id if scope='group', else `undefined`. */ + groupId?: number; + /** Friend uin if scope='private', else `undefined`. */ + userId?: number; + fileName: string; + fileSize: number; + fileMd5: Uint8Array; + fileSha1: Uint8Array; + /** Server-issued hash returned alongside the upload (private only). */ + fileHash?: string; + /** Insert time — used to evict the oldest entry when the cache fills. */ + rememberedAt: number; } export interface DownloadRKeyInfo { - rkey: string; - ttlSeconds: number; - storeId: number; - createTime: number; - type: number; + rkey: string; + ttlSeconds: number; + storeId: number; + createTime: number; + type: number; } export interface ClientKeyInfo { - clientKey: string; - expireTime: string; - keyIndex: string + clientKey: string; + expireTime: string; + keyIndex: string; } export { AiVoiceChatType }; export type { AiVoiceCategory, StrangerStatus }; diff --git a/packages/core/src/bridge/manager.ts b/packages/core/src/bridge/manager.ts index 336c36d3..4a9c42c2 100644 --- a/packages/core/src/bridge/manager.ts +++ b/packages/core/src/bridge/manager.ts @@ -1,8 +1,4 @@ -import { - createLogger, - renderTraceBytes, - runWithTraceRequest, -} from '@snowluma/common/logger'; +import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger'; import type { PacketSender } from '@snowluma/common/packet-sender'; import type { PacketInfo } from '@snowluma/common/protocol-types'; import { isRealUin } from '@snowluma/common/uin'; @@ -13,7 +9,7 @@ export type SessionStartedCallback = (uin: string, bridge: Bridge) => void; export type SessionClosedCallback = (uin: string, bridge: Bridge) => void; interface QQSession { - bridge: Bridge; + bridge: Bridge; } const log = createLogger('Bridge'); @@ -21,366 +17,393 @@ const packetLog = createLogger('Bridge.Packet'); const runtimeLog = createLogger('Bridge.Runtime'); export class BridgeManager { - private sessions_ = new Map(); - private pidToUin_ = new Map(); + private sessions_ = new Map(); + private pidToUin_ = new Map(); - private sessionStartedListeners_: SessionStartedCallback[] = []; - private sessionClosedListeners_: SessionClosedCallback[] = []; + private sessionStartedListeners_: SessionStartedCallback[] = []; + private sessionClosedListeners_: SessionClosedCallback[] = []; - /** Additive subscription: every observer (OneBotManager, NotificationManager, - * …) receives every session edge. (Was a single `set*Callback` setter — - * converted to N listeners so a second observer can't clobber the first.) - * The close edge now carries the bridge too, since callers read the last - * nickname before it is disposed. */ - addSessionStartedListener(cb: SessionStartedCallback): void { - this.sessionStartedListeners_.push(cb); - } - addSessionClosedListener(cb: SessionClosedCallback): void { - this.sessionClosedListeners_.push(cb); - } - - private fireSessionStarted(uin: string, bridge: Bridge): void { - for (const cb of this.sessionStartedListeners_) { - try { - cb(uin, bridge); - } catch (err) { - log.warn('session-started listener threw: %s', err instanceof Error ? err.message : String(err)); - } + /** Additive subscription: every observer (OneBotManager, NotificationManager, + * …) receives every session edge. (Was a single `set*Callback` setter — + * converted to N listeners so a second observer can't clobber the first.) + * The close edge now carries the bridge too, since callers read the last + * nickname before it is disposed. */ + addSessionStartedListener(cb: SessionStartedCallback): void { + this.sessionStartedListeners_.push(cb); } - } - - private fireSessionClosed(uin: string, bridge: Bridge): void { - for (const cb of this.sessionClosedListeners_) { - try { - cb(uin, bridge); - } catch (err) { - log.warn('session-closed listener threw: %s', err instanceof Error ? err.message : String(err)); - } + addSessionClosedListener(cb: SessionClosedCallback): void { + this.sessionClosedListeners_.push(cb); } - } - onPidDisconnected(pid: number): void { - const uin = this.pidToUin_.get(pid); - if (!uin) return; - - runWithTraceRequest(() => { - const startedAt = Date.now(); - runtimeLog.trace( - 'bridge_detach_start pid=%d uin=%j', - pid, - uin, - ); - try { - const closed = this.detachPidFromSession(pid, uin); - const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null; - if (closed) { - runtimeLog.trace( - 'bridge_detach_branch pid=%d uin=%j branch=session_closed', - pid, - uin, - ); + private fireSessionStarted(uin: string, bridge: Bridge): void { + for (const cb of this.sessionStartedListeners_) { + try { + cb(uin, bridge); + } catch (err) { + log.warn( + 'session-started listener threw: %s', + err instanceof Error ? err.message : String(err), + ); + } } - runtimeLog.trace( - 'bridge_detach_terminal pid=%d uin=%j outcome=completed reason=%s activePid=%j elapsedMs=%d', - pid, - uin, - closed ? 'session_closed' : 'pid_detached', - activePid, - Date.now() - startedAt, - ); - } catch (error) { - runtimeLog.trace( - 'bridge_detach_terminal pid=%d uin=%j outcome=failed reason=invariant_violation error=%j elapsedMs=%d', - pid, - uin, - error instanceof Error ? error.message : String(error), - Date.now() - startedAt, - ); - throw error; - } - }); - } - - onPidReceiveHealthChanged(pid: number, healthy: boolean): void { - const uin = this.pidToUin_.get(pid); - if (!uin) { - const message = `BridgeManager invariant violated: receive health for unmapped PID=${pid}`; - log.error(message); - throw new Error(message); } - const session = this.sessions_.get(uin); - if (!session || !session.bridge.hasPid(pid)) { - const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`; - log.error(message); - throw new Error(message); + private fireSessionClosed(uin: string, bridge: Bridge): void { + for (const cb of this.sessionClosedListeners_) { + try { + cb(uin, bridge); + } catch (err) { + log.warn( + 'session-closed listener threw: %s', + err instanceof Error ? err.message : String(err), + ); + } + } } - session.bridge.setPidReceiveHealthy(pid, healthy); - } - onHookLogin(pid: number, uin: string, packetClient: PacketSender): void { - if (!isRealUin(uin)) return; + onPidDisconnected(pid: number): void { + const uin = this.pidToUin_.get(pid); - runWithTraceRequest(() => { - const startedAt = Date.now(); - const previousUin = this.pidToUin_.get(pid) ?? null; - runtimeLog.trace( - 'bridge_binding_start pid=%d uin=%j source=login previousUin=%j', - pid, - uin, - previousUin, - ); + if (!uin) { + return; + } + + runWithTraceRequest(() => { + const startedAt = Date.now(); + runtimeLog.trace('bridge_detach_start pid=%d uin=%j', pid, uin); + + try { + const closed = this.detachPidFromSession(pid, uin); + const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null; + + if (closed) { + runtimeLog.trace( + 'bridge_detach_branch pid=%d uin=%j branch=session_closed', + pid, + uin, + ); + } + + runtimeLog.trace( + 'bridge_detach_terminal pid=%d uin=%j outcome=completed reason=%s activePid=%j elapsedMs=%d', + pid, + uin, + closed ? 'session_closed' : 'pid_detached', + activePid, + Date.now() - startedAt, + ); + } catch (error) { + runtimeLog.trace( + 'bridge_detach_terminal pid=%d uin=%j outcome=failed reason=invariant_violation error=%j elapsedMs=%d', + pid, + uin, + error instanceof Error ? error.message : String(error), + Date.now() - startedAt, + ); + throw error; + } + }); + } + + onPidReceiveHealthChanged(pid: number, healthy: boolean): void { + const uin = this.pidToUin_.get(pid); + + if (!uin) { + const message = `BridgeManager invariant violated: receive health for unmapped PID=${pid}`; + log.error(message); + throw new Error(message); + } + + const session = this.sessions_.get(uin); + + if (!session || !session.bridge.hasPid(pid)) { + const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`; + log.error(message); + throw new Error(message); + } + + session.bridge.setPidReceiveHealthy(pid, healthy); + } + + onHookLogin(pid: number, uin: string, packetClient: PacketSender): void { + if (!isRealUin(uin)) { + return; + } + + runWithTraceRequest(() => { + const startedAt = Date.now(); + const previousUin = this.pidToUin_.get(pid) ?? null; + runtimeLog.trace( + 'bridge_binding_start pid=%d uin=%j source=login previousUin=%j', + pid, + uin, + previousUin, + ); + + try { + const { session, created } = this.bindPid(pid, uin, packetClient, 'login'); + + if (previousUin && previousUin !== uin) { + runtimeLog.trace( + 'bridge_binding_branch pid=%d uin=%j branch=account_rebind previousUin=%j', + pid, + uin, + previousUin, + ); + const previousSession = this.sessions_.get(previousUin); + runtimeLog.trace( + 'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j', + pid, + uin, + previousSession ? 'previous_session_retained' : 'previous_session_closed', + previousUin, + previousSession?.bridge.activePid ?? null, + ); + } + + if (created) { + runtimeLog.trace( + 'bridge_binding_branch pid=%d uin=%j branch=session_created', + pid, + uin, + ); + log.debug('session started: UIN=%s', uin); + this.fireSessionStarted(uin, session.bridge); + } + + runtimeLog.trace( + 'bridge_binding_terminal pid=%d uin=%j source=login outcome=completed reason=%s created=%s activePid=%j elapsedMs=%d', + pid, + uin, + previousUin && previousUin !== uin ? 'rebound' : 'bound', + created, + session.bridge.activePid, + Date.now() - startedAt, + ); + } catch (error) { + runtimeLog.trace( + 'bridge_binding_terminal pid=%d uin=%j source=login outcome=failed reason=binding_failed error=%j elapsedMs=%d', + pid, + uin, + error instanceof Error ? error.message : String(error), + Date.now() - startedAt, + ); + throw error; + } + }); + } + + onPacket(pkt: PacketInfo): void { + runWithTraceRequest(() => this.onPacketInContext(pkt)); + } + + private onPacketInContext(pkt: PacketInfo): void { + const startedAt = Date.now(); + packetLog.trace(() => [ + 'packet_push serviceCmd=%j seqId=%d retCode=%d fromClient=%s pid=%d uin=%j length=%d body=%s', + pkt.serviceCmd, + pkt.seqId, + pkt.retCode, + pkt.fromClient, + pkt.pid, + pkt.uin, + pkt.body.byteLength, + renderTraceBytes(pkt.body), + ]); + + if (!pkt.uin || !isRealUin(pkt.uin)) { + packetLog.trace(() => [ + 'packet_terminal serviceCmd=%j seqId=%d outcome=dropped reason=invalid_uin events=0 dispatched=0 elapsedMs=%d', + pkt.serviceCmd, + pkt.seqId, + Date.now() - startedAt, + ]); + return; + } + + const uin = pkt.uin; + + let completion: Promise; + let handedToPipeline = false; + + try { + // A packet may be the first trustworthy observation that a live PID moved + // to another UIN. Apply the exact same ownership transition as login so a + // PID can never remain attached to two Bridges. + const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null; + const { session, created } = client + ? this.bindPid(pkt.pid, uin, client, 'packet') + : this.ensureSession(uin); + + // Notify session started on first real packet + if (created) { + log.debug('session started: UIN=%s', uin); + this.fireSessionStarted(uin, session.bridge); + } + + // Dispatch packet to bridge. The pipeline preserves synchronous parsing and + // dispatch; its promise only marks completion of any async enrichment. + handedToPipeline = true; + completion = session.bridge.onPacket(pkt); + } catch (error) { + this.tracePacketFailure( + pkt, + startedAt, + handedToPipeline ? 'pipeline_failed' : 'routing_failed', + error, + ); + throw error; + } + + void completion.catch((error) => { + this.tracePacketFailure(pkt, startedAt, 'pipeline_failed', error); + }); + } + + private tracePacketFailure( + pkt: PacketInfo, + startedAt: number, + reason: 'routing_failed' | 'pipeline_failed', + error: unknown, + ): void { + packetLog.trace(() => [ + 'packet_terminal serviceCmd=%j seqId=%d outcome=failed reason=%s error=%j events=0 dispatched=0 elapsedMs=%d', + pkt.serviceCmd, + pkt.seqId, + reason, + error instanceof Error ? error.message : String(error), + Date.now() - startedAt, + ]); + log.error( + 'packet %s failed for %s: %s', + reason === 'routing_failed' ? 'routing' : 'pipeline', + pkt.serviceCmd, + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + } + + /** Bind PID + sender as one state transition. If the PID changed accounts, + * the old Bridge is fully detached (and, when empty, closed) before the new + * Bridge is created. */ + private bindPid( + pid: number, + uin: string, + packetClient: PacketSender, + source: 'login' | 'packet', + ): { session: QQSession; created: boolean } { + const previousUin = this.pidToUin_.get(pid); - try { - const { session, created } = this.bindPid(pid, uin, packetClient, 'login'); if (previousUin && previousUin !== uin) { - runtimeLog.trace( - 'bridge_binding_branch pid=%d uin=%j branch=account_rebind previousUin=%j', - pid, - uin, - previousUin, - ); - const previousSession = this.sessions_.get(previousUin); - runtimeLog.trace( - 'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j', - pid, - uin, - previousSession ? 'previous_session_retained' : 'previous_session_closed', - previousUin, - previousSession?.bridge.activePid ?? null, - ); + log.warn( + 'PID ownership changed: PID=%d UIN=%s -> UIN=%s source=%s', + pid, + previousUin, + uin, + source, + ); + this.detachPidFromSession(pid, previousUin); } - if (created) { - runtimeLog.trace( - 'bridge_binding_branch pid=%d uin=%j branch=session_created', - pid, - uin, - ); - log.debug('session started: UIN=%s', uin); - this.fireSessionStarted(uin, session.bridge); + const result = this.ensureSession(uin); + result.session.bridge.bindPid(pid, packetClient); + this.pidToUin_.set(pid, uin); + return result; + } + + private packetClientForPid(pid: number): PacketSender | null { + const uin = this.pidToUin_.get(pid); + + if (!uin) { + return null; } - runtimeLog.trace( - 'bridge_binding_terminal pid=%d uin=%j source=login outcome=completed reason=%s created=%s activePid=%j elapsedMs=%d', - pid, - uin, - previousUin && previousUin !== uin ? 'rebound' : 'bound', - created, - session.bridge.activePid, - Date.now() - startedAt, - ); - } catch (error) { - runtimeLog.trace( - 'bridge_binding_terminal pid=%d uin=%j source=login outcome=failed reason=binding_failed error=%j elapsedMs=%d', - pid, - uin, - error instanceof Error ? error.message : String(error), - Date.now() - startedAt, - ); - throw error; - } - }); - } - onPacket(pkt: PacketInfo): void { - runWithTraceRequest(() => this.onPacketInContext(pkt)); - } + const session = this.sessions_.get(uin); - private onPacketInContext(pkt: PacketInfo): void { - const startedAt = Date.now(); - packetLog.trace(() => [ - 'packet_push serviceCmd=%j seqId=%d retCode=%d fromClient=%s pid=%d uin=%j length=%d body=%s', - pkt.serviceCmd, - pkt.seqId, - pkt.retCode, - pkt.fromClient, - pkt.pid, - pkt.uin, - pkt.body.byteLength, - renderTraceBytes(pkt.body), - ]); - if (!pkt.uin || !isRealUin(pkt.uin)) { - packetLog.trace(() => [ - 'packet_terminal serviceCmd=%j seqId=%d outcome=dropped reason=invalid_uin events=0 dispatched=0 elapsedMs=%d', - pkt.serviceCmd, - pkt.seqId, - Date.now() - startedAt, - ]); - return; - } - const uin = pkt.uin; + if (!session) { + const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`; + log.error(message); + throw new Error(message); + } - let completion: Promise; - let handedToPipeline = false; - try { - // A packet may be the first trustworthy observation that a live PID moved - // to another UIN. Apply the exact same ownership transition as login so a - // PID can never remain attached to two Bridges. - const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null; - const { session, created } = client - ? this.bindPid(pkt.pid, uin, client, 'packet') - : this.ensureSession(uin); + const packetClient = session.bridge.packetClientForPid(pid); - // Notify session started on first real packet - if (created) { - log.debug('session started: UIN=%s', uin); - this.fireSessionStarted(uin, session.bridge); - } + if (packetClient) { + return packetClient; + } - // Dispatch packet to bridge. The pipeline preserves synchronous parsing and - // dispatch; its promise only marks completion of any async enrichment. - handedToPipeline = true; - completion = session.bridge.onPacket(pkt); - } catch (error) { - this.tracePacketFailure( - pkt, - startedAt, - handedToPipeline - ? 'pipeline_failed' - : 'routing_failed', - error, - ); - throw error; - } - void completion.catch((error) => { - this.tracePacketFailure( - pkt, - startedAt, - 'pipeline_failed', - error, - ); - }); - } - - private tracePacketFailure( - pkt: PacketInfo, - startedAt: number, - reason: 'routing_failed' | 'pipeline_failed', - error: unknown, - ): void { - packetLog.trace(() => [ - 'packet_terminal serviceCmd=%j seqId=%d outcome=failed reason=%s error=%j events=0 dispatched=0 elapsedMs=%d', - pkt.serviceCmd, - pkt.seqId, - reason, - error instanceof Error ? error.message : String(error), - Date.now() - startedAt, - ]); - log.error( - 'packet %s failed for %s: %s', - reason === 'routing_failed' - ? 'routing' - : 'pipeline', - pkt.serviceCmd, - error instanceof Error ? (error.stack ?? error.message) : String(error), - ); - } - - /** Bind PID + sender as one state transition. If the PID changed accounts, - * the old Bridge is fully detached (and, when empty, closed) before the new - * Bridge is created. */ - private bindPid( - pid: number, - uin: string, - packetClient: PacketSender, - source: 'login' | 'packet', - ): { session: QQSession; created: boolean } { - const previousUin = this.pidToUin_.get(pid); - if (previousUin && previousUin !== uin) { - log.warn( - 'PID ownership changed: PID=%d UIN=%s -> UIN=%s source=%s', - pid, - previousUin, - uin, - source, - ); - this.detachPidFromSession(pid, previousUin); + const message = `BridgeManager invariant violated: PID=${pid} has no sender in UIN=${uin} session`; + log.error(message); + throw new Error(message); } - const result = this.ensureSession(uin); - result.session.bridge.bindPid(pid, packetClient); - this.pidToUin_.set(pid, uin); - return result; - } + private detachPidFromSession(pid: number, uin: string): boolean { + const mappedUin = this.pidToUin_.get(pid); - private packetClientForPid(pid: number): PacketSender | null { - const uin = this.pidToUin_.get(pid); - if (!uin) return null; + if (mappedUin !== uin) { + const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`; + log.error(message); + throw new Error(message); + } - const session = this.sessions_.get(uin); - if (!session) { - const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`; - log.error(message); - throw new Error(message); + const session = this.sessions_.get(uin); + + if (!session) { + const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`; + log.error(message); + throw new Error(message); + } + + if (!session.bridge.hasPid(pid)) { + const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`; + log.error(message); + throw new Error(message); + } + + if (!session.bridge.packetClientForPid(pid)) { + const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`; + log.error(message); + throw new Error(message); + } + + // Validation is complete. Mutate both sides only after the ownership + // invariant is known to hold, so a fail-fast error preserves the evidence. + this.pidToUin_.delete(pid); + session.bridge.detachPid(pid); + + if (!session.bridge.empty) { + return false; + } + + this.sessions_.delete(uin); + log.debug('session closed: UIN=%s', uin); + // Fire before dispose() so listeners can still read bridge.identity. + this.fireSessionClosed(uin, session.bridge); + session.bridge.dispose(); + return true; } - const packetClient = session.bridge.packetClientForPid(pid); - if (packetClient) return packetClient; + private ensureSession(uin: string): { session: QQSession; created: boolean } { + let session = this.sessions_.get(uin); - const message = `BridgeManager invariant violated: PID=${pid} has no sender in UIN=${uin} session`; - log.error(message); - throw new Error(message); - } + if (session) { + return { session, created: false }; + } - private detachPidFromSession(pid: number, uin: string): boolean { - const mappedUin = this.pidToUin_.get(pid); - if (mappedUin !== uin) { - const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`; - log.error(message); - throw new Error(message); + const bridge = new Bridge(IdentityService.openForUin(uin)); + session = { bridge }; + this.sessions_.set(uin, session); + + // Each downstream consumer (e.g. OneBotInstance) subscribes to + // `bridge.events` directly via the per-kind bus — there is no longer a + // generic firehose to wire here. + return { session, created: true }; } - const session = this.sessions_.get(uin); - if (!session) { - const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`; - log.error(message); - throw new Error(message); + getSession(uin: string): QQSession | null { + return this.sessions_.get(uin) ?? null; } - if (!session.bridge.hasPid(pid)) { - const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`; - log.error(message); - throw new Error(message); + get sessions(): Map { + return this.sessions_; } - if (!session.bridge.packetClientForPid(pid)) { - const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`; - log.error(message); - throw new Error(message); - } - - // Validation is complete. Mutate both sides only after the ownership - // invariant is known to hold, so a fail-fast error preserves the evidence. - this.pidToUin_.delete(pid); - session.bridge.detachPid(pid); - if (!session.bridge.empty) return false; - - this.sessions_.delete(uin); - log.debug('session closed: UIN=%s', uin); - // Fire before dispose() so listeners can still read bridge.identity. - this.fireSessionClosed(uin, session.bridge); - session.bridge.dispose(); - return true; - } - - private ensureSession(uin: string): { session: QQSession; created: boolean } { - let session = this.sessions_.get(uin); - if (session) return { session, created: false }; - - const bridge = new Bridge(IdentityService.openForUin(uin)); - session = { bridge }; - this.sessions_.set(uin, session); - - // Each downstream consumer (e.g. OneBotInstance) subscribes to - // `bridge.events` directly via the per-kind bus — there is no longer a - // generic firehose to wire here. - return { session, created: true }; - } - - getSession(uin: string): QQSession | null { - return this.sessions_.get(uin) ?? null; - } - - get sessions(): Map { - return this.sessions_; - } } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index bd6fc894..d3dc700b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -2,17 +2,17 @@ import { HookManager } from '@snowluma/bridge'; import { configureFileTransport } from '@snowluma/common/log-file-transport'; import { closeLogger, createLogger } from '@snowluma/common/logger'; import { - DEFAULT_LOG_MAX_TOTAL_MB, - DEFAULT_LOG_PER_UIN, - DEFAULT_LOG_RETAIN_DAYS, - loadRuntimeConfig, + DEFAULT_LOG_MAX_TOTAL_MB, + DEFAULT_LOG_PER_UIN, + DEFAULT_LOG_RETAIN_DAYS, + loadRuntimeConfig, } from '@snowluma/common/runtime'; import { OneBotManager } from '@snowluma/onebot/manager'; import { migrateGlobalSettings } from '@snowluma/onebot/global-config'; import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config'; import { - isMessageStoreMigrationWorkerData, - runMessageStoreMigrationWorker, + isMessageStoreMigrationWorkerData, + runMessageStoreMigrationWorker, } from '@snowluma/onebot/message-store-migration-worker'; import { workerData } from 'node:worker_threads'; import { BridgeManager } from './bridge/manager'; @@ -24,155 +24,213 @@ import { readAppVersion, startNativeStageSync, tempStagePath } from './native-st const log = createLogger('App'); function installProcessGuards(): void { - // Last-resort process guards. This is a long-running daemon: a hooked QQ pipe - // can drop at any moment, and a stray rejection on a detached callback (or a - // throw that escapes one) must NOT take the whole process down — otherwise - // Docker restarts it (dropping every session) and a bare Windows run just dies - // ("connection pipe closed", bot offline). Log and keep serving; the bridge's - // own watcher reconnects the dropped pipe. Targeted handlers still cover the - // known paths (e.g. the hook-client send deferreds) — these only catch what - // slips through, and surface its stack so the real source can be fixed. - process.on('unhandledRejection', (reason) => { - log.error('unhandledRejection (kept alive): %s', - reason instanceof Error ? (reason.stack ?? reason.message) : String(reason)); - }); - process.on('uncaughtException', (error) => { - log.error('uncaughtException (kept alive): %s', error.stack ?? error.message); - }); + // Last-resort process guards. This is a long-running daemon: a hooked QQ pipe + // can drop at any moment, and a stray rejection on a detached callback (or a + // throw that escapes one) must NOT take the whole process down — otherwise + // Docker restarts it (dropping every session) and a bare Windows run just dies + // ("connection pipe closed", bot offline). Log and keep serving; the bridge's + // own watcher reconnects the dropped pipe. Targeted handlers still cover the + // known paths (e.g. the hook-client send deferreds) — these only catch what + // slips through, and surface its stack so the real source can be fixed. + process.on('unhandledRejection', (reason) => { + log.error( + 'unhandledRejection (kept alive): %s', + reason instanceof Error ? (reason.stack ?? reason.message) : String(reason), + ); + }); + process.on('uncaughtException', (error) => { + log.error('uncaughtException (kept alive): %s', error.stack ?? error.message); + }); } async function main() { - const runtimeConfig = loadRuntimeConfig(); - await configureFileTransport({ - maxTotalMb: runtimeConfig.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB, - retainDays: runtimeConfig.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS, - perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN, - }); - log.info('SnowLuma starting'); - const stopNativeStageSync = startNativeStageSync({ - version: readAppVersion(import.meta.url), - dataDir: 'data', - tempPath: tempStagePath(), - }); + const runtimeConfig = loadRuntimeConfig(); + await configureFileTransport({ + maxTotalMb: runtimeConfig.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB, + retainDays: runtimeConfig.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS, + perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN, + }); + log.info('SnowLuma starting'); + const stopNativeStageSync = startNativeStageSync({ + version: readAppVersion(import.meta.url), + dataDir: 'data', + tempPath: tempStagePath(), + }); - // One-shot: lift a legacy per-UIN musicSignUrl into the global store before - // any session (and thus any per-UIN config rewrite) can drop it. - migrateGlobalSettings(); + // One-shot: lift a legacy per-UIN musicSignUrl into the global store before + // any session (and thus any per-UIN config rewrite) can drop it. + migrateGlobalSettings(); - // One-shot: purge any persisted phantom accounts (onebot_.json) the - // native hook may have created with a timestamp-shaped UIN (issue #162). - cleanupInvalidPerUinConfigs(); + // One-shot: purge any persisted phantom accounts (onebot_.json) the + // native hook may have created with a timestamp-shaped UIN (issue #162). + cleanupInvalidPerUinConfigs(); - const bridgeManager = new BridgeManager(); - bindSystemFaceCatalog(bridgeManager); - const oneBotManager = new OneBotManager(); - const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad); + const bridgeManager = new BridgeManager(); + bindSystemFaceCatalog(bridgeManager); + const oneBotManager = new OneBotManager(); + const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad); - // WebUI state-push wiring: HookManager + BridgeManager edges publish - // `processes` / `qq-list` / `connections` invalidations into a bus the - // /api/state/stream SSE handler subscribes to (no REST polling required). - const stateWiring = createStateWiring(); - const hookManager = new HookManager({ - bridgeManager, - autoLoadOnDiscovery, - onSessionsChanged: stateWiring.onSessionsChanged, - }); - if (autoLoadOnDiscovery) { - log.info('hook auto-load enabled: every discovered QQ process will be injected'); - } + // WebUI state-push wiring: HookManager + BridgeManager edges publish + // `processes` / `qq-list` / `connections` invalidations into a bus the + // /api/state/stream SSE handler subscribes to (no REST polling required). + const stateWiring = createStateWiring(); + const hookManager = new HookManager({ + bridgeManager, + autoLoadOnDiscovery, + onSessionsChanged: stateWiring.onSessionsChanged, + }); - oneBotManager.bind(bridgeManager); - stateWiring.bindBridgeManager(bridgeManager); - - // Global notification subsystem (account up/down → webhook). Bound AFTER - // OneBotManager so the nickname fallback is already populated when it observes. - const notificationManager = createNotificationManager(); - notificationManager.bind(bridgeManager); - - let stopWebUI: (() => Promise) | undefined; - if ( - (typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) || - process.env.SNOWLUMA_DEV_WEBUI === '1' - ) { - try { - const { initWebUI } = await import('./webui/server'); - const started = await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, { - host: runtimeConfig.webuiHost, - tlsEnabled: runtimeConfig.webuiTls?.enabled, - trustProxy: runtimeConfig.trustProxy, - stateBus: stateWiring.bus, - }); - stopWebUI = started.stop; - } catch (err) { - log.error('Failed to start WebUI: ', err); + if (autoLoadOnDiscovery) { + log.info('hook auto-load enabled: every discovered QQ process will be injected'); } - } - // Graceful shutdown: dispose managers, await log flush, then exit. - // SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path. - let shutdownStarted = false; - const shutdown = (signal: string) => async () => { - if (shutdownStarted) return; - shutdownStarted = true; - log.warn(`Shutting down (${signal})...`); - let exitCode = 0; - try { - await oneBotManager.dispose(); - } catch (error) { - exitCode = 1; - log.error('OneBot shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); + oneBotManager.bind(bridgeManager); + stateWiring.bindBridgeManager(bridgeManager); + + // Global notification subsystem (account up/down → webhook). Bound AFTER + // OneBotManager so the nickname fallback is already populated when it observes. + const notificationManager = createNotificationManager(); + notificationManager.bind(bridgeManager); + + let stopWebUI: (() => Promise) | undefined; + + if ( + (typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) || + process.env.SNOWLUMA_DEV_WEBUI === '1' + ) { + try { + const { initWebUI } = await import('./webui/server'); + const started = await initWebUI( + runtimeConfig.webuiPort || 5099, + oneBotManager, + hookManager, + notificationManager, + { + host: runtimeConfig.webuiHost, + tlsEnabled: runtimeConfig.webuiTls?.enabled, + trustProxy: runtimeConfig.trustProxy, + stateBus: stateWiring.bus, + }, + ); + stopWebUI = started.stop; + } catch (err) { + log.error('Failed to start WebUI: ', err); + } } - try { notificationManager.dispose(); } catch (error) { - exitCode = 1; - log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); - } - try { - if (stopWebUI) await stopWebUI(); - } catch (error) { - exitCode = 1; - log.error('WebUI shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); - } - // Observers go deaf before Hook teardown. Hook dispose then emits the - // same disconnected → PID detach → Bridge closed path as a live drop; - // those closed edges must not look like a runtime offline. - try { stateWiring.dispose(); } catch (error) { - exitCode = 1; - log.error('state wiring shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); - } - try { stopNativeStageSync.stop(); } catch (error) { - exitCode = 1; - log.error('stage sync shutdown failed: %s', error instanceof Error ? error.message : String(error)); - } - try { hookManager.dispose(); } catch (error) { - exitCode = 1; - log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); - } - await closeLogger(); - process.exit(exitCode); - }; - process.on('SIGINT', shutdown('SIGINT')); - process.on('SIGTERM', shutdown('SIGTERM')); + + // Graceful shutdown: dispose managers, await log flush, then exit. + // SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path. + let shutdownStarted = false; + + const shutdown = (signal: string) => async () => { + if (shutdownStarted) { + return; + } + + shutdownStarted = true; + log.warn(`Shutting down (${signal})...`); + let exitCode = 0; + + try { + await oneBotManager.dispose(); + } catch (error) { + exitCode = 1; + log.error( + 'OneBot shutdown failed: %s', + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + } + + try { + notificationManager.dispose(); + } catch (error) { + exitCode = 1; + log.error( + 'notification shutdown failed: %s', + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + } + + try { + if (stopWebUI) { + await stopWebUI(); + } + } catch (error) { + exitCode = 1; + log.error( + 'WebUI shutdown failed: %s', + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + } + + // Observers go deaf before Hook teardown. Hook dispose then emits the + // same disconnected → PID detach → Bridge closed path as a live drop; + // those closed edges must not look like a runtime offline. + try { + stateWiring.dispose(); + } catch (error) { + exitCode = 1; + log.error( + 'state wiring shutdown failed: %s', + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + } + + try { + stopNativeStageSync.stop(); + } catch (error) { + exitCode = 1; + log.error( + 'stage sync shutdown failed: %s', + error instanceof Error ? error.message : String(error), + ); + } + + try { + hookManager.dispose(); + } catch (error) { + exitCode = 1; + log.error( + 'hook shutdown failed: %s', + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + } + + await closeLogger(); + process.exit(exitCode); + }; + + process.on('SIGINT', shutdown('SIGINT')); + process.on('SIGTERM', shutdown('SIGTERM')); } function resolveAutoLoad(fromConfig: boolean | undefined): boolean { - const envRaw = process.env.SNOWLUMA_HOOK_AUTOLOAD; - if (typeof envRaw === 'string' && envRaw.trim()) { - const v = envRaw.trim().toLowerCase(); - if (v === '1' || v === 'true' || v === 'yes' || v === 'on') return true; - if (v === '0' || v === 'false' || v === 'no' || v === 'off') return false; - } - return fromConfig === true; + const envRaw = process.env.SNOWLUMA_HOOK_AUTOLOAD; + + if (typeof envRaw === 'string' && envRaw.trim()) { + const v = envRaw.trim().toLowerCase(); + + if (v === '1' || v === 'true' || v === 'yes' || v === 'on') { + return true; + } + + if (v === '0' || v === 'false' || v === 'no' || v === 'off') { + return false; + } + } + + return fromConfig === true; } if (isMessageStoreMigrationWorkerData(workerData)) { - runMessageStoreMigrationWorker(workerData).catch(() => { - process.exitCode = 1; - }); + runMessageStoreMigrationWorker(workerData).catch(() => { + process.exitCode = 1; + }); } else { - installProcessGuards(); - main().catch(async (error) => { - log.error(error instanceof Error ? (error.stack ?? error.message) : String(error)); - await closeLogger(); - process.exit(1); - }); + installProcessGuards(); + main().catch(async (error) => { + log.error(error instanceof Error ? (error.stack ?? error.message) : String(error)); + await closeLogger(); + process.exit(1); + }); } diff --git a/packages/core/src/native-stage-sync.ts b/packages/core/src/native-stage-sync.ts index 3be9e76d..6cc46eee 100644 --- a/packages/core/src/native-stage-sync.ts +++ b/packages/core/src/native-stage-sync.ts @@ -1,4 +1,13 @@ -import { readFileSync, writeFileSync, mkdirSync, statSync, openSync, readSync, closeSync, fstatSync } from 'node:fs'; +import { + readFileSync, + writeFileSync, + mkdirSync, + statSync, + openSync, + readSync, + closeSync, + fstatSync, +} from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { createLogger, type Logger } from '@snowluma/common/logger'; @@ -9,260 +18,349 @@ export const MIRROR_LIMIT_BYTES = 1024 * 1024; const VERSION_HEADER = /^v\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/; export function isVersionHeader(line: string): boolean { - return VERSION_HEADER.test(line); + return VERSION_HEADER.test(line); } export function lineSeverity(line: string): 'info' | 'error' { - const parts = line.trim().split(/\s+/); - return parts.length >= 4 && parts[3] === '1' ? 'error' : 'info'; + const parts = line.trim().split(/\s+/); + return parts.length >= 4 && parts[3] === '1' ? 'error' : 'info'; } export function publicLine(version: string, raw: string): string { - return `${version} ${raw.trim()}`; + return `${version} ${raw.trim()}`; } function byteSize(lines: readonly string[]): number { - if (lines.length === 0) return 0; - return Buffer.byteLength(`${lines.join('\n')}\n`, 'utf8'); + if (lines.length === 0) { + return 0; + } + + return Buffer.byteLength(`${lines.join('\n')}\n`, 'utf8'); } export function trimMirror(text: string, limit = MIRROR_LIMIT_BYTES): string { - const lines = text.split('\n').filter((line) => line.length > 0); - const size = () => byteSize(lines); - while (lines.length > 0 && size() > limit) { - const body = lines.findIndex((line) => !isVersionHeader(line)); - if (body >= 0) { - lines.splice(body, 1); - continue; + const lines = text.split('\n').filter((line) => line.length > 0); + const size = () => byteSize(lines); + + while (lines.length > 0 && size() > limit) { + const body = lines.findIndex((line) => !isVersionHeader(line)); + + if (body >= 0) { + lines.splice(body, 1); + continue; + } + + if (lines.length <= 1) { + break; + } + + lines.shift(); } - if (lines.length <= 1) break; - lines.shift(); - } - if (lines.length === 0) return ''; - return `${lines.join('\n')}\n`; + + if (lines.length === 0) { + return ''; + } + + return `${lines.join('\n')}\n`; } export function appendEvents( - mirror: string, - version: string, - events: readonly string[], - limit = MIRROR_LIMIT_BYTES, + mirror: string, + version: string, + events: readonly string[], + limit = MIRROR_LIMIT_BYTES, ): string { - const fresh = events.map((line) => line.trim()).filter((line) => line.length > 0); - if (fresh.length === 0) return mirror; - const header = `v${version}`; - const lines = mirror.split('\n').filter((line) => line.length > 0); - let lastHeader = ''; - for (const line of lines) { - if (isVersionHeader(line)) lastHeader = line; - } - const next = [...lines]; - if (lastHeader !== header) next.push(header); - next.push(...fresh); - return trimMirror(`${next.join('\n')}\n`, limit); + const fresh = events.map((line) => line.trim()).filter((line) => line.length > 0); + + if (fresh.length === 0) { + return mirror; + } + + const header = `v${version}`; + const lines = mirror.split('\n').filter((line) => line.length > 0); + let lastHeader = ''; + + for (const line of lines) { + if (isVersionHeader(line)) { + lastHeader = line; + } + } + + const next = [...lines]; + + if (lastHeader !== header) { + next.push(header); + } + + next.push(...fresh); + return trimMirror(`${next.join('\n')}\n`, limit); } export function tempStagePath( - platform = process.platform, - env: NodeJS.ProcessEnv = process.env, + platform = process.platform, + env: NodeJS.ProcessEnv = process.env, ): string { - if (platform === 'win32') { - const base = env.TMP || env.TEMP || os.tmpdir(); - return path.join(base, STAGE_FILE_NAME); - } - const uid = typeof process.getuid === 'function' ? process.getuid() : 0; - return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`; + if (platform === 'win32') { + const base = env.TMP || env.TEMP || os.tmpdir(); + return path.join(base, STAGE_FILE_NAME); + } + + const uid = typeof process.getuid === 'function' ? process.getuid() : 0; + return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`; } export function readAppVersion(moduleUrl: string | URL = import.meta.url): string { - if (typeof __APP_VERSION__ === 'string' && __APP_VERSION__) return __APP_VERSION__; - try { - const raw = readFileSync(new URL('../package.json', moduleUrl), 'utf8'); - const version = JSON.parse(raw).version; - if (typeof version === 'string' && version.trim()) return version.trim(); - } catch { - // Built layouts that do not sit next to a package manifest keep the fallback. - } - return '0.0.0'; + if (typeof __APP_VERSION__ === 'string' && __APP_VERSION__) { + return __APP_VERSION__; + } + + try { + const raw = readFileSync(new URL('../package.json', moduleUrl), 'utf8'); + const version = JSON.parse(raw).version; + + if (typeof version === 'string' && version.trim()) { + return version.trim(); + } + } catch { + // Built layouts that do not sit next to a package manifest keep the fallback. + } + + return '0.0.0'; } export function errorCode(error: unknown): string { - if (error && typeof error === 'object' && 'code' in error) { - const code = (error as { code?: unknown }).code; - if (typeof code === 'string' && code) return code; - } - return 'ERR'; + if (error && typeof error === 'object' && 'code' in error) { + const code = (error as { code?: unknown }).code; + + if (typeof code === 'string' && code) { + return code; + } + } + + return 'ERR'; } export interface StageSyncOptions { - version: string; - dataDir: string; - tempPath: string; - log?: Logger; - intervalMs?: number; + version: string; + dataDir: string; + tempPath: string; + log?: Logger; + intervalMs?: number; } interface IngestResult { - mirror: string; - offset: number; - lines: string[]; - missing: boolean; - errorCode?: string; + mirror: string; + offset: number; + lines: string[]; + missing: boolean; + errorCode?: string; } export function ingestTemp(args: { - tempText: string; - offset: number; - mirror: string; - version: string; - missing?: boolean; - errorCode?: string; + tempText: string; + offset: number; + mirror: string; + version: string; + missing?: boolean; + errorCode?: string; }): IngestResult { - if (args.missing) { - return { mirror: args.mirror, offset: args.offset, lines: [], missing: true }; - } - if (args.errorCode) { + if (args.missing) { + return { mirror: args.mirror, offset: args.offset, lines: [], missing: true }; + } + + if (args.errorCode) { + return { + mirror: args.mirror, + offset: args.offset, + lines: [], + missing: false, + errorCode: args.errorCode, + }; + } + + const start = args.offset > args.tempText.length ? 0 : args.offset; + const chunk = args.tempText.slice(start); + const newline = chunk.lastIndexOf('\n'); + + if (newline < 0) { + return { mirror: args.mirror, offset: start, lines: [], missing: false }; + } + + const complete = chunk.slice(0, newline + 1); + const lines = complete + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0); return { - mirror: args.mirror, - offset: args.offset, - lines: [], - missing: false, - errorCode: args.errorCode, + mirror: appendEvents(args.mirror, args.version, lines), + offset: start + newline + 1, + lines, + missing: false, }; - } - const start = args.offset > args.tempText.length ? 0 : args.offset; - const chunk = args.tempText.slice(start); - const newline = chunk.lastIndexOf('\n'); - if (newline < 0) { - return { mirror: args.mirror, offset: start, lines: [], missing: false }; - } - const complete = chunk.slice(0, newline + 1); - const lines = complete.split('\n').map((line) => line.trim()).filter((line) => line.length > 0); - return { - mirror: appendEvents(args.mirror, args.version, lines), - offset: start + newline + 1, - lines, - missing: false, - }; } function readOffset(file: string): number { - try { - const raw = readFileSync(file, 'utf8').trim(); - const value = Number(raw); - return Number.isSafeInteger(value) && value >= 0 ? value : 0; - } catch { - return 0; - } + try { + const raw = readFileSync(file, 'utf8').trim(); + const value = Number(raw); + return Number.isSafeInteger(value) && value >= 0 ? value : 0; + } catch { + return 0; + } } function readTemp(file: string): { text: string; missing: boolean; errorCode?: string } { - let fd: number | undefined; - try { - fd = openSync(file, 'r'); - const info = fstatSync(fd); - const size = info.size; - if (size > 8 * 1024 * 1024) { - return { text: '', missing: false, errorCode: 'E2BIG' }; + let fd: number | undefined; + + try { + fd = openSync(file, 'r'); + const info = fstatSync(fd); + const size = info.size; + + if (size > 8 * 1024 * 1024) { + return { text: '', missing: false, errorCode: 'E2BIG' }; + } + + const buf = Buffer.alloc(size); + let got = 0; + + while (got < size) { + const n = readSync(fd, buf, got, size - got, got); + + if (n <= 0) { + break; + } + + got += n; + } + + return { text: buf.subarray(0, got).toString('utf8'), missing: false }; + } catch (error) { + const code = errorCode(error); + + if (code === 'ENOENT') { + return { text: '', missing: true }; + } + + return { text: '', missing: false, errorCode: code }; + } finally { + if (fd !== undefined) { + closeSync(fd); + } } - const buf = Buffer.alloc(size); - let got = 0; - while (got < size) { - const n = readSync(fd, buf, got, size - got, got); - if (n <= 0) break; - got += n; - } - return { text: buf.subarray(0, got).toString('utf8'), missing: false }; - } catch (error) { - const code = errorCode(error); - if (code === 'ENOENT') return { text: '', missing: true }; - return { text: '', missing: false, errorCode: code }; - } finally { - if (fd !== undefined) closeSync(fd); - } } export function startNativeStageSync(options: StageSyncOptions): { stop: () => void } { - const log = options.log ?? createLogger('native'); - const mirrorPath = path.join(options.dataDir, STAGE_FILE_NAME); - const offsetPath = path.join(options.dataDir, 's7.off'); - let offset = readOffset(offsetPath); - let failed = false; - let stopped = false; + const log = options.log ?? createLogger('native'); + const mirrorPath = path.join(options.dataDir, STAGE_FILE_NAME); + const offsetPath = path.join(options.dataDir, 's7.off'); + let offset = readOffset(offsetPath); + let failed = false; + let stopped = false; - const tick = () => { - if (stopped) return; - let tempSize = 0; - try { - tempSize = statSync(options.tempPath).size; - } catch (error) { - const code = errorCode(error); - if (code === 'ENOENT') return; - if (!failed) { - failed = true; - log.error('sync failed %s', code); - } - return; - } - if (tempSize < offset) offset = 0; - const temp = readTemp(options.tempPath); - if (temp.missing) return; - if (temp.errorCode) { - if (!failed) { - failed = true; - log.error('sync failed %s', temp.errorCode); - } - return; - } - let mirror = ''; - try { - mirror = readFileSync(mirrorPath, 'utf8'); - } catch (error) { - if (errorCode(error) !== 'ENOENT') { - if (!failed) { - failed = true; - log.error('sync failed %s', errorCode(error)); + const tick = () => { + if (stopped) { + return; } - return; - } - } - const ingested = ingestTemp({ - tempText: temp.text, - offset, - mirror, - version: options.version, - }); - if (ingested.lines.length === 0 && ingested.offset === offset) { - failed = false; - return; - } - try { - mkdirSync(options.dataDir, { recursive: true }); - writeFileSync(mirrorPath, ingested.mirror); - writeFileSync(offsetPath, `${ingested.offset}\n`); - offset = ingested.offset; - failed = false; - } catch (error) { - if (!failed) { - failed = true; - log.error('sync failed %s', errorCode(error)); - } - return; - } - for (const line of ingested.lines) { - const text = publicLine(options.version, line); - if (lineSeverity(line) === 'error') log.error('%s', text); - else log.info('%s', text); - } - }; - tick(); - const timer = setInterval(tick, options.intervalMs ?? 500); - timer.unref?.(); - return { - stop() { - stopped = true; - clearInterval(timer); - }, - }; + let tempSize = 0; + + try { + tempSize = statSync(options.tempPath).size; + } catch (error) { + const code = errorCode(error); + + if (code === 'ENOENT') { + return; + } + + if (!failed) { + failed = true; + log.error('sync failed %s', code); + } + + return; + } + + if (tempSize < offset) { + offset = 0; + } + + const temp = readTemp(options.tempPath); + + if (temp.missing) { + return; + } + + if (temp.errorCode) { + if (!failed) { + failed = true; + log.error('sync failed %s', temp.errorCode); + } + + return; + } + + let mirror = ''; + + try { + mirror = readFileSync(mirrorPath, 'utf8'); + } catch (error) { + if (errorCode(error) !== 'ENOENT') { + if (!failed) { + failed = true; + log.error('sync failed %s', errorCode(error)); + } + + return; + } + } + + const ingested = ingestTemp({ + tempText: temp.text, + offset, + mirror, + version: options.version, + }); + + if (ingested.lines.length === 0 && ingested.offset === offset) { + failed = false; + return; + } + + try { + mkdirSync(options.dataDir, { recursive: true }); + writeFileSync(mirrorPath, ingested.mirror); + writeFileSync(offsetPath, `${ingested.offset}\n`); + offset = ingested.offset; + failed = false; + } catch (error) { + if (!failed) { + failed = true; + log.error('sync failed %s', errorCode(error)); + } + + return; + } + + for (const line of ingested.lines) { + const text = publicLine(options.version, line); + + if (lineSeverity(line) === 'error') { + log.error('%s', text); + } else { + log.info('%s', text); + } + } + }; + + tick(); + const timer = setInterval(tick, options.intervalMs ?? 500); + timer.unref?.(); + return { + stop() { + stopped = true; + clearInterval(timer); + }, + }; } diff --git a/packages/core/src/notifications/config.ts b/packages/core/src/notifications/config.ts index 6b8cec89..9076cad5 100644 --- a/packages/core/src/notifications/config.ts +++ b/packages/core/src/notifications/config.ts @@ -43,40 +43,40 @@ export type NotificationEvent = 'offline' | 'online'; export type NotificationChannelType = 'webhook' | 'email'; export interface NotificationChannel { - id: string; - name: string; - type: NotificationChannelType; - /** http(s) webhook target. Empty on email channels. */ - url: string; - bodyTemplate: string; - enabled: boolean; - /** Extra outbound request headers (Authorization, etc.). Webhook only. */ - headers?: Record; - smtpHost?: string; - smtpPort?: number; - smtpSecure?: boolean; - smtpUser?: string; - smtpPass?: string; - from?: string; - to?: string; - subjectTemplate?: string; + id: string; + name: string; + type: NotificationChannelType; + /** http(s) webhook target. Empty on email channels. */ + url: string; + bodyTemplate: string; + enabled: boolean; + /** Extra outbound request headers (Authorization, etc.). Webhook only. */ + headers?: Record; + smtpHost?: string; + smtpPort?: number; + smtpSecure?: boolean; + smtpUser?: string; + smtpPass?: string; + from?: string; + to?: string; + subjectTemplate?: string; } export function isEmailChannel(ch: NotificationChannel): ch is NotificationChannel & { - smtpHost: string; - smtpPort: number; - smtpSecure: boolean; - from: string; - to: string; - subjectTemplate: string; + smtpHost: string; + smtpPort: number; + smtpSecure: boolean; + from: string; + to: string; + subjectTemplate: string; } { - return ch.type === 'email'; + return ch.type === 'email'; } export interface NotificationsConfig { - version: typeof NOTIFICATIONS_CONFIG_VERSION; - debounceSeconds: number; - channels: NotificationChannel[]; + version: typeof NOTIFICATIONS_CONFIG_VERSION; + debounceSeconds: number; + channels: NotificationChannel[]; } /** Default body template — Server酱-style JSON ({title}/{desp}). The WebUI @@ -105,11 +105,11 @@ const SMTP_PORT_MIN = 1; const SMTP_PORT_MAX = 65535; export function defaultNotificationsConfig(): NotificationsConfig { - return { - version: NOTIFICATIONS_CONFIG_VERSION, - debounceSeconds: DEFAULT_DEBOUNCE_SECONDS, - channels: [], - }; + return { + version: NOTIFICATIONS_CONFIG_VERSION, + debounceSeconds: DEFAULT_DEBOUNCE_SECONDS, + channels: [], + }; } // ─── Template renderer ────────────────────────────────────────────────────── @@ -125,19 +125,27 @@ export function defaultNotificationsConfig(): NotificationsConfig { * become `\\` and double-quotes become `\"`. */ export function renderTemplate(template: string, vars: Record): string { - if (typeof template !== 'string') return ''; - 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; - }); + if (typeof template !== 'string') { + return ''; + } + + 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 ────────────────────────────────────────────────── @@ -145,235 +153,351 @@ export function renderTemplate(template: string, vars: Record): // notifications-only (string truncation to maxLen), so it stays here. function strOr(value: unknown, fallback: string, maxLen: number): string { - return typeof value === 'string' ? value.slice(0, maxLen) : fallback; + return typeof value === 'string' ? value.slice(0, maxLen) : fallback; } function normalizeChannelId(value: unknown): string | null { - if (typeof value !== 'string') return null; - const v = value.trim(); - if (v.length === 0 || v.length > CHANNEL_ID_MAX) return null; - if (!CHANNEL_ID_RE.test(v)) return null; - return v; + if (typeof value !== 'string') { + return null; + } + + const v = value.trim(); + + if (v.length === 0 || v.length > CHANNEL_ID_MAX) { + return null; + } + + if (!CHANNEL_ID_RE.test(v)) { + return null; + } + + return v; } function isHttpUrl(value: string): boolean { - try { - const u = new URL(value); - return u.protocol === 'http:' || u.protocol === 'https:'; - } catch { - return false; - } + try { + const u = new URL(value); + return u.protocol === 'http:' || u.protocol === 'https:'; + } catch { + return false; + } } function normalizeHeaders(value: unknown): Record | undefined { - if (!isObject(value)) return undefined; - const out: Record = {}; - const seen = new Set(); - for (const [rawName, rawValue] of Object.entries(value)) { - if (Object.keys(out).length >= HEADERS_MAX) break; - if (typeof rawValue !== 'string') continue; - const name = rawName.trim(); - if (name.length === 0 || name.length > HEADER_NAME_MAX) continue; - if (!HEADER_NAME_RE.test(name)) continue; - const folded = name.toLowerCase(); - if (seen.has(folded)) continue; - const headerValue = rawValue.trim(); - if (headerValue.length === 0 || headerValue.length > HEADER_VALUE_MAX) continue; - if (headerValue.includes('\r') || headerValue.includes('\n')) continue; - seen.add(folded); - out[name] = headerValue; - } - return Object.keys(out).length > 0 ? out : undefined; + if (!isObject(value)) { + return undefined; + } + + const out: Record = {}; + const seen = new Set(); + + for (const [rawName, rawValue] of Object.entries(value)) { + if (Object.keys(out).length >= HEADERS_MAX) { + break; + } + + if (typeof rawValue !== 'string') { + continue; + } + + const name = rawName.trim(); + + if (name.length === 0 || name.length > HEADER_NAME_MAX) { + continue; + } + + if (!HEADER_NAME_RE.test(name)) { + continue; + } + + const folded = name.toLowerCase(); + + if (seen.has(folded)) { + continue; + } + + const headerValue = rawValue.trim(); + + if (headerValue.length === 0 || headerValue.length > HEADER_VALUE_MAX) { + continue; + } + + if (headerValue.includes('\r') || headerValue.includes('\n')) { + continue; + } + + seen.add(folded); + out[name] = headerValue; + } + + return Object.keys(out).length > 0 ? out : undefined; } function normalizeSmtpHost(value: unknown): string | null { - if (typeof value !== 'string') return null; - const v = value.trim(); - if (!v || v.length > SMTP_HOST_MAX) return null; - if (/\s/.test(v) || v.includes('/') || v.includes('://')) return null; - return v; + if (typeof value !== 'string') { + return null; + } + + const v = value.trim(); + + if (!v || v.length > SMTP_HOST_MAX) { + return null; + } + + if (/\s/.test(v) || v.includes('/') || v.includes('://')) { + return null; + } + + return v; } function normalizeFrom(value: unknown): string | null { - if (typeof value !== 'string') return null; - const v = value.trim().slice(0, EMAIL_FIELD_MAX); - return extractAddress(v) ? v : null; + if (typeof value !== 'string') { + return null; + } + + const v = value.trim().slice(0, EMAIL_FIELD_MAX); + return extractAddress(v) ? v : null; } function normalizeTo(value: unknown): string | null { - if (typeof value !== 'string') return null; - const addrs = parseRecipients(value.trim().slice(0, EMAIL_FIELD_MAX)); - return addrs.length > 0 ? addrs.join(', ') : null; + if (typeof value !== 'string') { + return null; + } + + const addrs = parseRecipients(value.trim().slice(0, EMAIL_FIELD_MAX)); + return addrs.length > 0 ? addrs.join(', ') : null; } function normalizeChannelType(value: unknown): NotificationChannelType | null { - if (value === 'email') return 'email'; - if (value === 'webhook' || value === undefined || value === '') return 'webhook'; - return null; + if (value === 'email') { + return 'email'; + } + + if (value === 'webhook' || value === undefined || value === '') { + return 'webhook'; + } + + return null; } function normalizeEmailChannel( - raw: Record, - id: string, - name: string, + raw: Record, + id: string, + name: string, ): NotificationChannel | null { - const smtpHost = normalizeSmtpHost(raw.smtpHost); - const from = normalizeFrom(raw.from); - const to = normalizeTo(raw.to); - if (!smtpHost || !from || !to) return null; + const smtpHost = normalizeSmtpHost(raw.smtpHost); + const from = normalizeFrom(raw.from); + const to = normalizeTo(raw.to); - const portRaw = raw.smtpPort; - const portProvided = portRaw !== undefined && portRaw !== null && portRaw !== ''; - const secureProvided = typeof raw.smtpSecure === 'boolean'; - const port = portProvided - ? clampInt(portRaw, SMTP_PORT_MIN, SMTP_PORT_MAX, 0) - : 0; - if (portProvided && port === 0) return null; + if (!smtpHost || !from || !to) { + return null; + } - const smtpSecure = secureProvided ? Boolean(raw.smtpSecure) : port === 465 || port === 0; - const smtpPort = port === 0 ? (smtpSecure ? 465 : 587) : port; + const portRaw = raw.smtpPort; + const portProvided = portRaw !== undefined && portRaw !== null && portRaw !== ''; + const secureProvided = typeof raw.smtpSecure === 'boolean'; + const port = portProvided ? clampInt(portRaw, SMTP_PORT_MIN, SMTP_PORT_MAX, 0) : 0; - const smtpUser = typeof raw.smtpUser === 'string' ? raw.smtpUser.trim().slice(0, SMTP_USER_MAX) : ''; - const smtpPass = typeof raw.smtpPass === 'string' ? raw.smtpPass.slice(0, SMTP_PASS_MAX) : ''; + if (portProvided && port === 0) { + return null; + } - return { - id, - name, - type: 'email', - url: '', - bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY_TEMPLATE, BODY_TEMPLATE_MAX), - enabled: boolOr(raw.enabled, true), - smtpHost, - smtpPort, - smtpSecure, - ...(smtpUser ? { smtpUser } : {}), - ...(smtpPass ? { smtpPass } : {}), - from, - to, - subjectTemplate: strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) || DEFAULT_SUBJECT_TEMPLATE, - }; + const smtpSecure = secureProvided ? Boolean(raw.smtpSecure) : port === 465 || port === 0; + const smtpPort = port === 0 ? (smtpSecure ? 465 : 587) : port; + + const smtpUser = + typeof raw.smtpUser === 'string' ? raw.smtpUser.trim().slice(0, SMTP_USER_MAX) : ''; + const smtpPass = typeof raw.smtpPass === 'string' ? raw.smtpPass.slice(0, SMTP_PASS_MAX) : ''; + + return { + id, + name, + type: 'email', + url: '', + bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY_TEMPLATE, BODY_TEMPLATE_MAX), + enabled: boolOr(raw.enabled, true), + smtpHost, + smtpPort, + smtpSecure, + ...(smtpUser ? { smtpUser } : {}), + ...(smtpPass ? { smtpPass } : {}), + from, + to, + subjectTemplate: + strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) || + DEFAULT_SUBJECT_TEMPLATE, + }; } /** A channel is usable only with a valid id AND a deliverable target — * http(s) URL for webhooks, SMTP host + from/to for email. Anything else * is dropped (total normalize). */ function normalizeChannel(raw: unknown): NotificationChannel | null { - if (!isObject(raw)) return null; - const id = normalizeChannelId(raw.id); - if (!id) return null; - const type = normalizeChannelType(raw.type); - if (!type) return null; - const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id; - if (type === 'email') return normalizeEmailChannel(raw, id, name); + if (!isObject(raw)) { + return null; + } - const url = typeof raw.url === 'string' ? raw.url.trim() : ''; - if (!isHttpUrl(url)) return null; - const headers = normalizeHeaders(raw.headers); - return { - id, - name, - type: 'webhook', - url, - bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX), - enabled: boolOr(raw.enabled, true), - ...(headers ? { headers } : {}), - }; + const id = normalizeChannelId(raw.id); + + if (!id) { + return null; + } + + const type = normalizeChannelType(raw.type); + + if (!type) { + return null; + } + + const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id; + + if (type === 'email') { + return normalizeEmailChannel(raw, id, name); + } + + const url = typeof raw.url === 'string' ? raw.url.trim() : ''; + + if (!isHttpUrl(url)) { + return null; + } + + const headers = normalizeHeaders(raw.headers); + return { + id, + name, + type: 'webhook', + url, + bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX), + enabled: boolOr(raw.enabled, true), + ...(headers ? { headers } : {}), + }; } function normalizeChannels(value: unknown): NotificationChannel[] { - if (!Array.isArray(value)) return []; - const seen = new Set(); - const out: NotificationChannel[] = []; - for (const raw of value) { - const ch = normalizeChannel(raw); - if (!ch) continue; - if (seen.has(ch.id)) continue; // dedupe by id — first occurrence wins - seen.add(ch.id); - out.push(ch); - } - return out; + if (!Array.isArray(value)) { + return []; + } + + const seen = new Set(); + const out: NotificationChannel[] = []; + + for (const raw of value) { + const ch = normalizeChannel(raw); + + if (!ch) { + continue; + } + + if (seen.has(ch.id)) { + continue; + } // dedupe by id — first occurrence wins + + seen.add(ch.id); + out.push(ch); + } + + return out; } export function normalizeNotificationsConfig(value: unknown): NotificationsConfig { - const v = isObject(value) ? value : {}; - return { - version: NOTIFICATIONS_CONFIG_VERSION, - debounceSeconds: clampInt( - v.debounceSeconds, - DEBOUNCE_SECONDS_MIN, - DEBOUNCE_SECONDS_MAX, - DEFAULT_DEBOUNCE_SECONDS, - ), - channels: normalizeChannels(v.channels), - }; + const v = isObject(value) ? value : {}; + return { + version: NOTIFICATIONS_CONFIG_VERSION, + debounceSeconds: clampInt( + v.debounceSeconds, + DEBOUNCE_SECONDS_MIN, + DEBOUNCE_SECONDS_MAX, + DEFAULT_DEBOUNCE_SECONDS, + ), + channels: normalizeChannels(v.channels), + }; } // ─── Persistence (atomic write + module-level cache) ──────────────────────── function ensureConfigDir(): void { - fs.mkdirSync(CONFIG_DIR, { recursive: true }); + fs.mkdirSync(CONFIG_DIR, { recursive: true }); } function enforceSensitiveFileMode(file: string): void { - // POSIX mode bits do not model Windows ACLs; on Windows the inherited ACL - // remains authoritative. Avoid pretending chmod provides equivalent policy. - if (process.platform !== 'win32') fs.chmodSync(file, 0o600); + // POSIX mode bits do not model Windows ACLs; on Windows the inherited ACL + // remains authoritative. Avoid pretending chmod provides equivalent policy. + if (process.platform !== 'win32') { + fs.chmodSync(file, 0o600); + } } function atomicWrite(config: NotificationsConfig): void { - ensureConfigDir(); - const tmp = NOTIFICATIONS_CONFIG_PATH + '.tmp'; - fs.writeFileSync(tmp, JSON.stringify(config, null, 2), { - encoding: 'utf8', - mode: 0o600, - }); - enforceSensitiveFileMode(tmp); - fs.renameSync(tmp, NOTIFICATIONS_CONFIG_PATH); - enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH); + ensureConfigDir(); + const tmp = NOTIFICATIONS_CONFIG_PATH + '.tmp'; + fs.writeFileSync(tmp, JSON.stringify(config, null, 2), { + encoding: 'utf8', + mode: 0o600, + }); + enforceSensitiveFileMode(tmp); + fs.renameSync(tmp, NOTIFICATIONS_CONFIG_PATH); + enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH); } let cached: NotificationsConfig | null = null; /** Load + normalize the channel store, creating it from defaults if absent. */ export function loadNotificationsConfig(): NotificationsConfig { - if (cached) return cached; - ensureConfigDir(); + if (cached) { + return cached; + } + + ensureConfigDir(); + + if (!fs.existsSync(NOTIFICATIONS_CONFIG_PATH)) { + const fresh = defaultNotificationsConfig(); + + try { + atomicWrite(fresh); + } catch (err) { + log.warn( + 'failed to write initial notifications.json: %s', + err instanceof Error ? err.message : String(err), + ); + } + + cached = fresh; + return fresh; + } + + // Webhook URLs commonly embed credentials. Repair older permissive files + // before reading them into memory so upgrades close the exposure promptly. + enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH); - if (!fs.existsSync(NOTIFICATIONS_CONFIG_PATH)) { - const fresh = defaultNotificationsConfig(); try { - atomicWrite(fresh); + const raw = fs.readFileSync(NOTIFICATIONS_CONFIG_PATH, 'utf8'); + const parsed = JSON.parse(raw) as unknown; + const normalized = normalizeNotificationsConfig(parsed); + + // Self-heal on disk only if normalization changed something (corrupt/old). + if (JSON.stringify(parsed) !== JSON.stringify(normalized)) { + try { + atomicWrite(normalized); + } catch (err) { + log.warn( + 'failed to normalize notifications.json on disk: %s', + err instanceof Error ? err.message : String(err), + ); + } + } + + cached = normalized; + return normalized; } catch (err) { - log.warn('failed to write initial notifications.json: %s', err instanceof Error ? err.message : String(err)); + log.warn( + 'notifications.json unreadable; using defaults: %s', + err instanceof Error ? err.message : String(err), + ); + const fresh = defaultNotificationsConfig(); + cached = fresh; + return fresh; } - cached = fresh; - return fresh; - } - - // Webhook URLs commonly embed credentials. Repair older permissive files - // before reading them into memory so upgrades close the exposure promptly. - enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH); - - try { - const raw = fs.readFileSync(NOTIFICATIONS_CONFIG_PATH, 'utf8'); - const parsed = JSON.parse(raw) as unknown; - const normalized = normalizeNotificationsConfig(parsed); - // Self-heal on disk only if normalization changed something (corrupt/old). - if (JSON.stringify(parsed) !== JSON.stringify(normalized)) { - try { - atomicWrite(normalized); - } catch (err) { - log.warn('failed to normalize notifications.json on disk: %s', err instanceof Error ? err.message : String(err)); - } - } - cached = normalized; - return normalized; - } catch (err) { - log.warn('notifications.json unreadable; using defaults: %s', err instanceof Error ? err.message : String(err)); - const fresh = defaultNotificationsConfig(); - cached = fresh; - return fresh; - } } /** @@ -382,17 +506,22 @@ export function loadNotificationsConfig(): NotificationsConfig { * as `saveUiConfig`. Returns the stored, normalized config. */ export function saveNotificationsConfig(incoming: unknown): NotificationsConfig { - const current = loadNotificationsConfig(); - const v = isObject(incoming) ? incoming : {}; - const next: NotificationsConfig = { - version: NOTIFICATIONS_CONFIG_VERSION, - debounceSeconds: - v.debounceSeconds !== undefined - ? clampInt(v.debounceSeconds, DEBOUNCE_SECONDS_MIN, DEBOUNCE_SECONDS_MAX, DEFAULT_DEBOUNCE_SECONDS) - : current.debounceSeconds, - channels: Array.isArray(v.channels) ? normalizeChannels(v.channels) : current.channels, - }; - atomicWrite(next); - cached = next; - return next; + const current = loadNotificationsConfig(); + const v = isObject(incoming) ? incoming : {}; + const next: NotificationsConfig = { + version: NOTIFICATIONS_CONFIG_VERSION, + debounceSeconds: + v.debounceSeconds !== undefined + ? clampInt( + v.debounceSeconds, + DEBOUNCE_SECONDS_MIN, + DEBOUNCE_SECONDS_MAX, + DEFAULT_DEBOUNCE_SECONDS, + ) + : current.debounceSeconds, + channels: Array.isArray(v.channels) ? normalizeChannels(v.channels) : current.channels, + }; + atomicWrite(next); + cached = next; + return next; } diff --git a/packages/core/src/notifications/debounce.ts b/packages/core/src/notifications/debounce.ts index cc556ba1..ed70028f 100644 --- a/packages/core/src/notifications/debounce.ts +++ b/packages/core/src/notifications/debounce.ts @@ -12,71 +12,85 @@ import type { NotificationEvent } from './config'; export type DebounceDecision = - | { kind: 'none' } - | { kind: 'schedule'; delayMs: number } - | { kind: 'cancel' } - | { kind: 'emit'; event: NotificationEvent }; + | { kind: 'none' } + | { kind: 'schedule'; delayMs: number } + | { kind: 'cancel' } + | { kind: 'emit'; event: NotificationEvent }; interface UinState { - /** An offline debounce timer is armed but has not yet fired. */ - pending: boolean; - /** An "offline" notification has fired and is awaiting its recovery. */ - firedOffline: boolean; + /** An offline debounce timer is armed but has not yet fired. */ + pending: boolean; + /** An "offline" notification has fired and is awaiting its recovery. */ + firedOffline: boolean; } export class DebounceMachine { - private readonly states = new Map(); + private readonly states = new Map(); - private state(uin: string): UinState { - let s = this.states.get(uin); - if (!s) { - s = { pending: false, firedOffline: false }; - this.states.set(uin, s); + private state(uin: string): UinState { + let s = this.states.get(uin); + + if (!s) { + s = { pending: false, firedOffline: false }; + this.states.set(uin, s); + } + + return s; } - return s; - } - /** Account went offline. `debounceSeconds` is read fresh from config so a - * reload takes effect on the next transition. */ - onOffline(uin: string, debounceSeconds: number): DebounceDecision { - const s = this.state(uin); - if (s.firedOffline || s.pending) return { kind: 'none' }; // already down / already counting - // Non-finite / non-positive → no debounce, fire immediately. Stays total: - // never schedule a setTimeout(NaN|Infinity). Production config always - // clamps to a finite [0,3600]; this only hardens direct callers. - if (!Number.isFinite(debounceSeconds) || debounceSeconds <= 0) { - s.firedOffline = true; - return { kind: 'emit', event: 'offline' }; + /** Account went offline. `debounceSeconds` is read fresh from config so a + * reload takes effect on the next transition. */ + onOffline(uin: string, debounceSeconds: number): DebounceDecision { + const s = this.state(uin); + + if (s.firedOffline || s.pending) { + return { kind: 'none' }; + } // already down / already counting + + // Non-finite / non-positive → no debounce, fire immediately. Stays total: + // never schedule a setTimeout(NaN|Infinity). Production config always + // clamps to a finite [0,3600]; this only hardens direct callers. + if (!Number.isFinite(debounceSeconds) || debounceSeconds <= 0) { + s.firedOffline = true; + return { kind: 'emit', event: 'offline' }; + } + + s.pending = true; + return { kind: 'schedule', delayMs: debounceSeconds * 1000 }; } - s.pending = true; - return { kind: 'schedule', delayMs: debounceSeconds * 1000 }; - } - /** Account came online. */ - onOnline(uin: string): DebounceDecision { - const s = this.state(uin); - if (s.pending) { - s.pending = false; - return { kind: 'cancel' }; // self-heal within the debounce window — nothing fired + /** Account came online. */ + onOnline(uin: string): DebounceDecision { + const s = this.state(uin); + + if (s.pending) { + s.pending = false; + return { kind: 'cancel' }; // self-heal within the debounce window — nothing fired + } + + if (s.firedOffline) { + s.firedOffline = false; + return { kind: 'emit', event: 'online' }; // recovery, paired with the fired offline + } + + return { kind: 'none' }; // cold online / already up } - if (s.firedOffline) { - s.firedOffline = false; - return { kind: 'emit', event: 'online' }; // recovery, paired with the fired offline + + /** The offline debounce window elapsed (the armed timer fired). */ + onTimerElapsed(uin: string): DebounceDecision { + const s = this.state(uin); + + if (!s.pending) { + return { kind: 'none' }; + } // cancelled before firing + + s.pending = false; + s.firedOffline = true; + return { kind: 'emit', event: 'offline' }; } - return { kind: 'none' }; // cold online / already up - } - /** The offline debounce window elapsed (the armed timer fired). */ - onTimerElapsed(uin: string): DebounceDecision { - const s = this.state(uin); - if (!s.pending) return { kind: 'none' }; // cancelled before firing - s.pending = false; - s.firedOffline = true; - return { kind: 'emit', event: 'offline' }; - } - - /** Drop a UIN's state (e.g. on dispose). */ - forget(uin: string): void { - this.states.delete(uin); - } + /** Drop a UIN's state (e.g. on dispose). */ + forget(uin: string): void { + this.states.delete(uin); + } } diff --git a/packages/core/src/notifications/manager.ts b/packages/core/src/notifications/manager.ts index 92eebde5..ceabc3f9 100644 --- a/packages/core/src/notifications/manager.ts +++ b/packages/core/src/notifications/manager.ts @@ -13,12 +13,12 @@ import { createLogger } from '@snowluma/common/logger'; import { loadOneBotConfig } from '@snowluma/onebot/config'; import type { BridgeManager } from '../bridge/manager'; import { - isEmailChannel, - loadNotificationsConfig, - renderTemplate, - type NotificationChannel, - type NotificationEvent, - type NotificationsConfig, + isEmailChannel, + loadNotificationsConfig, + renderTemplate, + type NotificationChannel, + type NotificationEvent, + type NotificationsConfig, } from './config'; import { DebounceMachine, type DebounceDecision } from './debounce'; import { formatSmtpError, parseRecipients, sendSmtpMail } from './smtp'; @@ -31,287 +31,360 @@ const FALLBACK_DEBOUNCE_SECONDS = 30; /** One delivery attempt; kept only in memory (the plan forbids persistence). */ export interface DeliveryRecord { - time: number; - uin: string; - event: NotificationEvent; - channelId: string; - ok: boolean; - status?: number; - error?: string; + time: number; + uin: string; + event: NotificationEvent; + channelId: string; + ok: boolean; + status?: number; + error?: string; } export interface PostResult { - ok: boolean; - status?: number; - error?: string; + ok: boolean; + status?: number; + error?: string; } export interface MailPayload { - host: string; - port: number; - secure: boolean; - user?: string; - pass?: string; - from: string; - to: string; - subject: string; - text: string; + host: string; + port: number; + secure: boolean; + user?: string; + pass?: string; + from: string; + to: string; + subject: string; + text: string; } export interface NotificationManagerDeps { - /** Global channel store (channels + debounceSeconds). */ - loadConfig: () => NotificationsConfig; - /** The channel ids a UIN has opted into. */ - loadChannelIds: (uin: string) => string[]; - /** Webhook delivery — never throws; failures come back as `{ ok: false }`. */ - post: (url: string, body: string, headers?: Record) => Promise; - /** SMTP delivery — optional so webhook-only tests stay lean. */ - sendMail?: (mail: MailPayload) => Promise; - now: () => number; - historyLimit?: number; + /** Global channel store (channels + debounceSeconds). */ + loadConfig: () => NotificationsConfig; + /** The channel ids a UIN has opted into. */ + loadChannelIds: (uin: string) => string[]; + /** Webhook delivery — never throws; failures come back as `{ ok: false }`. */ + post: (url: string, body: string, headers?: Record) => Promise; + /** SMTP delivery — optional so webhook-only tests stay lean. */ + sendMail?: (mail: MailPayload) => Promise; + now: () => number; + historyLimit?: number; } function errMsg(err: unknown): string { - return err instanceof Error ? err.message : String(err); + return err instanceof Error ? err.message : String(err); } /** * Pure: the channels a UIN should be notified through — globally enabled AND * opted into by the UIN — preserving config order. Exported for unit tests. */ -export function selectChannels(channels: NotificationChannel[], enabledIds: string[]): NotificationChannel[] { - const wanted = new Set(enabledIds); - return channels.filter((c) => c.enabled && wanted.has(c.id)); +export function selectChannels( + channels: NotificationChannel[], + enabledIds: string[], +): NotificationChannel[] { + const wanted = new Set(enabledIds); + return channels.filter((c) => c.enabled && wanted.has(c.id)); } export class NotificationManager { - private readonly deps: NotificationManagerDeps; - private readonly machine = new DebounceMachine(); - private readonly timers = new Map>(); - private readonly nicknames = new Map(); - private readonly history: DeliveryRecord[] = []; - private readonly historyLimit: number; - private disposed = false; + private readonly deps: NotificationManagerDeps; + private readonly machine = new DebounceMachine(); + private readonly timers = new Map>(); + private readonly nicknames = new Map(); + private readonly history: DeliveryRecord[] = []; + private readonly historyLimit: number; + private disposed = false; - constructor(deps: NotificationManagerDeps) { - this.deps = deps; - this.historyLimit = deps.historyLimit ?? DEFAULT_HISTORY_LIMIT; - } - - /** Subscribe to the global session online/offline edges. Register AFTER - * OneBotManager so the nickname fallback is already populated. */ - bind(bridgeManager: BridgeManager): void { - bridgeManager.addSessionStartedListener((uin, bridge) => this.handleOnline(uin, bridge.identity.nickname)); - bridgeManager.addSessionClosedListener((uin, bridge) => this.handleOffline(uin, bridge.identity.nickname)); - } - - handleOnline(uin: string, nickname?: string): void { - if (this.disposed) return; - if (nickname) this.nicknames.set(uin, nickname); - this.apply(uin, this.machine.onOnline(uin)); - } - - handleOffline(uin: string, nickname?: string): void { - if (this.disposed) return; - if (nickname) this.nicknames.set(uin, nickname); - this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds())); - } - - private debounceSeconds(): number { - try { - return this.deps.loadConfig().debounceSeconds; - } catch { - return FALLBACK_DEBOUNCE_SECONDS; + constructor(deps: NotificationManagerDeps) { + this.deps = deps; + this.historyLimit = deps.historyLimit ?? DEFAULT_HISTORY_LIMIT; } - } - private apply(uin: string, decision: DebounceDecision): void { - switch (decision.kind) { - case 'schedule': { - const existing = this.timers.get(uin); - if (existing) clearTimeout(existing); - const timer = setTimeout(() => { - this.timers.delete(uin); - this.apply(uin, this.machine.onTimerElapsed(uin)); - }, decision.delayMs); - // Don't let a pending notification timer keep the process alive. - if (typeof (timer as { unref?: () => void }).unref === 'function') { - (timer as { unref: () => void }).unref(); + /** Subscribe to the global session online/offline edges. Register AFTER + * OneBotManager so the nickname fallback is already populated. */ + bind(bridgeManager: BridgeManager): void { + bridgeManager.addSessionStartedListener((uin, bridge) => + this.handleOnline(uin, bridge.identity.nickname), + ); + bridgeManager.addSessionClosedListener((uin, bridge) => + this.handleOffline(uin, bridge.identity.nickname), + ); + } + + handleOnline(uin: string, nickname?: string): void { + if (this.disposed) { + return; } - this.timers.set(uin, timer); - break; - } - case 'cancel': { - const timer = this.timers.get(uin); - if (timer) { - clearTimeout(timer); - this.timers.delete(uin); + + if (nickname) { + this.nicknames.set(uin, nickname); } - break; - } - case 'emit': - void this.notify(uin, decision.event); - break; - case 'none': - break; + + this.apply(uin, this.machine.onOnline(uin)); } - } - /** Render + deliver a transition to every opted-in, enabled channel and record - * the outcome. Never throws (a bad channel can't break the others). */ - async notify(uin: string, event: NotificationEvent): Promise { - let channels: NotificationChannel[]; - try { - const cfg = this.deps.loadConfig(); - channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin)); - } catch (err) { - log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err)); - return; + handleOffline(uin: string, nickname?: string): void { + if (this.disposed) { + return; + } + + if (nickname) { + this.nicknames.set(uin, nickname); + } + + this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds())); } - if (channels.length === 0) return; - const nickname = this.nicknames.get(uin) || uin; - const vars: Record = { - uin, - nickname, - event, - time: new Date(this.deps.now()).toISOString(), - }; - - for (const ch of channels) { - const result = await this.deliver(ch, vars); - this.record({ - time: this.deps.now(), - uin, - event, - channelId: ch.id, - ok: result.ok, - status: result.status, - error: result.ok ? undefined : (result.error ?? (result.status ? `HTTP ${result.status}` : 'delivery failed')), - }); - if (!result.ok) { - log.warn('notify %s→%s channel=%s failed: %s', uin, event, ch.id, result.error ?? `HTTP ${result.status ?? '?'}`); - } + private debounceSeconds(): number { + try { + return this.deps.loadConfig().debounceSeconds; + } catch { + return FALLBACK_DEBOUNCE_SECONDS; + } } - } - private async deliver(ch: NotificationChannel, vars: Record): Promise { - try { - if (isEmailChannel(ch)) { - const send = this.deps.sendMail; - if (!send) return { ok: false, error: 'email delivery is not configured' }; - return await send({ - host: ch.smtpHost, - port: ch.smtpPort, - secure: ch.smtpSecure, - user: ch.smtpUser, - pass: ch.smtpPass, - from: ch.from, - to: ch.to, - subject: renderTemplate(ch.subjectTemplate, vars), - text: renderTemplate(ch.bodyTemplate, vars), - }); - } - return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers); - } catch (err) { - // Injected collaborators are contracted not to throw, but guard anyway. - return { ok: false, error: errMsg(err) }; + private apply(uin: string, decision: DebounceDecision): void { + switch (decision.kind) { + case 'schedule': { + const existing = this.timers.get(uin); + + if (existing) { + clearTimeout(existing); + } + + const timer = setTimeout(() => { + this.timers.delete(uin); + this.apply(uin, this.machine.onTimerElapsed(uin)); + }, decision.delayMs); + + // Don't let a pending notification timer keep the process alive. + if (typeof (timer as { unref?: () => void }).unref === 'function') { + (timer as { unref: () => void }).unref(); + } + + this.timers.set(uin, timer); + break; + } + + case 'cancel': { + const timer = this.timers.get(uin); + + if (timer) { + clearTimeout(timer); + this.timers.delete(uin); + } + + break; + } + + case 'emit': + void this.notify(uin, decision.event); + break; + case 'none': + break; + } } - } - /** Send a one-off test to a single channel by id — ignores `enabled` and the - * per-UIN opt-in (you test a channel before wiring it up), with sample - * variables. Reuses the real render+deliver path; NOT recorded to history. - * `found:false` means the channel id is unknown. */ - async testSend(channelId: string): Promise { - let channel: NotificationChannel | undefined; - try { - channel = this.deps.loadConfig().channels.find((c) => c.id === channelId); - } catch (err) { - return { ok: false, found: false, error: errMsg(err) }; + /** Render + deliver a transition to every opted-in, enabled channel and record + * the outcome. Never throws (a bad channel can't break the others). */ + async notify(uin: string, event: NotificationEvent): Promise { + let channels: NotificationChannel[]; + + try { + const cfg = this.deps.loadConfig(); + channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin)); + } catch (err) { + log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err)); + return; + } + + if (channels.length === 0) { + return; + } + + const nickname = this.nicknames.get(uin) || uin; + const vars: Record = { + uin, + nickname, + event, + time: new Date(this.deps.now()).toISOString(), + }; + + for (const ch of channels) { + const result = await this.deliver(ch, vars); + this.record({ + time: this.deps.now(), + uin, + event, + channelId: ch.id, + ok: result.ok, + status: result.status, + error: result.ok + ? undefined + : (result.error ?? + (result.status ? `HTTP ${result.status}` : 'delivery failed')), + }); + + if (!result.ok) { + log.warn( + 'notify %s→%s channel=%s failed: %s', + uin, + event, + ch.id, + result.error ?? `HTTP ${result.status ?? '?'}`, + ); + } + } } - if (!channel) return { ok: false, found: false }; - const vars = { - uin: '10000', - nickname: '测试账号', - event: 'offline' as const, - time: new Date(this.deps.now()).toISOString(), - }; - return { ...(await this.deliver(channel, vars)), found: true }; - } - private record(rec: DeliveryRecord): void { - this.history.push(rec); - if (this.history.length > this.historyLimit) { - this.history.splice(0, this.history.length - this.historyLimit); + private async deliver( + ch: NotificationChannel, + vars: Record, + ): Promise { + try { + if (isEmailChannel(ch)) { + const send = this.deps.sendMail; + + if (!send) { + return { ok: false, error: 'email delivery is not configured' }; + } + + return await send({ + host: ch.smtpHost, + port: ch.smtpPort, + secure: ch.smtpSecure, + user: ch.smtpUser, + pass: ch.smtpPass, + from: ch.from, + to: ch.to, + subject: renderTemplate(ch.subjectTemplate, vars), + text: renderTemplate(ch.bodyTemplate, vars), + }); + } + + return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers); + } catch (err) { + // Injected collaborators are contracted not to throw, but guard anyway. + return { ok: false, error: errMsg(err) }; + } } - } - /** Most-recent-first delivery history (capped at the buffer size). */ - getRecent(limit = this.historyLimit): DeliveryRecord[] { - const n = Math.max(0, Math.min(Math.trunc(limit) || 0, this.history.length)); - return this.history.slice(this.history.length - n).reverse(); - } + /** Send a one-off test to a single channel by id — ignores `enabled` and the + * per-UIN opt-in (you test a channel before wiring it up), with sample + * variables. Reuses the real render+deliver path; NOT recorded to history. + * `found:false` means the channel id is unknown. */ + async testSend(channelId: string): Promise { + let channel: NotificationChannel | undefined; - dispose(): void { - if (this.disposed) return; - this.disposed = true; - for (const timer of this.timers.values()) clearTimeout(timer); - this.timers.clear(); - } + try { + channel = this.deps.loadConfig().channels.find((c) => c.id === channelId); + } catch (err) { + return { ok: false, found: false, error: errMsg(err) }; + } + + if (!channel) { + return { ok: false, found: false }; + } + + const vars = { + uin: '10000', + nickname: '测试账号', + event: 'offline' as const, + time: new Date(this.deps.now()).toISOString(), + }; + return { ...(await this.deliver(channel, vars)), found: true }; + } + + private record(rec: DeliveryRecord): void { + this.history.push(rec); + + if (this.history.length > this.historyLimit) { + this.history.splice(0, this.history.length - this.historyLimit); + } + } + + /** Most-recent-first delivery history (capped at the buffer size). */ + getRecent(limit = this.historyLimit): DeliveryRecord[] { + const n = Math.max(0, Math.min(Math.trunc(limit) || 0, this.history.length)); + return this.history.slice(this.history.length - n).reverse(); + } + + dispose(): void { + if (this.disposed) { + return; + } + + this.disposed = true; + + for (const timer of this.timers.values()) { + clearTimeout(timer); + } + + this.timers.clear(); + } } /** Default outbound POST: a single attempt with a timeout, JSON content-type * (the common case for 钉钉/Discord/飞书). Never throws. */ export function createDefaultPost( - timeoutMs = positiveIntEnv('SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', DEFAULT_POST_TIMEOUT_MS), + timeoutMs = positiveIntEnv('SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', DEFAULT_POST_TIMEOUT_MS), ): NotificationManagerDeps['post'] { - return async (url, body, headers) => { - try { - const res = await fetch(url, { - method: 'POST', - headers: { 'Content-Type': 'application/json', ...headers }, - body, - signal: AbortSignal.timeout(timeoutMs), - }); - return { ok: res.ok, status: res.status, error: res.ok ? undefined : `HTTP ${res.status}` }; - } catch (err) { - return { ok: false, error: errMsg(err) }; - } - }; + return async (url, body, headers) => { + try { + const res = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...headers }, + body, + signal: AbortSignal.timeout(timeoutMs), + }); + return { + ok: res.ok, + status: res.status, + error: res.ok ? undefined : `HTTP ${res.status}`, + }; + } catch (err) { + return { ok: false, error: errMsg(err) }; + } + }; } const DEFAULT_SMTP_TIMEOUT_MS = 15_000; /** Default SMTP send. Never throws. */ -export function createDefaultSendMail(timeoutMs = DEFAULT_SMTP_TIMEOUT_MS): NonNullable { - return async (mail) => { - try { - await sendSmtpMail({ - host: mail.host, - port: mail.port, - secure: mail.secure, - user: mail.user, - pass: mail.pass, - from: mail.from, - to: parseRecipients(mail.to), - subject: mail.subject, - body: mail.text, - }, { timeoutMs }); - return { ok: true }; - } catch (err) { - return { ok: false, error: formatSmtpError(err, mail.host, mail.port) }; - } - }; +export function createDefaultSendMail( + timeoutMs = DEFAULT_SMTP_TIMEOUT_MS, +): NonNullable { + return async (mail) => { + try { + await sendSmtpMail( + { + host: mail.host, + port: mail.port, + secure: mail.secure, + user: mail.user, + pass: mail.pass, + from: mail.from, + to: parseRecipients(mail.to), + subject: mail.subject, + body: mail.text, + }, + { timeoutMs }, + ); + return { ok: true }; + } catch (err) { + return { ok: false, error: formatSmtpError(err, mail.host, mail.port) }; + } + }; } /** The real, fully-wired singleton. */ export function createNotificationManager(): NotificationManager { - return new NotificationManager({ - loadConfig: loadNotificationsConfig, - loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [], - post: createDefaultPost(), - sendMail: createDefaultSendMail(), - now: () => Date.now(), - }); + return new NotificationManager({ + loadConfig: loadNotificationsConfig, + loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [], + post: createDefaultPost(), + sendMail: createDefaultSendMail(), + now: () => Date.now(), + }); } diff --git a/packages/core/src/notifications/smtp.ts b/packages/core/src/notifications/smtp.ts index 4780ead9..f626375a 100644 --- a/packages/core/src/notifications/smtp.ts +++ b/packages/core/src/notifications/smtp.ts @@ -9,375 +9,474 @@ const CRLF = '\r\n'; const DEFAULT_TIMEOUT_MS = 15_000; export class SmtpError extends Error { - readonly responseCode?: number; - readonly code?: string; + readonly responseCode?: number; + readonly code?: string; - constructor(message: string, opts?: { responseCode?: number; code?: string }) { - super(message); - this.name = 'SmtpError'; - this.responseCode = opts?.responseCode; - this.code = opts?.code; - } + constructor(message: string, opts?: { responseCode?: number; code?: string }) { + super(message); + this.name = 'SmtpError'; + this.responseCode = opts?.responseCode; + this.code = opts?.code; + } } export interface SmtpMail { - host: string; - port: number; - secure: boolean; - user?: string; - pass?: string; - from: string; - to: string[]; - subject: string; - body: string; + host: string; + port: number; + secure: boolean; + user?: string; + pass?: string; + from: string; + to: string[]; + subject: string; + body: string; } export interface SendSmtpOptions { - timeoutMs?: number; - /** Defaults true. Tests against a self-signed mock pass false. */ - rejectUnauthorized?: boolean; + timeoutMs?: number; + /** Defaults true. Tests against a self-signed mock pass false. */ + rejectUnauthorized?: boolean; } export function looksLikeEmail(value: string): boolean { - return /^[^\s<>@]+@[^\s<>@]+$/.test(value); + return /^[^\s<>@]+@[^\s<>@]+$/.test(value); } /** Address from `Name ` or a bare addr; null if neither is usable. */ export function extractAddress(value: string): string | null { - const trimmed = value.trim(); - if (!trimmed) return null; - const angled = /<([^<>]+)>/.exec(trimmed); - const addr = (angled ? angled[1] : trimmed).trim(); - return looksLikeEmail(addr) ? addr : null; + const trimmed = value.trim(); + + if (!trimmed) { + return null; + } + + const angled = /<([^<>]+)>/.exec(trimmed); + const addr = (angled ? angled[1] : trimmed).trim(); + return looksLikeEmail(addr) ? addr : null; } /** Split a comma / semicolon / newline list and keep unique addresses. */ export function parseRecipients(value: string): string[] { - const seen = new Set(); - const out: string[] = []; - for (const part of value.split(/[,;\n]+/)) { - const addr = extractAddress(part); - if (!addr) continue; - const key = addr.toLowerCase(); - if (seen.has(key)) continue; - seen.add(key); - out.push(addr); - } - return out; + const seen = new Set(); + const out: string[] = []; + + for (const part of value.split(/[,;\n]+/)) { + const addr = extractAddress(part); + + if (!addr) { + continue; + } + + const key = addr.toLowerCase(); + + if (seen.has(key)) { + continue; + } + + seen.add(key); + out.push(addr); + } + + return out; } function encodeHeader(value: string): string { - if (/^[\x20-\x7E]*$/.test(value) && !/[\r\n]/.test(value)) return value; - return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`; + if (/^[\x20-\x7E]*$/.test(value) && !/[\r\n]/.test(value)) { + return value; + } + + return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`; } function rfc5322Date(d: Date): string { - return d.toUTCString().replace(/GMT$/, '+0000'); + return d.toUTCString().replace(/GMT$/, '+0000'); } function wrap76(b64: string): string { - return b64.replace(/.{1,76}/g, (line) => `${line}\r\n`).trimEnd(); + return b64.replace(/.{1,76}/g, (line) => `${line}\r\n`).trimEnd(); } function isHtmlBody(body: string): boolean { - return /^\s*`; - const headers = [ - `From: ${mail.from.trim() || (fromAddr ? `<${fromAddr}>` : '')}`, - `To: ${toHeader}`, - `Subject: ${encodeHeader(mail.subject)}`, - `Date: ${rfc5322Date(now)}`, - `Message-ID: ${id}`, - 'MIME-Version: 1.0', - `Content-Type: ${html ? 'text/html' : 'text/plain'}; charset=UTF-8`, - 'Content-Transfer-Encoding: base64', - ]; - const body = wrap76(Buffer.from(mail.body, 'utf8').toString('base64')); - return `${headers.join(CRLF)}${CRLF}${CRLF}${body}${CRLF}`; + const fromAddr = extractAddress(mail.from); + const toHeader = mail.to.join(', '); + const html = isHtmlBody(mail.body); + const id = `<${now.getTime()}.${Math.random().toString(36).slice(2, 10)}@snowluma>`; + const headers = [ + `From: ${mail.from.trim() || (fromAddr ? `<${fromAddr}>` : '')}`, + `To: ${toHeader}`, + `Subject: ${encodeHeader(mail.subject)}`, + `Date: ${rfc5322Date(now)}`, + `Message-ID: ${id}`, + 'MIME-Version: 1.0', + `Content-Type: ${html ? 'text/html' : 'text/plain'}; charset=UTF-8`, + 'Content-Transfer-Encoding: base64', + ]; + const body = wrap76(Buffer.from(mail.body, 'utf8').toString('base64')); + return `${headers.join(CRLF)}${CRLF}${CRLF}${body}${CRLF}`; } interface SmtpReply { - code: number; - lines: string[]; - text: string; + code: number; + lines: string[]; + text: string; } function consumeReply(buf: string): { reply: SmtpReply; rest: string } | null { - let offset = 0; - const lines: string[] = []; - let code = 0; - while (offset < buf.length) { - const nl = buf.indexOf('\n', offset); - if (nl === -1) return null; - const line = buf.slice(offset, nl).replace(/\r$/, ''); - offset = nl + 1; - const m = /^(\d{3})([ -])(.*)$/.exec(line); - if (!m) continue; - code = Number(m[1]); - lines.push(m[3]); - if (m[2] === ' ') { - return { reply: { code, lines, text: lines.join('\n') }, rest: buf.slice(offset) }; + let offset = 0; + const lines: string[] = []; + let code = 0; + + while (offset < buf.length) { + const nl = buf.indexOf('\n', offset); + + if (nl === -1) { + return null; + } + + const line = buf.slice(offset, nl).replace(/\r$/, ''); + offset = nl + 1; + const m = /^(\d{3})([ -])(.*)$/.exec(line); + + if (!m) { + continue; + } + + code = Number(m[1]); + lines.push(m[3]); + + if (m[2] === ' ') { + return { reply: { code, lines, text: lines.join('\n') }, rest: buf.slice(offset) }; + } } - } - return null; + + return null; } type SmtpSock = net.Socket | tls.TLSSocket; function parseCapabilities(reply: SmtpReply): { starttls: boolean; auth: Set } { - const auth = new Set(); - let starttls = false; - for (const line of reply.lines) { - const u = line.toUpperCase(); - if (u === 'STARTTLS' || u.startsWith('STARTTLS ')) starttls = true; - if (u.startsWith('AUTH ')) { - for (const mech of u.slice(5).split(/\s+/)) { - if (mech) auth.add(mech); - } + const auth = new Set(); + let starttls = false; + + for (const line of reply.lines) { + const u = line.toUpperCase(); + + if (u === 'STARTTLS' || u.startsWith('STARTTLS ')) { + starttls = true; + } + + if (u.startsWith('AUTH ')) { + for (const mech of u.slice(5).split(/\s+/)) { + if (mech) { + auth.add(mech); + } + } + } } - } - return { starttls, auth }; + + return { starttls, auth }; } function connectSocket( - host: string, - port: number, - secure: boolean, - timeoutMs: number, - rejectUnauthorized: boolean, + host: string, + port: number, + secure: boolean, + timeoutMs: number, + rejectUnauthorized: boolean, ): Promise { - return new Promise((resolve, reject) => { - const sock: SmtpSock = secure - ? tls.connect({ - host, - port, - servername: net.isIP(host) === 0 ? host : undefined, - rejectUnauthorized, - }) - : net.connect({ host, port }); - const fail = (err: Error) => { - sock.destroy(); - reject(err); - }; - sock.setTimeout(timeoutMs); - sock.once('timeout', () => fail(new SmtpError('SMTP connection timed out', { code: 'ETIMEDOUT' }))); - sock.once('error', fail); - sock.once(secure ? 'secureConnect' : 'connect', () => { - sock.removeAllListeners('timeout'); - sock.removeAllListeners('error'); - resolve(sock); + return new Promise((resolve, reject) => { + const sock: SmtpSock = secure + ? tls.connect({ + host, + port, + servername: net.isIP(host) === 0 ? host : undefined, + rejectUnauthorized, + }) + : net.connect({ host, port }); + + const fail = (err: Error) => { + sock.destroy(); + reject(err); + }; + + sock.setTimeout(timeoutMs); + sock.once('timeout', () => + fail(new SmtpError('SMTP connection timed out', { code: 'ETIMEDOUT' })), + ); + sock.once('error', fail); + sock.once(secure ? 'secureConnect' : 'connect', () => { + sock.removeAllListeners('timeout'); + sock.removeAllListeners('error'); + resolve(sock); + }); }); - }); } function upgradeTls( - socket: net.Socket, - host: string, - timeoutMs: number, - rejectUnauthorized: boolean, + socket: net.Socket, + host: string, + timeoutMs: number, + rejectUnauthorized: boolean, ): Promise { - return new Promise((resolve, reject) => { - const tlsSocket = tls.connect({ - socket, - servername: net.isIP(host) === 0 ? host : undefined, - rejectUnauthorized, - }, () => resolve(tlsSocket)); - tlsSocket.setTimeout(timeoutMs); - tlsSocket.once('timeout', () => { - tlsSocket.destroy(); - reject(new SmtpError('SMTP STARTTLS timed out', { code: 'ETIMEDOUT' })); + return new Promise((resolve, reject) => { + const tlsSocket = tls.connect( + { + socket, + servername: net.isIP(host) === 0 ? host : undefined, + rejectUnauthorized, + }, + () => resolve(tlsSocket), + ); + tlsSocket.setTimeout(timeoutMs); + tlsSocket.once('timeout', () => { + tlsSocket.destroy(); + reject(new SmtpError('SMTP STARTTLS timed out', { code: 'ETIMEDOUT' })); + }); + tlsSocket.once('error', reject); }); - tlsSocket.once('error', reject); - }); } class SmtpSession { - private buf = ''; + private buf = ''; - constructor(private socket: SmtpSock) {} + constructor(private socket: SmtpSock) {} - destroy(): void { - this.socket.destroy(); - } - - attachTimeout(timeoutMs: number, onTimeout: () => void): void { - this.socket.setTimeout(timeoutMs); - this.socket.once('timeout', onTimeout); - } - - async read(): Promise { - const ready = consumeReply(this.buf); - if (ready) { - this.buf = ready.rest; - return ready.reply; + destroy(): void { + this.socket.destroy(); } - return new Promise((resolve, reject) => { - const onData = (chunk: Buffer) => { - this.buf += chunk.toString('utf8'); - const got = consumeReply(this.buf); - if (!got) return; - this.buf = got.rest; - cleanup(); - resolve(got.reply); - }; - const onError = (err: Error) => { - cleanup(); - reject(err); - }; - const onClose = () => { - cleanup(); - reject(new SmtpError('SMTP connection closed')); - }; - const cleanup = () => { - this.socket.removeListener('data', onData); - this.socket.removeListener('error', onError); - this.socket.removeListener('close', onClose); - }; - this.socket.on('data', onData); - this.socket.once('error', onError); - this.socket.once('close', onClose); - }); - } - write(data: string): void { - this.socket.write(data); - } - - async command(line: string, ok: (code: number) => boolean, label?: string): Promise { - this.write(line + CRLF); - const reply = await this.read(); - if (!ok(reply.code)) { - const name = label ?? line.split(' ')[0] ?? 'SMTP'; - throw new SmtpError(`${name} failed: ${reply.code} ${reply.text}`.trim(), { - responseCode: reply.code, - }); + attachTimeout(timeoutMs: number, onTimeout: () => void): void { + this.socket.setTimeout(timeoutMs); + this.socket.once('timeout', onTimeout); } - return reply; - } - replaceSocket(next: SmtpSock): void { - this.socket = next; - this.buf = ''; - } + async read(): Promise { + const ready = consumeReply(this.buf); + + if (ready) { + this.buf = ready.rest; + return ready.reply; + } + + return new Promise((resolve, reject) => { + const onData = (chunk: Buffer) => { + this.buf += chunk.toString('utf8'); + const got = consumeReply(this.buf); + + if (!got) { + return; + } + + this.buf = got.rest; + cleanup(); + resolve(got.reply); + }; + + const onError = (err: Error) => { + cleanup(); + reject(err); + }; + + const onClose = () => { + cleanup(); + reject(new SmtpError('SMTP connection closed')); + }; + + const cleanup = () => { + this.socket.removeListener('data', onData); + this.socket.removeListener('error', onError); + this.socket.removeListener('close', onClose); + }; + + this.socket.on('data', onData); + this.socket.once('error', onError); + this.socket.once('close', onClose); + }); + } + + write(data: string): void { + this.socket.write(data); + } + + async command(line: string, ok: (code: number) => boolean, label?: string): Promise { + this.write(line + CRLF); + const reply = await this.read(); + + if (!ok(reply.code)) { + const name = label ?? line.split(' ')[0] ?? 'SMTP'; + throw new SmtpError(`${name} failed: ${reply.code} ${reply.text}`.trim(), { + responseCode: reply.code, + }); + } + + return reply; + } + + replaceSocket(next: SmtpSock): void { + this.socket = next; + this.buf = ''; + } } export function formatSmtpError(err: unknown, host: string, port: number): string { - if (err instanceof SmtpError) { - if (err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND' || err.code === 'ETIMEDOUT') { - return `无法连接 SMTP:${host}:${port}`; + if (err instanceof SmtpError) { + if (err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND' || err.code === 'ETIMEDOUT') { + return `无法连接 SMTP:${host}:${port}`; + } + + if (err.responseCode === 535) { + return 'SMTP 认证失败'; + } + + return err.message; } - if (err.responseCode === 535) return 'SMTP 认证失败'; - return err.message; - } - if (err instanceof Error) { - const code = (err as NodeJS.ErrnoException).code; - if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'ETIMEDOUT') { - return `无法连接 SMTP:${host}:${port}`; + + if (err instanceof Error) { + const code = (err as NodeJS.ErrnoException).code; + + if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'ETIMEDOUT') { + return `无法连接 SMTP:${host}:${port}`; + } + + if (/self-signed|unable to verify/i.test(err.message)) { + return `SMTP 证书不受信任:${host}`; + } + + return err.message || '邮件发送失败'; } - if (/self-signed|unable to verify/i.test(err.message)) { - return `SMTP 证书不受信任:${host}`; - } - return err.message || '邮件发送失败'; - } - return '邮件发送失败'; + + return '邮件发送失败'; } export async function sendSmtpMail(mail: SmtpMail, opts: SendSmtpOptions = {}): Promise { - const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS; - const rejectUnauthorized = opts.rejectUnauthorized ?? true; - const fromAddr = extractAddress(mail.from); - if (!fromAddr) throw new SmtpError('invalid from address'); - if (mail.to.length === 0) throw new SmtpError('no recipients'); + const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const rejectUnauthorized = opts.rejectUnauthorized ?? true; + const fromAddr = extractAddress(mail.from); - let sock = await connectSocket(mail.host, mail.port, mail.secure, timeoutMs, rejectUnauthorized); - const session = new SmtpSession(sock); - let finished = false; - const failTimeout = () => { - if (finished) return; - session.destroy(); - }; - session.attachTimeout(timeoutMs, failTimeout); - - try { - const greeting = await session.read(); - if (greeting.code !== 220) { - throw new SmtpError(`SMTP greeting failed: ${greeting.code} ${greeting.text}`.trim(), { - responseCode: greeting.code, - }); + if (!fromAddr) { + throw new SmtpError('invalid from address'); } - const ehlo = async () => session.command('EHLO [127.0.0.1]', (c) => c === 250); - let caps = parseCapabilities(await ehlo()); - - if (!mail.secure && caps.starttls) { - await session.command('STARTTLS', (c) => c === 220); - const upgraded = await upgradeTls(sock as net.Socket, mail.host, timeoutMs, rejectUnauthorized); - session.replaceSocket(upgraded); - session.attachTimeout(timeoutMs, failTimeout); - sock = upgraded; - caps = parseCapabilities(await ehlo()); + if (mail.to.length === 0) { + throw new SmtpError('no recipients'); } - const user = mail.user?.trim() ?? ''; - if (user) { - await authenticate(session, caps.auth, user, mail.pass ?? ''); - } + let sock = await connectSocket( + mail.host, + mail.port, + mail.secure, + timeoutMs, + rejectUnauthorized, + ); + const session = new SmtpSession(sock); + let finished = false; + + const failTimeout = () => { + if (finished) { + return; + } + + session.destroy(); + }; + + session.attachTimeout(timeoutMs, failTimeout); - await session.command(`MAIL FROM:<${fromAddr}>`, (c) => c === 250); - for (const rcpt of mail.to) { - await session.command(`RCPT TO:<${rcpt}>`, (c) => c === 250 || c === 251); - } - await session.command('DATA', (c) => c === 354); - session.write(dotStuff(buildMimeMessage(mail))); - await session.command('.', (c) => c === 250, 'DATA'); try { - await session.command('QUIT', (c) => c === 221); - } catch { - // Some relays drop the socket after 250; delivery already succeeded. + const greeting = await session.read(); + + if (greeting.code !== 220) { + throw new SmtpError(`SMTP greeting failed: ${greeting.code} ${greeting.text}`.trim(), { + responseCode: greeting.code, + }); + } + + const ehlo = async () => session.command('EHLO [127.0.0.1]', (c) => c === 250); + let caps = parseCapabilities(await ehlo()); + + if (!mail.secure && caps.starttls) { + await session.command('STARTTLS', (c) => c === 220); + const upgraded = await upgradeTls( + sock as net.Socket, + mail.host, + timeoutMs, + rejectUnauthorized, + ); + session.replaceSocket(upgraded); + session.attachTimeout(timeoutMs, failTimeout); + sock = upgraded; + caps = parseCapabilities(await ehlo()); + } + + const user = mail.user?.trim() ?? ''; + + if (user) { + await authenticate(session, caps.auth, user, mail.pass ?? ''); + } + + await session.command(`MAIL FROM:<${fromAddr}>`, (c) => c === 250); + + for (const rcpt of mail.to) { + await session.command(`RCPT TO:<${rcpt}>`, (c) => c === 250 || c === 251); + } + + await session.command('DATA', (c) => c === 354); + session.write(dotStuff(buildMimeMessage(mail))); + await session.command('.', (c) => c === 250, 'DATA'); + + try { + await session.command('QUIT', (c) => c === 221); + } catch { + // Some relays drop the socket after 250; delivery already succeeded. + } + + finished = true; + } catch (err) { + finished = true; + throw err; + } finally { + session.destroy(); } - finished = true; - } catch (err) { - finished = true; - throw err; - } finally { - session.destroy(); - } } async function authenticate( - session: SmtpSession, - mechs: Set, - user: string, - pass: string, + session: SmtpSession, + mechs: Set, + user: string, + pass: string, ): Promise { - const hasPlain = mechs.has('PLAIN'); - const hasLogin = mechs.has('LOGIN'); - if (hasPlain || !hasLogin) { - try { - const token = Buffer.from(`\0${user}\0${pass}`, 'utf8').toString('base64'); - await session.command(`AUTH PLAIN ${token}`, (c) => c === 235, 'AUTH'); - return; - } catch (err) { - if (hasPlain && !hasLogin) throw err; - if (err instanceof SmtpError && err.responseCode === 535) throw err; + const hasPlain = mechs.has('PLAIN'); + const hasLogin = mechs.has('LOGIN'); + + if (hasPlain || !hasLogin) { + try { + const token = Buffer.from(`\0${user}\0${pass}`, 'utf8').toString('base64'); + await session.command(`AUTH PLAIN ${token}`, (c) => c === 235, 'AUTH'); + return; + } catch (err) { + if (hasPlain && !hasLogin) { + throw err; + } + + if (err instanceof SmtpError && err.responseCode === 535) { + throw err; + } + } } - } - await loginAuth(session, user, pass); + + await loginAuth(session, user, pass); } async function loginAuth(session: SmtpSession, user: string, pass: string): Promise { - await session.command('AUTH LOGIN', (c) => c === 334, 'AUTH'); - await session.command(Buffer.from(user, 'utf8').toString('base64'), (c) => c === 334, 'AUTH'); - await session.command(Buffer.from(pass, 'utf8').toString('base64'), (c) => c === 235, 'AUTH'); + await session.command('AUTH LOGIN', (c) => c === 334, 'AUTH'); + await session.command(Buffer.from(user, 'utf8').toString('base64'), (c) => c === 334, 'AUTH'); + await session.command(Buffer.from(pass, 'utf8').toString('base64'), (c) => c === 235, 'AUTH'); } diff --git a/packages/core/src/sys-face-catalog.ts b/packages/core/src/sys-face-catalog.ts index e04a9f6f..bbe23e55 100644 --- a/packages/core/src/sys-face-catalog.ts +++ b/packages/core/src/sys-face-catalog.ts @@ -1,9 +1,9 @@ import path from 'node:path'; import { createLogger } from '@snowluma/common/logger'; import { - SysFaceStore, - sysFaceStore, - type SysFaceCatalogStorage, + SysFaceStore, + sysFaceStore, + type SysFaceCatalogStorage, } from '@snowluma/protocol/sys-face-store'; import { JsonSysFaceCatalogStorage } from '@snowluma/protocol/sys-face-storage'; import type { BridgeManager } from './bridge/manager'; @@ -11,30 +11,32 @@ import type { BridgeManager } from './bridge/manager'; const log = createLogger('SysFace'); export interface SystemFaceCatalogBindingOptions { - store?: SysFaceStore; - storage?: SysFaceCatalogStorage; - dataRoot?: string; + store?: SysFaceStore; + storage?: SysFaceCatalogStorage; + dataRoot?: string; } /** Attach the shared system-face catalog to Bridge login edges. The first * account restores + refreshes it; later accounts reuse the same result. */ export function bindSystemFaceCatalog( - manager: BridgeManager, - options: SystemFaceCatalogBindingOptions = {}, + manager: BridgeManager, + options: SystemFaceCatalogBindingOptions = {}, ): void { - const store = options.store ?? sysFaceStore; - const storage = options.storage ?? new JsonSysFaceCatalogStorage( - path.join(options.dataRoot ?? 'data', 'sys-face-catalog.json'), - ); - store.configureStorage(storage); + const store = options.store ?? sysFaceStore; + const storage = + options.storage ?? + new JsonSysFaceCatalogStorage( + path.join(options.dataRoot ?? 'data', 'sys-face-catalog.json'), + ); + store.configureStorage(storage); - manager.addSessionStartedListener((uin, bridge) => { - void store.prewarm(bridge).catch((error) => { - log.error( - 'system face catalog login prewarm failed: uin=%s error=%s', - uin, - error instanceof Error ? (error.stack ?? error.message) : String(error), - ); + manager.addSessionStartedListener((uin, bridge) => { + void store.prewarm(bridge).catch((error) => { + log.error( + 'system face catalog login prewarm failed: uin=%s error=%s', + uin, + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + }); }); - }); } diff --git a/packages/core/src/webui/auth.ts b/packages/core/src/webui/auth.ts index ad1fa4fc..165d0f11 100644 --- a/packages/core/src/webui/auth.ts +++ b/packages/core/src/webui/auth.ts @@ -3,10 +3,10 @@ import { randomBytes, scryptSync, timingSafeEqual } from 'crypto'; import fs from 'fs'; import path from 'path'; import { - parseTotpStateLenient, - prepareTotpStateForRestore, - rewrapTotpSecret, - type TotpPersistedState, + parseTotpStateLenient, + prepareTotpStateForRestore, + rewrapTotpSecret, + type TotpPersistedState, } from './totp'; const log = createLogger('WebUI.Auth'); @@ -22,53 +22,62 @@ const SCRYPT_P = 1; const DEV_PASSWORD = 'snowluma-dev'; export function isDevAuthMode(): boolean { - return process.env.SNOWLUMA_DEV_MODE === '1'; + return process.env.SNOWLUMA_DEV_MODE === '1'; } function envBootstrapPassword(): string | null { - const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD; - if (!raw || typeof raw !== 'string') return null; - if (raw.length < 8) return null; - return raw; + const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD; + + if (!raw || typeof raw !== 'string') { + return null; + } + + if (raw.length < 8) { + return null; + } + + return raw; } export interface WebuiAuthState { - passwordHash: string; // hex - passwordSalt: string; // hex - mustChangePassword: boolean; - generatedAt: string; - updatedAt: string; - totp?: TotpPersistedState; + passwordHash: string; // hex + passwordSalt: string; // hex + mustChangePassword: boolean; + generatedAt: string; + updatedAt: string; + totp?: TotpPersistedState; } export interface PasswordRule { - id: string; - label: string; - test: (pwd: string) => boolean; + id: string; + label: string; + test: (pwd: string) => boolean; } export const PASSWORD_RULES: PasswordRule[] = [ - { id: 'length', label: '长度不少于 10 位', test: (p) => p.length >= 10 }, - { id: 'lower', label: '包含小写字母', test: (p) => /[a-z]/.test(p) }, - { id: 'upper', label: '包含大写字母', test: (p) => /[A-Z]/.test(p) }, - { id: 'special', label: '包含特殊符号 (!@#$%…)', test: (p) => /[^A-Za-z0-9\s]/.test(p) }, - { id: 'no-space', label: '不包含空格', test: (p) => !/\s/.test(p) && p.length > 0 }, + { id: 'length', label: '长度不少于 10 位', test: (p) => p.length >= 10 }, + { id: 'lower', label: '包含小写字母', test: (p) => /[a-z]/.test(p) }, + { id: 'upper', label: '包含大写字母', test: (p) => /[A-Z]/.test(p) }, + { id: 'special', label: '包含特殊符号 (!@#$%…)', test: (p) => /[^A-Za-z0-9\s]/.test(p) }, + { id: 'no-space', label: '不包含空格', test: (p) => !/\s/.test(p) && p.length > 0 }, ]; -export function evaluatePasswordRules(password: string): { id: string; label: string; ok: boolean }[] { - return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, ok: r.test(password) })); +export function evaluatePasswordRules( + password: string, +): { id: string; label: string; ok: boolean }[] { + return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, ok: r.test(password) })); } export function isStrongPassword(password: string): boolean { - return PASSWORD_RULES.every((r) => r.test(password)); + return PASSWORD_RULES.every((r) => r.test(password)); } function hashPassword(password: string, salt: Buffer): Buffer { - return scryptSync(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P }); + return scryptSync(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P }); } function ensureConfigDir(): void { - fs.mkdirSync(CONFIG_DIR, { recursive: true }); + fs.mkdirSync(CONFIG_DIR, { recursive: true }); } /** @@ -79,265 +88,332 @@ function ensureConfigDir(): void { * operator would be locked out after a restore. */ export function prepareWebuiAuthStateForRestore(value: unknown): WebuiAuthState { - if (!value || typeof value !== 'object' || Array.isArray(value)) { - throw new Error('credential state must be an object'); - } - const v = value as Record; - if (typeof v.passwordHash !== 'string' || !/^[0-9a-f]{128}$/i.test(v.passwordHash)) { - throw new Error('passwordHash must be exactly 128 hexadecimal characters'); - } - if (typeof v.passwordSalt !== 'string' || !/^[0-9a-f]{32}$/i.test(v.passwordSalt)) { - throw new Error('passwordSalt must be exactly 32 hexadecimal characters'); - } - if (typeof v.mustChangePassword !== 'boolean') { - throw new Error('mustChangePassword must be a boolean'); - } - if (typeof v.generatedAt !== 'string' || !Number.isFinite(Date.parse(v.generatedAt))) { - throw new Error('generatedAt must be a valid timestamp'); - } - if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) { - throw new Error('updatedAt must be a valid timestamp'); - } - const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt', 'totp']); - const unknown = Object.keys(v).find((key) => !allowed.has(key)); - if (unknown) throw new Error(`unknown field $.${unknown}`); - const state: WebuiAuthState = { - passwordHash: v.passwordHash, - passwordSalt: v.passwordSalt, - mustChangePassword: v.mustChangePassword, - generatedAt: v.generatedAt, - updatedAt: v.updatedAt, - }; - if (!Object.prototype.hasOwnProperty.call(v, 'totp') || v.totp === undefined) { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new Error('credential state must be an object'); + } + + const v = value as Record; + + if (typeof v.passwordHash !== 'string' || !/^[0-9a-f]{128}$/i.test(v.passwordHash)) { + throw new Error('passwordHash must be exactly 128 hexadecimal characters'); + } + + if (typeof v.passwordSalt !== 'string' || !/^[0-9a-f]{32}$/i.test(v.passwordSalt)) { + throw new Error('passwordSalt must be exactly 32 hexadecimal characters'); + } + + if (typeof v.mustChangePassword !== 'boolean') { + throw new Error('mustChangePassword must be a boolean'); + } + + if (typeof v.generatedAt !== 'string' || !Number.isFinite(Date.parse(v.generatedAt))) { + throw new Error('generatedAt must be a valid timestamp'); + } + + if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) { + throw new Error('updatedAt must be a valid timestamp'); + } + + const allowed = new Set([ + 'passwordHash', + 'passwordSalt', + 'mustChangePassword', + 'generatedAt', + 'updatedAt', + 'totp', + ]); + const unknown = Object.keys(v).find((key) => !allowed.has(key)); + + if (unknown) { + throw new Error(`unknown field $.${unknown}`); + } + + const state: WebuiAuthState = { + passwordHash: v.passwordHash, + passwordSalt: v.passwordSalt, + mustChangePassword: v.mustChangePassword, + generatedAt: v.generatedAt, + updatedAt: v.updatedAt, + }; + + if (!Object.prototype.hasOwnProperty.call(v, 'totp') || v.totp === undefined) { + return state; + } + + state.totp = prepareTotpStateForRestore(v.totp); return state; - } - state.totp = prepareTotpStateForRestore(v.totp); - return state; } function parseLiveAuthState(value: unknown): WebuiAuthState | null { - if (!value || typeof value !== 'object' || Array.isArray(value)) return null; - const v = value as Record; - const totpValue = v.totp; - const withoutTotp = { ...v }; - delete withoutTotp.totp; - try { - const state = prepareWebuiAuthStateForRestore( - Object.prototype.hasOwnProperty.call(v, 'totp') - ? withoutTotp - : value, - ); - const totp = parseTotpStateLenient(totpValue); - if (Object.prototype.hasOwnProperty.call(v, 'totp') && totpValue !== undefined && !totp) { - log.warn('webui.json totp field is invalid and will be ignored; password credentials are unchanged'); + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return null; + } + + const v = value as Record; + const totpValue = v.totp; + const withoutTotp = { ...v }; + delete withoutTotp.totp; + + try { + const state = prepareWebuiAuthStateForRestore( + Object.prototype.hasOwnProperty.call(v, 'totp') ? withoutTotp : value, + ); + const totp = parseTotpStateLenient(totpValue); + + if (Object.prototype.hasOwnProperty.call(v, 'totp') && totpValue !== undefined && !totp) { + log.warn( + 'webui.json totp field is invalid and will be ignored; password credentials are unchanged', + ); + } + + if (totp) { + state.totp = totp; + } + + return state; + } catch { + return null; } - if (totp) state.totp = totp; - return state; - } catch { - return null; - } } function generateInitialState(initialPassword: string): WebuiAuthState { - const salt = randomBytes(16); - const hash = hashPassword(initialPassword, salt); - const now = new Date().toISOString(); - return { - passwordHash: hash.toString('hex'), - passwordSalt: salt.toString('hex'), - mustChangePassword: true, - generatedAt: now, - updatedAt: now, - }; + const salt = randomBytes(16); + const hash = hashPassword(initialPassword, salt); + const now = new Date().toISOString(); + return { + passwordHash: hash.toString('hex'), + passwordSalt: salt.toString('hex'), + mustChangePassword: true, + generatedAt: now, + updatedAt: now, + }; } function backupCorruptConfig(): void { - try { - const dest = `${WEBUI_CONFIG_PATH}.bak.${Date.now()}`; - fs.renameSync(WEBUI_CONFIG_PATH, dest); - log.warn('previous webui.json moved to %s', dest); - } catch (err) { - log.warn('failed to back up corrupt webui.json: %s', err instanceof Error ? err.message : String(err)); - } + try { + const dest = `${WEBUI_CONFIG_PATH}.bak.${Date.now()}`; + fs.renameSync(WEBUI_CONFIG_PATH, dest); + log.warn('previous webui.json moved to %s', dest); + } catch (err) { + log.warn( + 'failed to back up corrupt webui.json: %s', + err instanceof Error ? err.message : String(err), + ); + } } function atomicWrite(state: WebuiAuthState): void { - ensureConfigDir(); - const tmp = WEBUI_CONFIG_PATH + '.tmp'; - fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 }); - try { - fs.chmodSync(tmp, 0o600); - } catch { - /* ignore */ - } - fs.renameSync(tmp, WEBUI_CONFIG_PATH); + ensureConfigDir(); + const tmp = WEBUI_CONFIG_PATH + '.tmp'; + fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 }); + + try { + fs.chmodSync(tmp, 0o600); + } catch { + /* ignore */ + } + + fs.renameSync(tmp, WEBUI_CONFIG_PATH); } export class WebuiAuth { - private state: WebuiAuthState; - private initialPlain: string | null; - private readonly devMode: boolean; + private state: WebuiAuthState; + private initialPlain: string | null; + private readonly devMode: boolean; - private constructor(state: WebuiAuthState, initialPlain: string | null, devMode: boolean) { - this.state = state; - this.initialPlain = initialPlain; - this.devMode = devMode; - } - - static load(): WebuiAuth { - if (isDevAuthMode()) { - const salt = randomBytes(16); - const hash = hashPassword(DEV_PASSWORD, salt); - const now = new Date().toISOString(); - const state: WebuiAuthState = { - passwordHash: hash.toString('hex'), - passwordSalt: salt.toString('hex'), - mustChangePassword: false, - generatedAt: now, - updatedAt: now, - }; - return new WebuiAuth(state, null, true); + private constructor(state: WebuiAuthState, initialPlain: string | null, devMode: boolean) { + this.state = state; + this.initialPlain = initialPlain; + this.devMode = devMode; } - ensureConfigDir(); - if (fs.existsSync(WEBUI_CONFIG_PATH)) { - try { - const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8'); - const parsed = JSON.parse(raw) as unknown; - const live = parseLiveAuthState(parsed); - if (live) { - if (live.mustChangePassword) { - // Previous start generated a bootstrap password but the operator - // never completed the forced-change flow. The plaintext is gone - // (only the hash is on disk, and the log line from last run may - // be lost), so rotate to a fresh CSPRNG password they can see. - const initialPassword = randomBytes(8).toString('hex'); - const state = generateInitialState(initialPassword); - atomicWrite(state); - log.warn('previous bootstrap password was never rotated; regenerated a new one'); - return new WebuiAuth(state, initialPassword, false); - } - return new WebuiAuth(live, null, false); + + static load(): WebuiAuth { + if (isDevAuthMode()) { + const salt = randomBytes(16); + const hash = hashPassword(DEV_PASSWORD, salt); + const now = new Date().toISOString(); + const state: WebuiAuthState = { + passwordHash: hash.toString('hex'), + passwordSalt: salt.toString('hex'), + mustChangePassword: false, + generatedAt: now, + updatedAt: now, + }; + return new WebuiAuth(state, null, true); } - log.error('webui.json schema invalid; backing up and regenerating credentials'); - backupCorruptConfig(); - } catch (err) { - log.error( - 'webui.json is corrupt and will be regenerated; the previous file is backed up: %s', - err instanceof Error ? err.message : String(err), - ); - backupCorruptConfig(); - } + + ensureConfigDir(); + + if (fs.existsSync(WEBUI_CONFIG_PATH)) { + try { + const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8'); + const parsed = JSON.parse(raw) as unknown; + const live = parseLiveAuthState(parsed); + + if (live) { + if (live.mustChangePassword) { + // Previous start generated a bootstrap password but the operator + // never completed the forced-change flow. The plaintext is gone + // (only the hash is on disk, and the log line from last run may + // be lost), so rotate to a fresh CSPRNG password they can see. + const initialPassword = randomBytes(8).toString('hex'); + const state = generateInitialState(initialPassword); + atomicWrite(state); + log.warn( + 'previous bootstrap password was never rotated; regenerated a new one', + ); + return new WebuiAuth(state, initialPassword, false); + } + + return new WebuiAuth(live, null, false); + } + + log.error('webui.json schema invalid; backing up and regenerating credentials'); + backupCorruptConfig(); + } catch (err) { + log.error( + 'webui.json is corrupt and will be regenerated; the previous file is backed up: %s', + err instanceof Error ? err.message : String(err), + ); + backupCorruptConfig(); + } + } + + const envPassword = envBootstrapPassword(); + + if (envPassword !== null) { + const salt = randomBytes(16); + const hash = hashPassword(envPassword, salt); + const now = new Date().toISOString(); + const state: WebuiAuthState = { + passwordHash: hash.toString('hex'), + passwordSalt: salt.toString('hex'), + mustChangePassword: false, + generatedAt: now, + updatedAt: now, + }; + atomicWrite(state); + log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD'); + return new WebuiAuth(state, null, false); + } + + const initialPassword = randomBytes(8).toString('hex'); + const state = generateInitialState(initialPassword); + atomicWrite(state); + return new WebuiAuth(state, initialPassword, false); } - const envPassword = envBootstrapPassword(); - if (envPassword !== null) { - const salt = randomBytes(16); - const hash = hashPassword(envPassword, salt); - const now = new Date().toISOString(); - const state: WebuiAuthState = { - passwordHash: hash.toString('hex'), - passwordSalt: salt.toString('hex'), - mustChangePassword: false, - generatedAt: now, - updatedAt: now, - }; - atomicWrite(state); - log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD'); - return new WebuiAuth(state, null, false); + + /** True when SNOWLUMA_DEV_MODE was active at load time. */ + isDevMode(): boolean { + return this.devMode; } - const initialPassword = randomBytes(8).toString('hex'); - const state = generateInitialState(initialPassword); - atomicWrite(state); - return new WebuiAuth(state, initialPassword, false); - } - /** True when SNOWLUMA_DEV_MODE was active at load time. */ - isDevMode(): boolean { - return this.devMode; - } - - /** Fixed dev password (only meaningful when {@link isDevMode} is true). */ - static get devPassword(): string { - return DEV_PASSWORD; - } - - /** Returns the auto-generated initial password if this is a fresh install, else null. */ - takeInitialPassword(): string | null { - const p = this.initialPlain; - this.initialPlain = null; - return p; - } - - mustChangePassword(): boolean { - return this.state.mustChangePassword; - } - - verify(password: string): boolean { - if (typeof password !== 'string' || password.length === 0) return false; - try { - const salt = Buffer.from(this.state.passwordSalt, 'hex'); - const expected = Buffer.from(this.state.passwordHash, 'hex'); - const got = hashPassword(password, salt); - if (got.length !== expected.length) return false; - return timingSafeEqual(got, expected); - } catch { - return false; + /** Fixed dev password (only meaningful when {@link isDevMode} is true). */ + static get devPassword(): string { + return DEV_PASSWORD; } - } - setPassword(newPassword: string, currentPassword?: string): void { - if (this.devMode) { - throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改'); + /** Returns the auto-generated initial password if this is a fresh install, else null. */ + takeInitialPassword(): string | null { + const p = this.initialPlain; + this.initialPlain = null; + return p; } - if (!isStrongPassword(newPassword)) { - throw new Error('密码不符合强度要求'); + + mustChangePassword(): boolean { + return this.state.mustChangePassword; } - let totp = this.state.totp; - if (totp) { - if (typeof currentPassword !== 'string' || currentPassword.length === 0) { - throw new Error('修改密码需要当前密码以重新保护 2FA 密钥'); - } - totp = rewrapTotpSecret(currentPassword, newPassword, totp); + + verify(password: string): boolean { + if (typeof password !== 'string' || password.length === 0) { + return false; + } + + try { + const salt = Buffer.from(this.state.passwordSalt, 'hex'); + const expected = Buffer.from(this.state.passwordHash, 'hex'); + const got = hashPassword(password, salt); + + if (got.length !== expected.length) { + return false; + } + + return timingSafeEqual(got, expected); + } catch { + return false; + } } - const salt = randomBytes(16); - const hash = hashPassword(newPassword, salt); - const next: WebuiAuthState = { - passwordHash: hash.toString('hex'), - passwordSalt: salt.toString('hex'), - mustChangePassword: false, - generatedAt: this.state.generatedAt, - updatedAt: new Date().toISOString(), - ...(totp ? { totp } : {}), - }; - atomicWrite(next); - this.state = next; - } - totpEnabled(): boolean { - return this.state.totp !== undefined; - } + setPassword(newPassword: string, currentPassword?: string): void { + if (this.devMode) { + throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改'); + } - totpStatus(): { enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } { - const totp = this.state.totp; - if (!totp) return { enabled: false }; - return { - enabled: true, - remainingRecoveryCodes: totp.recoveryCodeHashes.length, - label: totp.label, - }; - } + if (!isStrongPassword(newPassword)) { + throw new Error('密码不符合强度要求'); + } - totpState(): TotpPersistedState | undefined { - return this.state.totp; - } + let totp = this.state.totp; - persistTotp(totp: TotpPersistedState | undefined): void { - if (this.devMode) { - throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA'); + if (totp) { + if (typeof currentPassword !== 'string' || currentPassword.length === 0) { + throw new Error('修改密码需要当前密码以重新保护 2FA 密钥'); + } + + totp = rewrapTotpSecret(currentPassword, newPassword, totp); + } + + const salt = randomBytes(16); + const hash = hashPassword(newPassword, salt); + const next: WebuiAuthState = { + passwordHash: hash.toString('hex'), + passwordSalt: salt.toString('hex'), + mustChangePassword: false, + generatedAt: this.state.generatedAt, + updatedAt: new Date().toISOString(), + ...(totp ? { totp } : {}), + }; + atomicWrite(next); + this.state = next; + } + + totpEnabled(): boolean { + return this.state.totp !== undefined; + } + + totpStatus(): + { enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } { + const totp = this.state.totp; + + if (!totp) { + return { enabled: false }; + } + + return { + enabled: true, + remainingRecoveryCodes: totp.recoveryCodeHashes.length, + label: totp.label, + }; + } + + totpState(): TotpPersistedState | undefined { + return this.state.totp; + } + + persistTotp(totp: TotpPersistedState | undefined): void { + if (this.devMode) { + throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA'); + } + + const next: WebuiAuthState = { ...this.state, updatedAt: new Date().toISOString() }; + + if (totp) { + next.totp = totp; + } else { + delete next.totp; + } + + atomicWrite(next); + this.state = next; } - const next: WebuiAuthState = { ...this.state, updatedAt: new Date().toISOString() }; - if (totp) next.totp = totp; - else delete next.totp; - atomicWrite(next); - this.state = next; - } } diff --git a/packages/core/src/webui/backup.ts b/packages/core/src/webui/backup.ts index 11c06037..692ee0f7 100644 --- a/packages/core/src/webui/backup.ts +++ b/packages/core/src/webui/backup.ts @@ -29,50 +29,60 @@ export const BACKUP_APP = 'snowluma'; export const MAX_BACKUP_DECODED_BYTES = 32 * 1024 * 1024; 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; + /** 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: true }, - // Global all-accounts SnowLuma settings (rkey fallback servers, …). - { name: 'snowluma.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 }, + { name: 'runtime.json', binary: false, credential: false }, + { name: 'ui.json', binary: false, credential: false }, + { name: 'notifications.json', binary: false, credential: true }, + // Global all-accounts SnowLuma settings (rkey fallback servers, …). + { name: 'snowluma.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$/; function isPerUinOneBotName(name: string): boolean { - const match = PER_UIN_ONEBOT.exec(name); - return match !== null && isRealUin(match[1]); + const match = PER_UIN_ONEBOT.exec(name); + return match !== null && isRealUin(match[1]); } /** 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 (isPerUinOneBotName(name)) return { name, binary: false, credential: true }; - return null; + const s = SPEC_BY_NAME.get(name); + + if (s) { + return s; + } + + if (isPerUinOneBotName(name)) { + return { name, binary: false, credential: true }; + } + + return null; } -export interface BackupEntry { encoding: 'utf8' | 'base64'; data: string } +export interface BackupEntry { + encoding: 'utf8' | 'base64'; + data: string; +} export interface Backup { - version: number; - app: string; - createdAt?: string; - files: Record; + version: number; + app: string; + createdAt?: string; + files: Record; } /** @@ -80,455 +90,713 @@ export interface Backup { * `readFile` returns null for missing. */ export function buildBackup( - readFile: (name: string) => Buffer | null, - perUinOnebotNames: readonly string[], - opts: { includeCredentials: boolean }, - createdAt: string, + readFile: (name: string) => Buffer | null, + perUinOnebotNames: readonly string[], + opts: { includeCredentials: boolean }, + createdAt: string, ): Backup { - const files: Record = {}; - const all: BackupFileSpec[] = [ - ...BACKUP_FILES, - ...perUinOnebotNames.filter(isPerUinOneBotName).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 }; + const files: Record = {}; + const all: BackupFileSpec[] = [ + ...BACKUP_FILES, + ...perUinOnebotNames + .filter(isPerUinOneBotName) + .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 }; } function validateBackupEntries( - parsed: unknown, - skipEntryValidation: (spec: BackupFileSpec) => boolean, + parsed: unknown, + skipEntryValidation: (spec: BackupFileSpec) => boolean, ): { 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)) { - const spec = specFor(name); - if (!spec) return { ok: false, error: `unknown file in backup: ${name}` }; - if (skipEntryValidation(spec)) continue; - 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 } }; + 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)) { + const spec = specFor(name); + + if (!spec) { + return { ok: false, error: `unknown file in backup: ${name}` }; + } + + if (skipEntryValidation(spec)) { + continue; + } + + 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, + }, + }; } export interface PreparedRestoreFile { - name: string; - data: Buffer; - mode: 0o600 | 0o644; + name: string; + data: Buffer; + mode: 0o600 | 0o644; } export interface RestoreMigration { - name: string; - fields: string[]; + name: string; + fields: string[]; } export interface PreparedRestorePlan { - restore: PreparedRestoreFile[]; - skipped: string[]; - migrated: RestoreMigration[]; + restore: PreparedRestoreFile[]; + skipped: string[]; + migrated: RestoreMigration[]; } export interface PrepareRestoreOptions { - restoreCredentials: boolean; - /** Read an existing live file for overlay-wide validation (TLS/UI). */ - readCurrent: (name: string) => Buffer | null; - /** Current per-account configs affected when onebot.json is replaced. */ - listCurrentOneBotNames?: () => string[]; + restoreCredentials: boolean; + /** Read an existing live file for overlay-wide validation (TLS/UI). */ + readCurrent: (name: string) => Buffer | null; + /** Current per-account configs affected when onebot.json is replaced. */ + listCurrentOneBotNames?: () => string[]; } export class RestorePreflightError extends Error { - readonly file: string; + readonly file: string; - constructor(file: string, message: string, options?: { cause?: unknown }) { - super(`${file}: ${message}`, options); - this.name = 'RestorePreflightError'; - this.file = file; - } + constructor(file: string, message: string, options?: { cause?: unknown }) { + super(`${file}: ${message}`, options); + this.name = 'RestorePreflightError'; + this.file = file; + } } /** * Validate every selected file semantically and materialize canonical bytes * before the transaction is allowed to touch live configuration. */ -export function prepareRestorePlan(parsed: unknown, opts: PrepareRestoreOptions): PreparedRestorePlan { - const checked = validateBackupEntries(parsed, (spec) => spec.credential && !opts.restoreCredentials); - if (!checked.ok) throw new RestorePreflightError('', checked.error); +export function prepareRestorePlan( + parsed: unknown, + opts: PrepareRestoreOptions, +): PreparedRestorePlan { + const checked = validateBackupEntries( + parsed, + (spec) => spec.credential && !opts.restoreCredentials, + ); - const restore: PreparedRestoreFile[] = []; - const skipped: string[] = []; - const migrated: RestoreMigration[] = []; - const selected: Array<{ name: string; data: Buffer; spec: BackupFileSpec }> = []; - let decodedBytes = 0; - - for (const [name, entry] of Object.entries(checked.backup.files)) { - const spec = specFor(name); - if (!spec) throw new RestorePreflightError(name, 'file is not in the restore allowlist'); - if (spec.credential && !opts.restoreCredentials) { - skipped.push(name); - continue; - } - if (entry.encoding !== (spec.binary ? 'base64' : 'utf8')) { - throw new RestorePreflightError(name, `encoding must be ${spec.binary ? 'base64' : 'utf8'}`); + if (!checked.ok) { + throw new RestorePreflightError('', checked.error); } - const decoded = decodeEntryStrict(name, entry); - decodedBytes += decoded.length; - if (decodedBytes > MAX_BACKUP_DECODED_BYTES) { - throw new RestorePreflightError(name, `selected files exceed ${String(MAX_BACKUP_DECODED_BYTES)} decoded bytes`); + const restore: PreparedRestoreFile[] = []; + const skipped: string[] = []; + const migrated: RestoreMigration[] = []; + const selected: Array<{ name: string; data: Buffer; spec: BackupFileSpec }> = []; + let decodedBytes = 0; + + for (const [name, entry] of Object.entries(checked.backup.files)) { + const spec = specFor(name); + + if (!spec) { + throw new RestorePreflightError(name, 'file is not in the restore allowlist'); + } + + if (spec.credential && !opts.restoreCredentials) { + skipped.push(name); + continue; + } + + if (entry.encoding !== (spec.binary ? 'base64' : 'utf8')) { + throw new RestorePreflightError( + name, + `encoding must be ${spec.binary ? 'base64' : 'utf8'}`, + ); + } + + const decoded = decodeEntryStrict(name, entry); + decodedBytes += decoded.length; + + if (decodedBytes > MAX_BACKUP_DECODED_BYTES) { + throw new RestorePreflightError( + name, + `selected files exceed ${String(MAX_BACKUP_DECODED_BYTES)} decoded bytes`, + ); + } + + selected.push({ name, data: decoded, spec }); } - selected.push({ name, data: decoded, spec }); - } + const selectedGlobal = selected.find((file) => file.name === 'onebot.json'); + const selectedPerUin = selected.filter((file) => isPerUinOneBotName(file.name)); + const selectedPerUinRaw = new Map( + selectedPerUin.map((file) => [file.name, parseJson(file.name, file.data)]), + ); + const perUinNeedsGlobal = [...selectedPerUinRaw.values()].some( + (raw) => !isPlainObject(raw) || raw.mode !== 'snapshot', + ); + let effectiveGlobalOneBot: unknown; + let preparedGlobalOneBot: ReturnType | null = null; - const selectedGlobal = selected.find((file) => file.name === 'onebot.json'); - const selectedPerUin = selected.filter((file) => isPerUinOneBotName(file.name)); - const selectedPerUinRaw = new Map(selectedPerUin.map((file) => [file.name, parseJson(file.name, file.data)])); - const perUinNeedsGlobal = [...selectedPerUinRaw.values()].some((raw) => !isPlainObject(raw) || raw.mode !== 'snapshot'); - let effectiveGlobalOneBot: unknown; - let preparedGlobalOneBot: ReturnType | null = null; - if (selectedGlobal) { - if (!opts.listCurrentOneBotNames) { - throw new RestorePreflightError('onebot.json', 'current per-account config listing is required to validate the effective overlay'); - } - const raw = parseJson(selectedGlobal.name, selectedGlobal.data); - preparedGlobalOneBot = prepareOneBotOrThrow(selectedGlobal.name, raw, 'global'); - effectiveGlobalOneBot = preparedGlobalOneBot.value; - } else if (perUinNeedsGlobal) { - const current = readCurrentForPreflight(opts, 'onebot.json'); - if (current) { - const raw = parseJson('onebot.json', current); - effectiveGlobalOneBot = prepareOneBotOrThrow('onebot.json', raw, 'global').value; - } - } + if (selectedGlobal) { + if (!opts.listCurrentOneBotNames) { + throw new RestorePreflightError( + 'onebot.json', + 'current per-account config listing is required to validate the effective overlay', + ); + } - for (const { name, data, spec } of selected) { - let prepared: { data: Buffer; migratedFields: string[] }; - if (name === 'onebot.json') { - const global = preparedGlobalOneBot!; - prepared = { data: serializeJson(global.value), migratedFields: global.migratedFields }; - } else if (isPerUinOneBotName(name)) { - const raw = selectedPerUinRaw.get(name); - const onebot = prepareOneBotOrThrow(name, raw, 'per-uin', effectiveGlobalOneBot); - prepared = { data: serializeJson(onebot.value), migratedFields: onebot.migratedFields }; - } else { - prepared = prepareFile(name, data); - } - restore.push({ name, data: prepared.data, mode: spec.credential ? 0o600 : 0o644 }); - if (prepared.migratedFields.length > 0) { - migrated.push({ name, fields: [...prepared.migratedFields].sort() }); - } - } + const raw = parseJson(selectedGlobal.name, selectedGlobal.data); + preparedGlobalOneBot = prepareOneBotOrThrow(selectedGlobal.name, raw, 'global'); + effectiveGlobalOneBot = preparedGlobalOneBot.value; + } else if (perUinNeedsGlobal) { + const current = readCurrentForPreflight(opts, 'onebot.json'); - if (selectedGlobal) { - const selectedNames = new Set(selected.map((file) => file.name)); - let currentNames: string[]; - try { - currentNames = opts.listCurrentOneBotNames!(); - } catch (error) { - throw new RestorePreflightError('onebot.json', `failed to list current per-account configs: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); + if (current) { + const raw = parseJson('onebot.json', current); + effectiveGlobalOneBot = prepareOneBotOrThrow('onebot.json', raw, 'global').value; + } } - for (const name of currentNames) { - if (!isPerUinOneBotName(name) || selectedNames.has(name)) continue; - const current = readCurrentForPreflight(opts, name); - if (!current) continue; - const raw = parseJson(name, current); - prepareOneBotOrThrow(name, raw, 'per-uin', effectiveGlobalOneBot); - } - } - validateEffectiveTls(restore, opts); - validateEffectiveUi(restore, opts); - return { restore, skipped, migrated }; + for (const { name, data, spec } of selected) { + let prepared: { data: Buffer; migratedFields: string[] }; + + if (name === 'onebot.json') { + const global = preparedGlobalOneBot!; + prepared = { data: serializeJson(global.value), migratedFields: global.migratedFields }; + } else if (isPerUinOneBotName(name)) { + const raw = selectedPerUinRaw.get(name); + const onebot = prepareOneBotOrThrow(name, raw, 'per-uin', effectiveGlobalOneBot); + prepared = { data: serializeJson(onebot.value), migratedFields: onebot.migratedFields }; + } else { + prepared = prepareFile(name, data); + } + + restore.push({ name, data: prepared.data, mode: spec.credential ? 0o600 : 0o644 }); + + if (prepared.migratedFields.length > 0) { + migrated.push({ name, fields: [...prepared.migratedFields].sort() }); + } + } + + if (selectedGlobal) { + const selectedNames = new Set(selected.map((file) => file.name)); + let currentNames: string[]; + + try { + currentNames = opts.listCurrentOneBotNames!(); + } catch (error) { + throw new RestorePreflightError( + 'onebot.json', + `failed to list current per-account configs: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + + for (const name of currentNames) { + if (!isPerUinOneBotName(name) || selectedNames.has(name)) { + continue; + } + + const current = readCurrentForPreflight(opts, name); + + if (!current) { + continue; + } + + const raw = parseJson(name, current); + prepareOneBotOrThrow(name, raw, 'per-uin', effectiveGlobalOneBot); + } + } + + validateEffectiveTls(restore, opts); + validateEffectiveUi(restore, opts); + return { restore, skipped, migrated }; } function decodeEntryStrict(name: string, entry: BackupEntry): Buffer { - if (entry.encoding === 'utf8') return Buffer.from(entry.data, 'utf8'); - if (!isCanonicalBase64(entry.data)) { - throw new RestorePreflightError(name, 'data is not canonical base64'); - } - return Buffer.from(entry.data, 'base64'); + if (entry.encoding === 'utf8') { + return Buffer.from(entry.data, 'utf8'); + } + + if (!isCanonicalBase64(entry.data)) { + throw new RestorePreflightError(name, 'data is not canonical base64'); + } + + return Buffer.from(entry.data, 'base64'); } function isCanonicalBase64(value: string): boolean { - if (value.length === 0) return true; - if (value.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) { - return false; - } - return Buffer.from(value, 'base64').toString('base64') === value; + if (value.length === 0) { + return true; + } + + if ( + value.length % 4 !== 0 || + !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value) + ) { + return false; + } + + return Buffer.from(value, 'base64').toString('base64') === value; } function prepareFile(name: string, data: Buffer): { data: Buffer; migratedFields: string[] } { - try { - switch (name) { - case 'runtime.json': - return prepareRuntimeJson(name, data); - case 'ui.json': - return prepareNormalizedJson(name, data, normalizeStoredUiConfig); - case 'notifications.json': - return prepareNormalizedJson(name, data, normalizeNotificationsConfig); - case 'snowluma.json': - return prepareGlobalSettingsJson(name, data); - case 'webui.json': { - const value = parseJson(name, data); - const canonical = prepareWebuiAuthStateForRestore(value); - return { data: serializeJson(canonical), migratedFields: [] }; - } - case 'ui-assets/background': - if (data.length > MAX_BACKGROUND_BYTES) { - throw new Error(`image exceeds ${String(MAX_BACKGROUND_BYTES)} bytes`); + try { + switch (name) { + case 'runtime.json': + return prepareRuntimeJson(name, data); + case 'ui.json': + return prepareNormalizedJson(name, data, normalizeStoredUiConfig); + case 'notifications.json': + return prepareNormalizedJson(name, data, normalizeNotificationsConfig); + case 'snowluma.json': + return prepareGlobalSettingsJson(name, data); + + case 'webui.json': { + const value = parseJson(name, data); + const canonical = prepareWebuiAuthStateForRestore(value); + return { data: serializeJson(canonical), migratedFields: [] }; + } + + case 'ui-assets/background': + if (data.length > MAX_BACKGROUND_BYTES) { + throw new Error(`image exceeds ${String(MAX_BACKGROUND_BYTES)} bytes`); + } + + if (!sniffImageMime(data)) { + throw new Error('image must be PNG, JPEG, or WebP'); + } + + return { data, migratedFields: [] }; + case 'cert.pem': + case 'key.pem': + if (!data.toString('utf8').trim()) { + throw new Error('PEM file must not be empty'); + } + + return { data, migratedFields: [] }; + default: + throw new Error('file is not in the restore allowlist'); } - if (!sniffImageMime(data)) throw new Error('image must be PNG, JPEG, or WebP'); - return { data, migratedFields: [] }; - case 'cert.pem': - case 'key.pem': - if (!data.toString('utf8').trim()) throw new Error('PEM file must not be empty'); - return { data, migratedFields: [] }; - default: - throw new Error('file is not in the restore allowlist'); + } catch (error) { + if (error instanceof RestorePreflightError) { + throw error; + } + + throw new RestorePreflightError( + name, + error instanceof Error ? error.message : String(error), + { + cause: error, + }, + ); } - } catch (error) { - if (error instanceof RestorePreflightError) throw error; - throw new RestorePreflightError(name, error instanceof Error ? error.message : String(error), { cause: error }); - } } function prepareOneBotOrThrow( - name: string, - value: unknown, - scope: 'global' | 'per-uin', - inheritedGlobal?: unknown, + name: string, + value: unknown, + scope: 'global' | 'per-uin', + inheritedGlobal?: unknown, ): ReturnType { - try { - return prepareOneBotConfigForRestore(value, scope, inheritedGlobal); - } catch (error) { - throw new RestorePreflightError(name, error instanceof Error ? error.message : String(error), { cause: error }); - } + try { + return prepareOneBotConfigForRestore(value, scope, inheritedGlobal); + } catch (error) { + throw new RestorePreflightError( + name, + error instanceof Error ? error.message : String(error), + { + cause: error, + }, + ); + } } function readCurrentForPreflight(opts: PrepareRestoreOptions, name: string): Buffer | null { - try { - return opts.readCurrent(name); - } catch (error) { - throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); - } + try { + return opts.readCurrent(name); + } catch (error) { + throw new RestorePreflightError( + name, + `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } } function parseJson(name: string, data: Buffer): unknown { - try { - return JSON.parse(data.toString('utf8')) as unknown; - } catch (error) { - // V8 may quote the offending input in SyntaxError.message. Some restored - // JSON files contain credentials, so expose only a fixed diagnostic while - // retaining the original exception as the in-process cause. - throw new RestorePreflightError(name, 'invalid JSON', { cause: error }); - } + try { + return JSON.parse(data.toString('utf8')) as unknown; + } catch (error) { + // V8 may quote the offending input in SyntaxError.message. Some restored + // JSON files contain credentials, so expose only a fixed diagnostic while + // retaining the original exception as the in-process cause. + throw new RestorePreflightError(name, 'invalid JSON', { cause: error }); + } } -function prepareNormalizedJson(name: string, data: Buffer, normalize: (value: unknown) => T): { - data: Buffer; - migratedFields: string[]; +function prepareNormalizedJson( + name: string, + data: Buffer, + normalize: (value: unknown) => T, +): { + data: Buffer; + migratedFields: string[]; } { - const raw = parseJson(name, data); - const canonical = normalize(raw); - const migratedFields: string[] = []; - assertNoLossyNormalization(name, raw, canonical, '$', migratedFields); - return { data: serializeJson(canonical), migratedFields }; + const raw = parseJson(name, data); + const canonical = normalize(raw); + const migratedFields: string[] = []; + assertNoLossyNormalization(name, raw, canonical, '$', migratedFields); + return { data: serializeJson(canonical), migratedFields }; } -function prepareRuntimeJson(name: string, data: Buffer): { - data: Buffer; - migratedFields: string[]; +function prepareRuntimeJson( + name: string, + data: Buffer, +): { + data: Buffer; + migratedFields: string[]; } { - const prepared = prepareNormalizedJson(name, data, normalizeRuntimeConfig); - const runtime = JSON.parse(prepared.data.toString('utf8')) as ReturnType; - if (!runtime.webuiHost || !isValidBindHost(runtime.webuiHost)) { - throw new RestorePreflightError(name, '$.webuiHost is not a valid TCP bind host'); - } - return prepared; + const prepared = prepareNormalizedJson(name, data, normalizeRuntimeConfig); + const runtime = JSON.parse(prepared.data.toString('utf8')) as ReturnType< + typeof normalizeRuntimeConfig + >; + + if (!runtime.webuiHost || !isValidBindHost(runtime.webuiHost)) { + throw new RestorePreflightError(name, '$.webuiHost is not a valid TCP bind host'); + } + + return prepared; } -function prepareGlobalSettingsJson(name: string, data: Buffer): { - data: Buffer; - migratedFields: string[]; +function prepareGlobalSettingsJson( + name: string, + data: Buffer, +): { + data: Buffer; + migratedFields: string[]; } { - const raw = parseJson(name, data); - const normalized = normalizeGlobalSettings(raw); - const canonical: Record = { rkey: normalized.rkey }; - // Missing is the existing one-shot migration sentinel: startup scans legacy - // onebot*.json only until snowluma.json first carries this key. - if (isPlainObject(raw) && Object.prototype.hasOwnProperty.call(raw, 'musicSignUrl')) { - canonical.musicSignUrl = normalized.musicSignUrl; - } - const migratedFields: string[] = []; - assertNoLossyNormalization(name, raw, canonical, '$', migratedFields); - return { data: serializeJson(canonical), migratedFields }; + const raw = parseJson(name, data); + const normalized = normalizeGlobalSettings(raw); + const canonical: Record = { rkey: normalized.rkey }; + + // Missing is the existing one-shot migration sentinel: startup scans legacy + // onebot*.json only until snowluma.json first carries this key. + if (isPlainObject(raw) && Object.prototype.hasOwnProperty.call(raw, 'musicSignUrl')) { + canonical.musicSignUrl = normalized.musicSignUrl; + } + + const migratedFields: string[] = []; + assertNoLossyNormalization(name, raw, canonical, '$', migratedFields); + return { data: serializeJson(canonical), migratedFields }; } function assertNoLossyNormalization( - name: string, - raw: unknown, - canonical: unknown, - at: string, - additions: string[], + name: string, + raw: unknown, + canonical: unknown, + at: string, + additions: string[], ): void { - if (isPlainObject(raw)) { - if (!isPlainObject(canonical)) throw new RestorePreflightError(name, `${at} has an invalid type`); - for (const [key, rawValue] of Object.entries(raw)) { - const child = `${at}.${key}`; - if (!Object.prototype.hasOwnProperty.call(canonical, key)) { - throw new RestorePreflightError(name, `${child} is unsupported or would be discarded`); - } - assertNoLossyNormalization(name, rawValue, canonical[key], child, additions); + if (isPlainObject(raw)) { + if (!isPlainObject(canonical)) { + throw new RestorePreflightError(name, `${at} has an invalid type`); + } + + for (const [key, rawValue] of Object.entries(raw)) { + const child = `${at}.${key}`; + + if (!Object.prototype.hasOwnProperty.call(canonical, key)) { + throw new RestorePreflightError( + name, + `${child} is unsupported or would be discarded`, + ); + } + + assertNoLossyNormalization(name, rawValue, canonical[key], child, additions); + } + + for (const key of Object.keys(canonical)) { + if (!Object.prototype.hasOwnProperty.call(raw, key)) { + additions.push(`${at}.${key}`); + } + } + + return; } - for (const key of Object.keys(canonical)) { - if (!Object.prototype.hasOwnProperty.call(raw, key)) additions.push(`${at}.${key}`); + + if (Array.isArray(raw)) { + if (!Array.isArray(canonical) || raw.length !== canonical.length) { + throw new RestorePreflightError( + name, + `${at} contains an invalid, duplicate, or discarded item`, + ); + } + + raw.forEach((value, index) => { + assertNoLossyNormalization( + name, + value, + canonical[index], + `${at}[${String(index)}]`, + additions, + ); + }); + return; } - return; - } - if (Array.isArray(raw)) { - if (!Array.isArray(canonical) || raw.length !== canonical.length) { - throw new RestorePreflightError(name, `${at} contains an invalid, duplicate, or discarded item`); + + if (!Object.is(raw, canonical)) { + if (isKnownLosslessScalarCoercion(name, at, raw, canonical)) { + additions.push(at); + return; + } + + throw new RestorePreflightError(name, `${at} is invalid or would be changed`); } - raw.forEach((value, index) => { - assertNoLossyNormalization(name, value, canonical[index], `${at}[${String(index)}]`, additions); - }); - return; - } - if (!Object.is(raw, canonical)) { - if (isKnownLosslessScalarCoercion(name, at, raw, canonical)) { - additions.push(at); - return; - } - throw new RestorePreflightError(name, `${at} is invalid or would be changed`); - } } -function isKnownLosslessScalarCoercion(name: string, at: string, raw: unknown, canonical: unknown): boolean { - if (typeof raw === 'string' && typeof canonical === 'string' && raw.trim() === canonical) { - return true; - } - if (typeof raw === 'string' && typeof canonical === 'number') { - const parsed = Number(raw.trim()); - return raw.trim().length > 0 && Number.isFinite(parsed) && Object.is(parsed, canonical); - } - if ( - name === 'runtime.json' && - (at === '$.hookAutoLoad' || at === '$.webuiTls.enabled') && - typeof canonical === 'boolean' - ) { - if (raw === 1 || raw === 0) return canonical === (raw === 1); - if (typeof raw !== 'string') return false; - const token = raw.trim().toLowerCase(); - const truthy = new Set(['true', '1', 'yes', 'on']); - const falsy = new Set(['false', '0', 'no', 'off', '']); - return (canonical && truthy.has(token)) || (!canonical && falsy.has(token)); - } - return false; +function isKnownLosslessScalarCoercion( + name: string, + at: string, + raw: unknown, + canonical: unknown, +): boolean { + if (typeof raw === 'string' && typeof canonical === 'string' && raw.trim() === canonical) { + return true; + } + + if (typeof raw === 'string' && typeof canonical === 'number') { + const parsed = Number(raw.trim()); + return raw.trim().length > 0 && Number.isFinite(parsed) && Object.is(parsed, canonical); + } + + if ( + name === 'runtime.json' && + (at === '$.hookAutoLoad' || at === '$.webuiTls.enabled') && + typeof canonical === 'boolean' + ) { + if (raw === 1 || raw === 0) { + return canonical === (raw === 1); + } + + if (typeof raw !== 'string') { + return false; + } + + const token = raw.trim().toLowerCase(); + const truthy = new Set(['true', '1', 'yes', 'on']); + const falsy = new Set(['false', '0', 'no', 'off', '']); + return (canonical && truthy.has(token)) || (!canonical && falsy.has(token)); + } + + return false; } function isPlainObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); + return typeof value === 'object' && value !== null && !Array.isArray(value); } function serializeJson(value: unknown): Buffer { - return Buffer.from(JSON.stringify(value, null, 2), 'utf8'); + return Buffer.from(JSON.stringify(value, null, 2), 'utf8'); } function validateEffectiveTls(restore: PreparedRestoreFile[], opts: PrepareRestoreOptions): void { - const byName = new Map(restore.map((file) => [file.name, file.data])); - const pairTouched = byName.has('cert.pem') || byName.has('key.pem'); - const tlsRelated = pairTouched || byName.has('runtime.json'); - if (!tlsRelated) return; + const byName = new Map(restore.map((file) => [file.name, file.data])); + const pairTouched = byName.has('cert.pem') || byName.has('key.pem'); + const tlsRelated = pairTouched || byName.has('runtime.json'); - const readEffective = (name: string): Buffer | null => { - const prepared = byName.get(name); - if (prepared) return prepared; - try { - return opts.readCurrent(name); - } catch (error) { - throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); + if (!tlsRelated) { + return; } - }; - const runtime = readEffective('runtime.json'); - let tlsEnabled = false; - if (runtime) { - try { - tlsEnabled = normalizeRuntimeConfig(JSON.parse(runtime.toString('utf8')) as unknown).webuiTls?.enabled === true; - } catch (error) { - throw new RestorePreflightError('runtime.json', 'effective runtime config is invalid JSON', { cause: error }); + + const readEffective = (name: string): Buffer | null => { + const prepared = byName.get(name); + + if (prepared) { + return prepared; + } + + try { + return opts.readCurrent(name); + } catch (error) { + throw new RestorePreflightError( + name, + `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + }; + + const runtime = readEffective('runtime.json'); + let tlsEnabled = false; + + if (runtime) { + try { + tlsEnabled = + normalizeRuntimeConfig(JSON.parse(runtime.toString('utf8')) as unknown).webuiTls + ?.enabled === true; + } catch (error) { + throw new RestorePreflightError( + 'runtime.json', + 'effective runtime config is invalid JSON', + { + cause: error, + }, + ); + } } - } - if (!tlsEnabled && !pairTouched) return; - const cert = readEffective('cert.pem'); - const key = readEffective('key.pem'); + if (!tlsEnabled && !pairTouched) { + return; + } - if (cert && key) { - const valid = validateTlsPair(cert, key); - if (!valid.ok) throw new RestorePreflightError('cert.pem + key.pem', valid.reason ?? 'TLS pair is invalid'); - return; - } - if (tlsEnabled) { - throw new RestorePreflightError('cert.pem + key.pem', 'TLS is enabled but the effective certificate/private-key pair is incomplete'); - } + const cert = readEffective('cert.pem'); + const key = readEffective('key.pem'); + + if (cert && key) { + const valid = validateTlsPair(cert, key); + + if (!valid.ok) { + throw new RestorePreflightError( + 'cert.pem + key.pem', + valid.reason ?? 'TLS pair is invalid', + ); + } + + return; + } + + if (tlsEnabled) { + throw new RestorePreflightError( + 'cert.pem + key.pem', + 'TLS is enabled but the effective certificate/private-key pair is incomplete', + ); + } } function validateEffectiveUi(restore: PreparedRestoreFile[], opts: PrepareRestoreOptions): void { - const byName = new Map(restore.map((file) => [file.name, file.data])); - if (!byName.has('ui.json') && !byName.has('ui-assets/background')) return; + const byName = new Map(restore.map((file) => [file.name, file.data])); - const readEffective = (name: string): Buffer | null => { - const prepared = byName.get(name); - if (prepared) return prepared; - try { - return opts.readCurrent(name); - } catch (error) { - throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); + if (!byName.has('ui.json') && !byName.has('ui-assets/background')) { + return; } - }; - const uiBytes = readEffective('ui.json'); - if (!uiBytes) return; - let ui; - try { - ui = normalizeStoredUiConfig(JSON.parse(uiBytes.toString('utf8')) as unknown); - } catch (error) { - throw new RestorePreflightError('ui.json', 'effective UI config is invalid JSON', { cause: error }); - } - const background = ui.appearance.background; - if (!background.hasImage) return; + const readEffective = (name: string): Buffer | null => { + const prepared = byName.get(name); - const image = readEffective('ui-assets/background'); - if (!image) { - throw new RestorePreflightError('ui.json + ui-assets/background', 'background metadata says an image exists, but the effective image is missing'); - } - if (image.length > MAX_BACKGROUND_BYTES) { - throw new RestorePreflightError('ui.json + ui-assets/background', `effective background exceeds ${String(MAX_BACKGROUND_BYTES)} bytes`); - } - const mime = sniffImageMime(image); - if (!mime) { - throw new RestorePreflightError('ui.json + ui-assets/background', 'effective background is not PNG, JPEG, or WebP'); - } - if (mime !== background.imageMime) { - throw new RestorePreflightError( - 'ui.json + ui-assets/background', - `background metadata MIME ${background.imageMime} does not match image bytes ${mime}`, - ); - } + if (prepared) { + return prepared; + } + + try { + return opts.readCurrent(name); + } catch (error) { + throw new RestorePreflightError( + name, + `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + }; + + const uiBytes = readEffective('ui.json'); + + if (!uiBytes) { + return; + } + + let ui; + + try { + ui = normalizeStoredUiConfig(JSON.parse(uiBytes.toString('utf8')) as unknown); + } catch (error) { + throw new RestorePreflightError('ui.json', 'effective UI config is invalid JSON', { + cause: error, + }); + } + + const background = ui.appearance.background; + + if (!background.hasImage) { + return; + } + + const image = readEffective('ui-assets/background'); + + if (!image) { + throw new RestorePreflightError( + 'ui.json + ui-assets/background', + 'background metadata says an image exists, but the effective image is missing', + ); + } + + if (image.length > MAX_BACKGROUND_BYTES) { + throw new RestorePreflightError( + 'ui.json + ui-assets/background', + `effective background exceeds ${String(MAX_BACKGROUND_BYTES)} bytes`, + ); + } + + const mime = sniffImageMime(image); + + if (!mime) { + throw new RestorePreflightError( + 'ui.json + ui-assets/background', + 'effective background is not PNG, JPEG, or WebP', + ); + } + + if (mime !== background.imageMime) { + throw new RestorePreflightError( + 'ui.json + ui-assets/background', + `background metadata MIME ${background.imageMime} does not match image bytes ${mime}`, + ); + } } diff --git a/packages/core/src/webui/client-ip.ts b/packages/core/src/webui/client-ip.ts index ead56398..2d70b3ff 100644 --- a/packages/core/src/webui/client-ip.ts +++ b/packages/core/src/webui/client-ip.ts @@ -2,88 +2,131 @@ import { getConnInfo } from '@hono/node-server/conninfo'; import type { Context } from 'hono'; export type TrustProxyMode = - | { kind: 'none' } - | { kind: 'loopback' } - | { kind: 'all' } - | { kind: 'ip-list'; ips: Set }; + | { kind: 'none' } + | { kind: 'loopback' } + | { kind: 'all' } + | { kind: 'ip-list'; ips: Set }; export function parseTrustProxy(raw: string | undefined): TrustProxyMode { - const value = raw?.trim().toLowerCase() ?? ''; - if (!value) return { kind: 'none' }; - if (value === '1' || value === 'true' || value === 'all') return { kind: 'all' }; - if (value === 'loopback') return { kind: 'loopback' }; - const ips = new Set( - value.split(',').map((s) => s.trim()).filter(Boolean), - ); - if (ips.size === 0) return { kind: 'none' }; - return { kind: 'ip-list', ips }; + const value = raw?.trim().toLowerCase() ?? ''; + + if (!value) { + return { kind: 'none' }; + } + + if (value === '1' || value === 'true' || value === 'all') { + return { kind: 'all' }; + } + + if (value === 'loopback') { + return { kind: 'loopback' }; + } + + const ips = new Set( + value + .split(',') + .map((s) => s.trim()) + .filter(Boolean), + ); + + if (ips.size === 0) { + return { kind: 'none' }; + } + + return { kind: 'ip-list', ips }; } export function describeTrustProxy(mode: TrustProxyMode): string { - switch (mode.kind) { - case 'none': return 'socket peer (default)'; - case 'all': return 'X-Real-IP / X-Forwarded-For from any peer'; - case 'loopback': return 'X-Real-IP / X-Forwarded-For when socket peer is loopback'; - case 'ip-list': return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`; - } + switch (mode.kind) { + case 'none': + return 'socket peer (default)'; + case 'all': + return 'X-Real-IP / X-Forwarded-For from any peer'; + case 'loopback': + return 'X-Real-IP / X-Forwarded-For when socket peer is loopback'; + case 'ip-list': + return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`; + } } export function isLoopbackClientIp(ip: string): boolean { - const normalized = ip.trim().toLowerCase(); - if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') return true; - if (normalized.startsWith('::ffff:')) { - return isLoopbackClientIp(normalized.slice('::ffff:'.length)); - } - const octets = normalized.split('.'); - return octets.length === 4 - && octets[0] === '127' - && octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255); + const normalized = ip.trim().toLowerCase(); + + if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') { + return true; + } + + if (normalized.startsWith('::ffff:')) { + return isLoopbackClientIp(normalized.slice('::ffff:'.length)); + } + + const octets = normalized.split('.'); + return ( + octets.length === 4 && + octets[0] === '127' && + octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255) + ); } function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean { - switch (mode.kind) { - case 'none': return false; - case 'all': return true; - case 'loopback': return isLoopbackClientIp(socketIp); - case 'ip-list': return mode.ips.has(socketIp); - } + switch (mode.kind) { + case 'none': + return false; + case 'all': + return true; + case 'loopback': + return isLoopbackClientIp(socketIp); + case 'ip-list': + return mode.ips.has(socketIp); + } } export function pickClientIp( - c: Pick, - mode: TrustProxyMode, - getSocketIp: () => string, - fallbackIp = '127.0.0.1', + c: Pick, + mode: TrustProxyMode, + getSocketIp: () => string, + fallbackIp = '127.0.0.1', ): string { - let socketIp: string; - try { - socketIp = getSocketIp(); - } catch { - return fallbackIp; - } - if (!socketIp) return fallbackIp; + let socketIp: string; - if (!shouldTrustHeaders(mode, socketIp)) return socketIp; + try { + socketIp = getSocketIp(); + } catch { + return fallbackIp; + } - const realIp = c.req.header('x-real-ip')?.trim(); - if (realIp) return realIp; - const xff = c.req.header('x-forwarded-for'); - if (xff) { - const first = xff.split(',')[0].trim(); - if (first) return first; - } - return socketIp; + if (!socketIp) { + return fallbackIp; + } + + if (!shouldTrustHeaders(mode, socketIp)) { + return socketIp; + } + + const realIp = c.req.header('x-real-ip')?.trim(); + + if (realIp) { + return realIp; + } + + const xff = c.req.header('x-forwarded-for'); + + if (xff) { + const first = xff.split(',')[0].trim(); + + if (first) { + return first; + } + } + + return socketIp; } /** Convenience binding for the live server: read socket via getConnInfo. */ export function makeClientIpResolver( - mode: TrustProxyMode, - fallbackIp = '127.0.0.1', + mode: TrustProxyMode, + fallbackIp = '127.0.0.1', ): (c: Context) => string { - return (c) => pickClientIp( - c, - mode, - () => getConnInfo(c).remote.address ?? fallbackIp, - fallbackIp, - ); + return (c) => + pickClientIp(c, mode, () => getConnInfo(c).remote.address ?? fallbackIp, fallbackIp); } diff --git a/packages/core/src/webui/connection-diff-loop.ts b/packages/core/src/webui/connection-diff-loop.ts index ca3558da..11ad67b7 100644 --- a/packages/core/src/webui/connection-diff-loop.ts +++ b/packages/core/src/webui/connection-diff-loop.ts @@ -11,138 +11,149 @@ * something update. */ -import { - createLogger, - runWithTraceRequest, -} from '@snowluma/common/logger'; +import { createLogger, runWithTraceRequest } from '@snowluma/common/logger'; import { renderParamsVerbose } from '@snowluma/common/log-summary'; import type { StateBus } from './state-bus'; const log = createLogger('WebUI.Connections'); export interface ConnectionDiffLoopOptions { - bus: StateBus; - /** Read the current adapter-status snapshot for every live UIN. */ - getSnapshot: () => unknown; - /** Optional projector — return the "comparable" subset of the snapshot. - * The full snapshot is what the SSE handler ships to the WebUI; this - * projection is what the diff loop compares between ticks. Use it to - * strip volatile fields (e.g. HH:MM:SS timestamps embedded in adapter - * `detail` strings) that would otherwise produce a publish every tick - * under any active webhook — defeating the loop's whole purpose. - * Default: identity. */ - pickComparable?: (snapshot: unknown) => unknown; - /** Poll cadence in milliseconds; default 500. */ - intervalMs?: number; + bus: StateBus; + /** Read the current adapter-status snapshot for every live UIN. */ + getSnapshot: () => unknown; + /** Optional projector — return the "comparable" subset of the snapshot. + * The full snapshot is what the SSE handler ships to the WebUI; this + * projection is what the diff loop compares between ticks. Use it to + * strip volatile fields (e.g. HH:MM:SS timestamps embedded in adapter + * `detail` strings) that would otherwise produce a publish every tick + * under any active webhook — defeating the loop's whole purpose. + * Default: identity. */ + pickComparable?: (snapshot: unknown) => unknown; + /** Poll cadence in milliseconds; default 500. */ + intervalMs?: number; } export interface ConnectionDiffLoopHandle { - /** Stop the loop. Subsequent snapshot mutations produce nothing. */ - dispose(): void; + /** Stop the loop. Subsequent snapshot mutations produce nothing. */ + dispose(): void; } export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle { - const intervalMs = opts.intervalMs ?? 500; - let lastSerialized = ''; - let haveBaseline = false; - let disposed = false; - // One-shot diagnostic latch: a projector that starts throwing only after - // a shape regression would otherwise wedge the baseline silently — no - // publishes, no log, no symptom besides "the dashboard's connections - // card stops updating". Surface it ONCE so the failure is visible. - let warnedSnapshotThrew = false; - let warnedProjectorThrew = false; + const intervalMs = opts.intervalMs ?? 500; + let lastSerialized = ''; + let haveBaseline = false; + let disposed = false; + // One-shot diagnostic latch: a projector that starts throwing only after + // a shape regression would otherwise wedge the baseline silently — no + // publishes, no log, no symptom besides "the dashboard's connections + // card stops updating". Surface it ONCE so the failure is visible. + let warnedSnapshotThrew = false; + let warnedProjectorThrew = false; - const tick = (): void => { - if (disposed) return; - let snap: unknown; - try { - snap = opts.getSnapshot(); - } catch (err) { - if (!warnedSnapshotThrew) { - warnedSnapshotThrew = true; + const tick = (): void => { + if (disposed) { + return; + } + + let snap: unknown; + + try { + snap = opts.getSnapshot(); + } catch (err) { + if (!warnedSnapshotThrew) { + warnedSnapshotThrew = true; + runWithTraceRequest(() => { + const startedAt = Date.now(); + log.trace('connection_diff_start phase=snapshot_read'); + log.trace( + 'connection_diff_terminal outcome=failed reason=snapshot_failed error=%j elapsedMs=%d', + err instanceof Error ? err.message : String(err), + Date.now() - startedAt, + ); + }); + } + + // Snapshot read failed (e.g. mid-shutdown). Skip this tick; the + // next one will retry. Don't reset the baseline so we don't + // spuriously republish when the snapshot starts working again. + return; + } + + let comparable: unknown; + + try { + comparable = opts.pickComparable ? opts.pickComparable(snap) : snap; + } catch (err) { + // A buggy projector must not crash the diff loop or wedge baseline. + // But silent wedge is its own bug class — log the FIRST occurrence + // so an operator can find it without re-running the loop locally. + if (!warnedProjectorThrew) { + warnedProjectorThrew = true; + log.error( + 'connection snapshot projector failed; updates may be stale: %s', + err instanceof Error ? err.message : String(err), + ); + runWithTraceRequest(() => { + const startedAt = Date.now(); + log.trace(() => [ + 'connection_diff_start phase=project snapshot=%s', + renderParamsVerbose(snap), + ]); + log.trace( + 'connection_diff_terminal outcome=failed reason=projector_failed error=%j elapsedMs=%d', + err instanceof Error ? err.message : String(err), + Date.now() - startedAt, + ); + }); + } + + return; + } + + const serialized = JSON.stringify(comparable); + + if (!haveBaseline) { + // First successful observation. The SSE handler's sendAllInitial + // already shipped a `connections` frame to every connected client + // on connect, so the baseline is what they already have — emitting + // it again would be a duplicate. Just store it. + lastSerialized = serialized; + haveBaseline = true; + return; + } + + if (serialized === lastSerialized) { + return; + } + + lastSerialized = serialized; runWithTraceRequest(() => { - const startedAt = Date.now(); - log.trace('connection_diff_start phase=snapshot_read'); - log.trace( - 'connection_diff_terminal outcome=failed reason=snapshot_failed error=%j elapsedMs=%d', - err instanceof Error ? err.message : String(err), - Date.now() - startedAt, - ); + const startedAt = Date.now(); + log.trace(() => ['connection_diff_start snapshot=%s', renderParamsVerbose(snap)]); + log.trace('connection_diff_branch branch=publish resource=connections'); + opts.bus.publish('connections'); + log.trace( + 'connection_diff_terminal outcome=completed reason=published elapsedMs=%d', + Date.now() - startedAt, + ); }); - } - // Snapshot read failed (e.g. mid-shutdown). Skip this tick; the - // next one will retry. Don't reset the baseline so we don't - // spuriously republish when the snapshot starts working again. - return; - } - let comparable: unknown; - try { - comparable = opts.pickComparable ? opts.pickComparable(snap) : snap; - } catch (err) { - // A buggy projector must not crash the diff loop or wedge baseline. - // But silent wedge is its own bug class — log the FIRST occurrence - // so an operator can find it without re-running the loop locally. - if (!warnedProjectorThrew) { - warnedProjectorThrew = true; - log.error( - 'connection snapshot projector failed; updates may be stale: %s', - err instanceof Error ? err.message : String(err), - ); - runWithTraceRequest(() => { - const startedAt = Date.now(); - log.trace(() => [ - 'connection_diff_start phase=project snapshot=%s', - renderParamsVerbose(snap), - ]); - log.trace( - 'connection_diff_terminal outcome=failed reason=projector_failed error=%j elapsedMs=%d', - err instanceof Error ? err.message : String(err), - Date.now() - startedAt, - ); - }); - } - return; - } - const serialized = JSON.stringify(comparable); - if (!haveBaseline) { - // First successful observation. The SSE handler's sendAllInitial - // already shipped a `connections` frame to every connected client - // on connect, so the baseline is what they already have — emitting - // it again would be a duplicate. Just store it. - lastSerialized = serialized; - haveBaseline = true; - return; - } - if (serialized === lastSerialized) return; - lastSerialized = serialized; - runWithTraceRequest(() => { - const startedAt = Date.now(); - log.trace(() => [ - 'connection_diff_start snapshot=%s', - renderParamsVerbose(snap), - ]); - log.trace('connection_diff_branch branch=publish resource=connections'); - opts.bus.publish('connections'); - log.trace( - 'connection_diff_terminal outcome=completed reason=published elapsedMs=%d', - Date.now() - startedAt, - ); - }); - }; + }; - const timer = setInterval(tick, intervalMs); - // Don't pin the Node event loop: the loop is permanent for the server - // lifetime by design, but tests / a future hot-reload scenario must be - // able to exit cleanly without an outstanding interval ref. Mirrors the - // tokenJanitor pattern in server.ts. - timer.unref?.(); + const timer = setInterval(tick, intervalMs); + // Don't pin the Node event loop: the loop is permanent for the server + // lifetime by design, but tests / a future hot-reload scenario must be + // able to exit cleanly without an outstanding interval ref. Mirrors the + // tokenJanitor pattern in server.ts. + timer.unref?.(); - return { - dispose(): void { - if (disposed) return; - disposed = true; - clearInterval(timer); - }, - }; + return { + dispose(): void { + if (disposed) { + return; + } + + disposed = true; + clearInterval(timer); + }, + }; } diff --git a/packages/core/src/webui/connection-snapshot.ts b/packages/core/src/webui/connection-snapshot.ts index 3c15cb2e..c824ad08 100644 --- a/packages/core/src/webui/connection-snapshot.ts +++ b/packages/core/src/webui/connection-snapshot.ts @@ -1,28 +1,31 @@ import type { AccountConnections } from '@snowluma/onebot/manager'; export function comparableConnectionSnapshot(snapshot: unknown): unknown { - if (!Array.isArray(snapshot)) return snapshot; - return (snapshot as AccountConnections[]).map((account) => ({ - uin: account.uin, - nickname: account.nickname, - adapters: Array.isArray(account.adapters) - ? account.adapters.map((adapter) => ({ - name: adapter.name, - kind: adapter.kind, - status: adapter.status, - lastErrorAt: adapter.lastErrorAt, - })) - : [], - databaseMigration: account.databaseMigration - ? { - phase: account.databaseMigration.phase, - usable: account.databaseMigration.usable, - processed: account.databaseMigration.processed, - total: account.databaseMigration.total, - progress: account.databaseMigration.progress, - estimatedRemainingSeconds: account.databaseMigration.estimatedRemainingSeconds, - error: account.databaseMigration.error, - } - : undefined, - })); + if (!Array.isArray(snapshot)) { + return snapshot; + } + + return (snapshot as AccountConnections[]).map((account) => ({ + uin: account.uin, + nickname: account.nickname, + adapters: Array.isArray(account.adapters) + ? account.adapters.map((adapter) => ({ + name: adapter.name, + kind: adapter.kind, + status: adapter.status, + lastErrorAt: adapter.lastErrorAt, + })) + : [], + databaseMigration: account.databaseMigration + ? { + phase: account.databaseMigration.phase, + usable: account.databaseMigration.usable, + processed: account.databaseMigration.processed, + total: account.databaseMigration.total, + progress: account.databaseMigration.progress, + estimatedRemainingSeconds: account.databaseMigration.estimatedRemainingSeconds, + error: account.databaseMigration.error, + } + : undefined, + })); } diff --git a/packages/core/src/webui/consent.ts b/packages/core/src/webui/consent.ts index 4790e4a9..222ecf07 100644 --- a/packages/core/src/webui/consent.ts +++ b/packages/core/src/webui/consent.ts @@ -14,8 +14,8 @@ const CONSENT_CONFIG_PATH = path.join(CONFIG_DIR, 'consent.json'); // repo-root markdown; the build copies them next to the bundle (dist/) so the // same lookup works in a packaged deploy. See vite.config.ts cp targets. const AGREEMENT_FILES = [ - { id: 'eula' as const, file: 'EULA.md' }, - { id: 'privacy' as const, file: 'PRIVACY.md' }, + { id: 'eula' as const, file: 'EULA.md' }, + { id: 'privacy' as const, file: 'PRIVACY.md' }, ]; export const EULA_ACCEPT_ENV = 'SNOWLUMA_ACCEPT_EULA'; @@ -24,54 +24,60 @@ export const PRIVACY_ACCEPT_ENV = 'SNOWLUMA_ACCEPT_PRIVACY'; type ConsentEnvironment = Readonly>; export interface EnvironmentConsent { - eulaAccepted: boolean; - privacyAccepted: boolean; - /** Both documents must be accepted; a partial opt-in never unlocks the gate. */ - accepted: boolean; + eulaAccepted: boolean; + privacyAccepted: boolean; + /** Both documents must be accepted; a partial opt-in never unlocks the gate. */ + accepted: boolean; } export interface AgreementDoc { - id: 'eula' | 'privacy'; - /** First markdown `# ` heading, for the tab/section title. */ - title: string; - /** Declared "Version: x" from the doc — display only, NOT the consent key. */ - declaredVersion: string; - /** Declared effective date (YYYY-MM-DD) — display only. */ - effectiveDate: string; - /** Full markdown body the frontend renders. */ - text: string; + id: 'eula' | 'privacy'; + /** First markdown `# ` heading, for the tab/section title. */ + title: string; + /** Declared "Version: x" from the doc — display only, NOT the consent key. */ + declaredVersion: string; + /** Declared effective date (YYYY-MM-DD) — display only. */ + effectiveDate: string; + /** Full markdown body the frontend renders. */ + text: string; } export interface ConsentRecord { - /** The content-hash agreements version that was accepted. */ - version: string; - /** ISO timestamp of acceptance. */ - acceptedAt: string; + /** The content-hash agreements version that was accepted. */ + version: string; + /** ISO timestamp of acceptance. */ + acceptedAt: string; } export interface AgreementsPayload { - /** Content-hash version of the current agreement set. */ - version: string; - /** - * True when the operator must (re-)accept: the agreements carry real text, - * environment consent is incomplete, AND the stored consent version differs - * from the current one. A missing or unreadable agreement set fails OPEN (no - * gate) so a broken bundle can never lock the admin out of their own panel. - */ - consentRequired: boolean; - documents: AgreementDoc[]; + /** Content-hash version of the current agreement set. */ + version: string; + /** + * True when the operator must (re-)accept: the agreements carry real text, + * environment consent is incomplete, AND the stored consent version differs + * from the current one. A missing or unreadable agreement set fails OPEN (no + * gate) so a broken bundle can never lock the admin out of their own panel. + */ + consentRequired: boolean; + documents: AgreementDoc[]; } function parseEnvironmentAcceptance(name: string, raw: string | undefined): boolean { - if (raw === undefined || raw.trim() === '') return false; + if (raw === undefined || raw.trim() === '') { + return false; + } - const normalized = raw.trim().toLowerCase(); - if (normalized === '1' || normalized === 'true') return true; - if (normalized === '0' || normalized === 'false') return false; + const normalized = raw.trim().toLowerCase(); - throw new Error( - `${name} must be one of: 1, true, 0, false; received ${JSON.stringify(raw)}`, - ); + if (normalized === '1' || normalized === 'true') { + return true; + } + + if (normalized === '0' || normalized === 'false') { + return false; + } + + throw new Error(`${name} must be one of: 1, true, 0, false; received ${JSON.stringify(raw)}`); } /** @@ -80,15 +86,15 @@ function parseEnvironmentAcceptance(name: string, raw: string | undefined): bool * versioned consent gate instead of silently writing a permanent record. */ export function resolveEnvironmentConsent( - env: ConsentEnvironment = process.env, + env: ConsentEnvironment = process.env, ): EnvironmentConsent { - const eulaAccepted = parseEnvironmentAcceptance(EULA_ACCEPT_ENV, env[EULA_ACCEPT_ENV]); - const privacyAccepted = parseEnvironmentAcceptance(PRIVACY_ACCEPT_ENV, env[PRIVACY_ACCEPT_ENV]); - return { - eulaAccepted, - privacyAccepted, - accepted: eulaAccepted && privacyAccepted, - }; + const eulaAccepted = parseEnvironmentAcceptance(EULA_ACCEPT_ENV, env[EULA_ACCEPT_ENV]); + const privacyAccepted = parseEnvironmentAcceptance(PRIVACY_ACCEPT_ENV, env[PRIVACY_ACCEPT_ENV]); + return { + eulaAccepted, + privacyAccepted, + accepted: eulaAccepted && privacyAccepted, + }; } // ── Agreement loading (pure-ish; file read + parse, cached) ───────────────── @@ -101,35 +107,39 @@ export function resolveEnvironmentConsent( * root or dist/), so we probe a handful of candidates and take the first hit. */ function resolveAgreementFile(file: string): string | null { - const candidates = [ - path.join(__dirname, file), // packaged: dist/ - path.resolve(__dirname, '..', '..', '..', '..', file), // dev tsx: repoRoot/ - path.resolve(process.cwd(), file), // started from repo root - path.resolve(process.cwd(), '..', '..', file), // dev cwd = packages/core - ]; - for (const candidate of candidates) { - try { - if (fs.existsSync(candidate)) return candidate; - } catch { - /* unreadable candidate, try next */ + const candidates = [ + path.join(__dirname, file), // packaged: dist/ + path.resolve(__dirname, '..', '..', '..', '..', file), // dev tsx: repoRoot/ + path.resolve(process.cwd(), file), // started from repo root + path.resolve(process.cwd(), '..', '..', file), // dev cwd = packages/core + ]; + + for (const candidate of candidates) { + try { + if (fs.existsSync(candidate)) { + return candidate; + } + } catch { + /* unreadable candidate, try next */ + } } - } - return null; + + return null; } /** Extract title / declared version / effective date from a doc body. */ export function parseAgreementMeta(text: string): { - title: string; - declaredVersion: string; - effectiveDate: string; + title: string; + declaredVersion: string; + effectiveDate: string; } { - const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() ?? ''; - // Matches both "Version: 1.0" / "版本 / Version:** 1.0" style lines. - const declaredVersion = - text.match(/(?:Version|版本)[^\n0-9]*([0-9][0-9A-Za-z.-]*)/)?.[1]?.trim() ?? ''; - const effectiveDate = - text.match(/(?:Effective date|生效日期)[^\n0-9]*(\d{4}-\d{2}-\d{2})/)?.[1] ?? ''; - return { title, declaredVersion, effectiveDate }; + const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() ?? ''; + // Matches both "Version: 1.0" / "版本 / Version:** 1.0" style lines. + const declaredVersion = + text.match(/(?:Version|版本)[^\n0-9]*([0-9][0-9A-Za-z.-]*)/)?.[1]?.trim() ?? ''; + const effectiveDate = + text.match(/(?:Effective date|生效日期)[^\n0-9]*(\d{4}-\d{2}-\d{2})/)?.[1] ?? ''; + return { title, declaredVersion, effectiveDate }; } /** @@ -139,89 +149,126 @@ export function parseAgreementMeta(text: string): { * and changes the moment any agreement's TEXT changes (forcing re-consent). */ export function computeAgreementsVersion(docs: { id: string; text: string }[]): string { - const hash = createHash('sha256'); - for (const doc of docs) { - hash.update(doc.id); - hash.update('\0'); - hash.update(doc.text); - hash.update('\0'); - } - return hash.digest('hex').slice(0, 16); + const hash = createHash('sha256'); + + for (const doc of docs) { + hash.update(doc.id); + hash.update('\0'); + hash.update(doc.text); + hash.update('\0'); + } + + return hash.digest('hex').slice(0, 16); } let cache: { docs: AgreementDoc[]; version: string } | null = null; /** Load + parse both agreements and compute the version. Cached per process. */ export function loadAgreements(): { docs: AgreementDoc[]; version: string } { - if (cache) return cache; - const docs: AgreementDoc[] = AGREEMENT_FILES.map(({ id, file }) => { - const resolved = resolveAgreementFile(file); - let text = ''; - if (resolved) { - try { - text = fs.readFileSync(resolved, 'utf8'); - } catch (err) { - log.warn('failed to read %s: %s', file, err instanceof Error ? err.message : String(err)); - } - } else { - log.warn('agreement file not found (looked for %s near the bundle and repo root)', file); + if (cache) { + return cache; } - const meta = parseAgreementMeta(text); - return { id, title: meta.title, declaredVersion: meta.declaredVersion, effectiveDate: meta.effectiveDate, text }; - }); - cache = { docs, version: computeAgreementsVersion(docs) }; - return cache; + + const docs: AgreementDoc[] = AGREEMENT_FILES.map(({ id, file }) => { + const resolved = resolveAgreementFile(file); + let text = ''; + + if (resolved) { + try { + text = fs.readFileSync(resolved, 'utf8'); + } catch (err) { + log.warn( + 'failed to read %s: %s', + file, + err instanceof Error ? err.message : String(err), + ); + } + } else { + log.warn( + 'agreement file not found (looked for %s near the bundle and repo root)', + file, + ); + } + + const meta = parseAgreementMeta(text); + return { + id, + title: meta.title, + declaredVersion: meta.declaredVersion, + effectiveDate: meta.effectiveDate, + text, + }; + }); + cache = { docs, version: computeAgreementsVersion(docs) }; + return cache; } // ── Consent persistence (config/consent.json, atomic) ─────────────────────── function ensureConfigDir(): void { - fs.mkdirSync(CONFIG_DIR, { recursive: true }); + fs.mkdirSync(CONFIG_DIR, { recursive: true }); } function isConsentRecord(value: unknown): value is ConsentRecord { - if (!value || typeof value !== 'object') return false; - const v = value as Record; - return typeof v.version === 'string' && v.version.length > 0 && typeof v.acceptedAt === 'string'; + if (!value || typeof value !== 'object') { + return false; + } + + const v = value as Record; + return ( + typeof v.version === 'string' && v.version.length > 0 && typeof v.acceptedAt === 'string' + ); } export function loadConsentRecord(): ConsentRecord | null { - try { - if (!fs.existsSync(CONSENT_CONFIG_PATH)) return null; - const parsed = JSON.parse(fs.readFileSync(CONSENT_CONFIG_PATH, 'utf8')) as unknown; - return isConsentRecord(parsed) ? parsed : null; - } catch (err) { - log.warn('consent.json unreadable, treating as no consent: %s', err instanceof Error ? err.message : String(err)); - return null; - } + try { + if (!fs.existsSync(CONSENT_CONFIG_PATH)) { + return null; + } + + const parsed = JSON.parse(fs.readFileSync(CONSENT_CONFIG_PATH, 'utf8')) as unknown; + return isConsentRecord(parsed) ? parsed : null; + } catch (err) { + log.warn( + 'consent.json unreadable, treating as no consent: %s', + err instanceof Error ? err.message : String(err), + ); + return null; + } } function atomicWrite(record: ConsentRecord): void { - ensureConfigDir(); - const tmp = CONSENT_CONFIG_PATH + '.tmp'; - fs.writeFileSync(tmp, JSON.stringify(record, null, 2), { encoding: 'utf8' }); - fs.renameSync(tmp, CONSENT_CONFIG_PATH); + ensureConfigDir(); + const tmp = CONSENT_CONFIG_PATH + '.tmp'; + fs.writeFileSync(tmp, JSON.stringify(record, null, 2), { encoding: 'utf8' }); + fs.renameSync(tmp, CONSENT_CONFIG_PATH); } /** Persist that the operator accepted `version`. Returns the stored record. */ export function recordConsent(version: string): ConsentRecord { - const record: ConsentRecord = { version, acceptedAt: new Date().toISOString() }; - atomicWrite(record); - return record; + const record: ConsentRecord = { version, acceptedAt: new Date().toISOString() }; + atomicWrite(record); + return record; } /** True when neither environment nor stored consent covers the current agreements. */ export function isConsentRequired(env: ConsentEnvironment = process.env): boolean { - if (resolveEnvironmentConsent(env).accepted) return false; + if (resolveEnvironmentConsent(env).accepted) { + return false; + } - const { docs, version } = loadAgreements(); - const hasContent = docs.some((d) => d.text.trim().length > 0); - if (!hasContent) return false; // fail open: never brick the panel on a broken bundle - return loadConsentRecord()?.version !== version; + const { docs, version } = loadAgreements(); + const hasContent = docs.some((d) => d.text.trim().length > 0); + + if (!hasContent) { + return false; + } // fail open: never brick the panel on a broken bundle + + return loadConsentRecord()?.version !== version; } /** Public payload for GET /api/agreements (texts + version + consentRequired). */ export function getAgreementsPayload(): AgreementsPayload { - const { docs, version } = loadAgreements(); - return { version, consentRequired: isConsentRequired(), documents: docs }; + const { docs, version } = loadAgreements(); + return { version, consentRequired: isConsentRequired(), documents: docs }; } diff --git a/packages/core/src/webui/debug-stream.ts b/packages/core/src/webui/debug-stream.ts index cc6889f7..9d2450d2 100644 --- a/packages/core/src/webui/debug-stream.ts +++ b/packages/core/src/webui/debug-stream.ts @@ -5,24 +5,33 @@ // 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; + /** 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`)); - }; + 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/debug-tools.ts b/packages/core/src/webui/debug-tools.ts index 66a62030..5e2ce9c2 100644 --- a/packages/core/src/webui/debug-tools.ts +++ b/packages/core/src/webui/debug-tools.ts @@ -35,27 +35,29 @@ const UPLOAD_TTL_MS = 24 * 60 * 60 * 1000; * with no path separators or traversal. The client path is NEVER trusted for * placement — this is only used to keep the stored name human-readable. */ export function safeUploadName(raw: string | undefined): string { - // Treat both separators as path delimiters, then take the basename so any - // `../` / absolute prefix is discarded regardless of host platform. - const base = path.basename(String(raw ?? '').replace(/\\/g, '/')); - const cleaned = base - .replace(/[^\w.-]+/g, '_') // collapse anything exotic to underscore - .replace(/^\.+/, '') // no leading dots (no hidden / '..' names) - .slice(0, 120); - return cleaned || 'file'; + // Treat both separators as path delimiters, then take the basename so any + // `../` / absolute prefix is discarded regardless of host platform. + const base = path.basename(String(raw ?? '').replace(/\\/g, '/')); + const cleaned = base + .replace(/[^\w.-]+/g, '_') // collapse anything exotic to underscore + .replace(/^\.+/, '') // no leading dots (no hidden / '..' names) + .slice(0, 120); + return cleaned || 'file'; } /** Unguessable destination path under DEBUG_UPLOAD_DIR for a sanitised name. * Throws if the composed path would escape the dir (defence in depth — it * can't, given the random id + basename, but we assert anyway). */ export function uploadDestPath(safeName: string): string { - const id = randomBytes(12).toString('hex'); - const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`); - const rel = path.relative(DEBUG_UPLOAD_DIR, dest); - if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) { - throw new Error('invalid upload path'); - } - return dest; + const id = randomBytes(12).toString('hex'); + const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`); + const rel = path.relative(DEBUG_UPLOAD_DIR, dest); + + if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) { + throw new Error('invalid upload path'); + } + + return dest; } /** Stream raw request-body bytes to a temp file under DEBUG_UPLOAD_DIR, enforcing @@ -63,84 +65,126 @@ export function uploadDestPath(safeName: string): string { * error the partial file is removed and the call rejects. Never buffers the * whole body. */ export async function streamUploadToDisk( - body: ReadableStream | null, - filename: string | undefined, - opts: { maxBytes?: number } = {}, + body: ReadableStream | null, + filename: string | undefined, + opts: { maxBytes?: number } = {}, ): Promise<{ path: string; size: number }> { - if (!body) throw new Error('empty body'); - const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES; - await mkdir(DEBUG_UPLOAD_DIR, { recursive: true }); - void sweepOldUploads(); // fire-and-forget TTL cleanup - - const dest = uploadDestPath(safeUploadName(filename)); - const out = createWriteStream(dest, { mode: 0o600 }); - // A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a - // background flush — typically while we're parked at reader.read() or waiting - // on 'drain'. An unhandled 'error' event would crash the whole process, and a - // backpressured error would leave 'drain' to never fire (a forever-hung await - // + leaked fd). So turn it into a rejection and race it into every await; the - // catch below then destroys + unlinks the partial. - const errored = new Promise((_, rej) => out.once('error', rej)); - errored.catch(() => { /* swallow a late error after success (still raced below) */ }); - let size = 0; - try { - const reader = body.getReader(); - for (;;) { - const { done, value } = await Promise.race([errored, reader.read()]); - if (done) break; - if (!value || value.byteLength === 0) continue; - const offset = size; - size += value.byteLength; - traceWebuiMutationRequestChunk(value, offset); - if (size > maxBytes) throw new Error('上传超出大小上限'); - // Respect the write stream's backpressure (but never hang on an error). - if (!out.write(value)) { - await Promise.race([errored, new Promise((res) => out.once('drain', res))]); - } + if (!body) { + throw new Error('empty body'); + } + + const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES; + await mkdir(DEBUG_UPLOAD_DIR, { recursive: true }); + void sweepOldUploads(); // fire-and-forget TTL cleanup + + const dest = uploadDestPath(safeUploadName(filename)); + const out = createWriteStream(dest, { mode: 0o600 }); + // A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a + // background flush — typically while we're parked at reader.read() or waiting + // on 'drain'. An unhandled 'error' event would crash the whole process, and a + // backpressured error would leave 'drain' to never fire (a forever-hung await + // + leaked fd). So turn it into a rejection and race it into every await; the + // catch below then destroys + unlinks the partial. + const errored = new Promise((_, rej) => out.once('error', rej)); + errored.catch(() => { + /* swallow a late error after success (still raced below) */ + }); + let size = 0; + + try { + const reader = body.getReader(); + + for (;;) { + const { done, value } = await Promise.race([errored, reader.read()]); + + if (done) { + break; + } + + if (!value || value.byteLength === 0) { + continue; + } + + const offset = size; + size += value.byteLength; + traceWebuiMutationRequestChunk(value, offset); + + if (size > maxBytes) { + throw new Error('上传超出大小上限'); + } + + // Respect the write stream's backpressure (but never hang on an error). + if (!out.write(value)) { + await Promise.race([errored, new Promise((res) => out.once('drain', res))]); + } + } + + await Promise.race([ + errored, + new Promise((res, rej) => + out.end((err?: Error | null) => (err ? rej(err) : res())), + ), + ]); + + if (size === 0) { + throw new Error('empty body'); + } + + return { path: dest, size }; + } catch (err) { + // Wait for the stream to fully close BEFORE unlinking: createWriteStream + // opens the fd asynchronously, so a fast failure can reach `rm` before the + // file even exists on disk — then the late open would re-create it and leak + // the partial. 'close' guarantees the fd is settled and no more writes land. + out.destroy(); + + if (!out.closed) { + await new Promise((res) => out.once('close', () => res())); + } + + await rm(dest, { force: true }).catch(() => { + /* best-effort */ + }); + throw err; } - await Promise.race([errored, new Promise((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())))]); - if (size === 0) throw new Error('empty body'); - return { path: dest, size }; - } catch (err) { - // Wait for the stream to fully close BEFORE unlinking: createWriteStream - // opens the fd asynchronously, so a fast failure can reach `rm` before the - // file even exists on disk — then the late open would re-create it and leak - // the partial. 'close' guarantees the fd is settled and no more writes land. - out.destroy(); - if (!out.closed) await new Promise((res) => out.once('close', () => res())); - await rm(dest, { force: true }).catch(() => { /* best-effort */ }); - throw err; - } } /** Remove upload temp files older than the TTL. Best-effort; never throws. */ export async function sweepOldUploads(now: number = Date.now()): Promise { - let removed = 0; - try { - const names = await readdir(DEBUG_UPLOAD_DIR); - await Promise.all( - names.map(async (n) => { - const p = path.join(DEBUG_UPLOAD_DIR, n); - try { - const s = await stat(p); - if (now - s.mtimeMs > UPLOAD_TTL_MS) { - await rm(p, { force: true, recursive: true }); - removed += 1; - } - } catch { /* racing cleanup / vanished file */ } - }), - ); - } catch { /* dir absent yet */ } - return removed; + let removed = 0; + + try { + const names = await readdir(DEBUG_UPLOAD_DIR); + await Promise.all( + names.map(async (n) => { + const p = path.join(DEBUG_UPLOAD_DIR, n); + + try { + const s = await stat(p); + + if (now - s.mtimeMs > UPLOAD_TTL_MS) { + await rm(p, { force: true, recursive: true }); + removed += 1; + } + } catch { + /* racing cleanup / vanished file */ + } + }), + ); + } catch { + /* dir absent yet */ + } + + return removed; } /** Drives a stream-capable action and relays its frames. The driver is the * instance's `invokeStream` (which itself handles non-stream actions by emitting * a single frame). */ export type StreamInvokeDriver = ( - rawRequest: string, - emit: (json: string) => Promise, - isAlive: () => boolean, + rawRequest: string, + emit: (json: string) => Promise, + isAlive: () => boolean, ) => Promise; /** How long emit() will wait for a backed-up consumer to drain before it gives @@ -154,47 +198,75 @@ const DRAIN_MAX_SPINS = 3000; // 3000 * 20ms ≈ 60s * becomes a terminal `failed` frame. Closing the request (signal abort) stops * delivery. `delay` is injectable for tests. */ export function buildStreamInvokeResponse( - driver: StreamInvokeDriver, - rawRequest: string, - signal: AbortSignal, - delay: (ms: number) => Promise = (ms) => new Promise((r) => setTimeout(r, ms)), + driver: StreamInvokeDriver, + rawRequest: string, + signal: AbortSignal, + delay: (ms: number) => Promise = (ms) => new Promise((r) => setTimeout(r, ms)), ): Response { - const encoder = new TextEncoder(); - const stream = new ReadableStream({ - async start(controller) { - let closed = false; - const onAbort = () => { closed = true; }; - signal.addEventListener('abort', onAbort); - const isAlive = () => !closed && !signal.aborted; + const encoder = new TextEncoder(); + const stream = new ReadableStream({ + async start(controller) { + let closed = false; - const emit = async (json: string): Promise => { - if (!isAlive()) throw new Error('stream transport closed'); - // Backpressure WITHOUT dropping: wait for the consumer to catch up. - let spins = 0; - while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) { - await delay(DRAIN_WAIT_MS); - spins += 1; - } - if (!isAlive()) throw new Error('stream transport closed'); - controller.enqueue(encoder.encode(`data: ${json}\n\n`)); - }; + const onAbort = () => { + closed = true; + }; - try { - await driver(rawRequest, emit, isAlive); - } catch (err) { - if (isAlive()) { - const msg = err instanceof Error ? err.message : 'stream error'; - try { - controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`)); - } catch { /* controller already torn down */ } - } - } finally { - signal.removeEventListener('abort', onAbort); - try { controller.close(); } catch { /* already closed */ } - } - }, - }); - return new Response(stream, { - headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }, - }); + signal.addEventListener('abort', onAbort); + const isAlive = () => !closed && !signal.aborted; + + const emit = async (json: string): Promise => { + if (!isAlive()) { + throw new Error('stream transport closed'); + } + + // Backpressure WITHOUT dropping: wait for the consumer to catch up. + let spins = 0; + + while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) { + await delay(DRAIN_WAIT_MS); + spins += 1; + } + + if (!isAlive()) { + throw new Error('stream transport closed'); + } + + controller.enqueue(encoder.encode(`data: ${json}\n\n`)); + }; + + try { + await driver(rawRequest, emit, isAlive); + } catch (err) { + if (isAlive()) { + const msg = err instanceof Error ? err.message : 'stream error'; + + try { + controller.enqueue( + encoder.encode( + `data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`, + ), + ); + } catch { + /* controller already torn down */ + } + } + } finally { + signal.removeEventListener('abort', onAbort); + + try { + controller.close(); + } catch { + /* already closed */ + } + } + }, + }); + return new Response(stream, { + headers: { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + }, + }); } diff --git a/packages/core/src/webui/listener-exposure.ts b/packages/core/src/webui/listener-exposure.ts index 3470f72d..f5b7d22f 100644 --- a/packages/core/src/webui/listener-exposure.ts +++ b/packages/core/src/webui/listener-exposure.ts @@ -1,27 +1,40 @@ import { isIP } from 'node:net'; export type ListenerExposureCheck = - | { ok: true } - | { ok: false; code: 'invalid-bind-host' | 'tls-pair-required' }; + { ok: true } | { ok: false; code: 'invalid-bind-host' | 'tls-pair-required' }; /** TCP bind-host accepted by WebUI Listener Exposure (settings, restore, boot). */ export function isValidBindHost(value: string): boolean { - const host = value.trim(); - if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) return false; - if (host.includes(':')) return isIP(host) === 6; - if (/^[\d.]+$/.test(host)) { - return isIP(host) === 4; - } - const normalized = host.endsWith('.') ? host.slice(0, -1) : host; - return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(? 253 || /[\s/?#@]/u.test(host)) { + return false; + } + + if (host.includes(':')) { + return isIP(host) === 6; + } + + if (/^[\d.]+$/.test(host)) { + return isIP(host) === 4; + } + + const normalized = host.endsWith('.') ? host.slice(0, -1) : host; + return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(? entry.line)); - } + if (entries.length === 0) { + lines.push('(No log records are currently retained.)'); + } else { + lines.push(...entries.map((entry) => entry.line)); + } - return `${lines.join('\n')}\n`; + return `${lines.join('\n')}\n`; } diff --git a/packages/core/src/webui/mutation-trace.ts b/packages/core/src/webui/mutation-trace.ts index c8951968..81227660 100644 --- a/packages/core/src/webui/mutation-trace.ts +++ b/packages/core/src/webui/mutation-trace.ts @@ -1,11 +1,11 @@ import { renderParamsVerbose } from '@snowluma/common/log-summary'; import { - createLogger, - currentRequestId, - getLogLevel, - renderTraceBytes, - runWithRequestId, - runWithTraceRequest, + createLogger, + currentRequestId, + getLogLevel, + renderTraceBytes, + runWithRequestId, + runWithTraceRequest, } from '@snowluma/common/logger'; const log = createLogger('WebUI.Mutation'); @@ -14,284 +14,343 @@ const STREAMED_REQUEST_PATHS = new Set(['/api/debug/upload']); const STREAMED_RESPONSE_PATHS = new Set(['/api/debug/invoke-stream']); // This route can disable TRACE while its own operation is in flight; its // existing WebUI info record is the authoritative result. -const TRACE_EXCLUDED_PATHS = new Set([ - '/api/auth/check-strength', - '/api/logs/level', -]); +const TRACE_EXCLUDED_PATHS = new Set(['/api/auth/check-strength', '/api/logs/level']); interface CapturedBody { - bytes: Uint8Array; - text: string; + bytes: Uint8Array; + text: string; } function shouldTraceMutation(request: Request): boolean { - if (getLogLevel() !== 'trace') return false; - if (READ_ONLY_METHODS.has(request.method.toUpperCase())) return false; - return !TRACE_EXCLUDED_PATHS.has(new URL(request.url).pathname); + if (getLogLevel() !== 'trace') { + return false; + } + + if (READ_ONLY_METHODS.has(request.method.toUpperCase())) { + return false; + } + + return !TRACE_EXCLUDED_PATHS.has(new URL(request.url).pathname); } async function captureBody(message: Request | Response): Promise { - const bytes = new Uint8Array(await message.arrayBuffer()); - return { - bytes, - text: new TextDecoder().decode(bytes), - }; + const bytes = new Uint8Array(await message.arrayBuffer()); + return { + bytes, + text: new TextDecoder().decode(bytes), + }; } function traceBody( - branch: 'request_body' | 'response', - body: CapturedBody, - response?: Response, + branch: 'request_body' | 'response', + body: CapturedBody, + response?: Response, ): void { - log.trace(() => [ - 'webui_mutation_branch branch=%s%s length=%d text=%j body=%s', - branch, - response - ? ` status=${response.status} statusText=${JSON.stringify(response.statusText)} headers=${renderParamsVerbose([...response.headers.entries()])}` - : '', - body.bytes.byteLength, - body.text, - renderTraceBytes(body.bytes), - ]); + log.trace(() => [ + 'webui_mutation_branch branch=%s%s length=%d text=%j body=%s', + branch, + response + ? ` status=${response.status} statusText=${JSON.stringify(response.statusText)} headers=${renderParamsVerbose([...response.headers.entries()])}` + : '', + body.bytes.byteLength, + body.text, + renderTraceBytes(body.bytes), + ]); } function traceStreamChunk( - branch: 'request_body_chunk' | 'response_chunk', - chunk: Uint8Array, - offset: number, + branch: 'request_body_chunk' | 'response_chunk', + chunk: Uint8Array, + offset: number, ): void { - log.trace(() => [ - 'webui_mutation_branch branch=%s offset=%d length=%d body=%s', - branch, - offset, - chunk.byteLength, - renderTraceBytes(chunk), - ]); + log.trace(() => [ + 'webui_mutation_branch branch=%s offset=%d length=%d body=%s', + branch, + offset, + chunk.byteLength, + renderTraceBytes(chunk), + ]); } export function traceWebuiMutationRequestChunk(chunk: Uint8Array, offset: number): void { - traceStreamChunk('request_body_chunk', chunk, offset); + traceStreamChunk('request_body_chunk', chunk, offset); } function traceStreamedResponse( - response: Response, - requestBody: Promise | null, - startedAt: number, + response: Response, + requestBody: Promise | null, + startedAt: number, ): Response { - if (!response.body) { - void settleMutation( - requestBody, - Promise.resolve({ bytes: new Uint8Array(), text: '' }), - response, - startedAt, - false, - ); - return response; - } + if (!response.body) { + void settleMutation( + requestBody, + Promise.resolve({ bytes: new Uint8Array(), text: '' }), + response, + startedAt, + false, + ); + return response; + } - const reader = response.body.getReader(); - const requestId = currentRequestId(); - const inContext = (fn: () => T): T => requestId === undefined - ? fn() - : runWithRequestId(requestId, fn); - let offset = 0; - let settled = false; - const terminal = (outcome: 'completed' | 'failed' | 'cancelled', reason: string, error?: unknown) => { - if (settled) return; - settled = true; - void inContext(() => traceRequestBody(requestBody)).then(() => { - inContext(() => log.trace( - 'webui_mutation_terminal outcome=%s reason=%s status=%d%s elapsedMs=%d', - outcome, - reason, - response.status, - error === undefined ? '' : ` error=${JSON.stringify(error instanceof Error ? error.message : String(error))}`, - Date.now() - startedAt, - )); - }); - }; - const body = new ReadableStream({ - async pull(controller) { - try { - const result = await reader.read(); - if (result.done) { - terminal(response.ok ? 'completed' : 'failed', response.ok ? 'response_completed' : 'http_status'); - controller.close(); - return; + const reader = response.body.getReader(); + const requestId = currentRequestId(); + const inContext = (fn: () => T): T => + requestId === undefined ? fn() : runWithRequestId(requestId, fn); + let offset = 0; + let settled = false; + + const terminal = ( + outcome: 'completed' | 'failed' | 'cancelled', + reason: string, + error?: unknown, + ) => { + if (settled) { + return; } - const chunk = result.value; - inContext(() => traceStreamChunk('response_chunk', chunk, offset)); - offset += chunk.byteLength; - controller.enqueue(chunk); - } catch (error) { - terminal(error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed', - error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed', error); - controller.error(error); - } - }, - async cancel(reason) { - terminal('cancelled', 'body_cancelled', reason); - await reader.cancel(reason); - }, - }, { highWaterMark: 0 }); - return new Response(body, response); + + settled = true; + void inContext(() => traceRequestBody(requestBody)).then(() => { + inContext(() => + log.trace( + 'webui_mutation_terminal outcome=%s reason=%s status=%d%s elapsedMs=%d', + outcome, + reason, + response.status, + error === undefined + ? '' + : ` error=${JSON.stringify(error instanceof Error ? error.message : String(error))}`, + Date.now() - startedAt, + ), + ); + }); + }; + + const body = new ReadableStream( + { + async pull(controller) { + try { + const result = await reader.read(); + + if (result.done) { + terminal( + response.ok ? 'completed' : 'failed', + response.ok ? 'response_completed' : 'http_status', + ); + controller.close(); + return; + } + + const chunk = result.value; + inContext(() => traceStreamChunk('response_chunk', chunk, offset)); + offset += chunk.byteLength; + controller.enqueue(chunk); + } catch (error) { + terminal( + error instanceof Error && error.name === 'AbortError' + ? 'cancelled' + : 'failed', + error instanceof Error && error.name === 'AbortError' + ? 'body_cancelled' + : 'body_read_failed', + error, + ); + controller.error(error); + } + }, + async cancel(reason) { + terminal('cancelled', 'body_cancelled', reason); + await reader.cancel(reason); + }, + }, + { highWaterMark: 0 }, + ); + return new Response(body, response); } async function traceRequestBody(requestBody: Promise | null): Promise { - if (!requestBody) return; - try { - traceBody('request_body', await requestBody); - } catch (error) { - log.trace( - 'webui_mutation_branch branch=request_body_failed error=%j', - error instanceof Error ? error.message : String(error), - ); - } + if (!requestBody) { + return; + } + + try { + traceBody('request_body', await requestBody); + } catch (error) { + log.trace( + 'webui_mutation_branch branch=request_body_failed error=%j', + error instanceof Error ? error.message : String(error), + ); + } } async function settleMutation( - requestBody: Promise | null, - responseBody: Promise, - response: Response, - startedAt: number, - requestCancelled: boolean, + requestBody: Promise | null, + responseBody: Promise, + response: Response, + startedAt: number, + requestCancelled: boolean, ): Promise { - const results = await Promise.allSettled([ - requestBody ?? Promise.resolve({ bytes: new Uint8Array(), text: '' }), - responseBody, - ]); - const [requestResult, responseResult] = results; - if (requestBody && requestResult.status === 'fulfilled') traceBody('request_body', requestResult.value); - if (requestBody && requestResult.status === 'rejected') { - log.trace('webui_mutation_branch branch=request_body_failed error=%j', - requestResult.reason instanceof Error ? requestResult.reason.message : String(requestResult.reason)); - } - if (responseResult.status === 'fulfilled') traceBody('response', responseResult.value, response); - else { - log.trace(() => [ - 'webui_mutation_branch branch=response_body_failed status=%d statusText=%j headers=%s error=%j', - response.status, - response.statusText, - renderParamsVerbose([...response.headers.entries()]), - responseResult.reason instanceof Error ? responseResult.reason.message : String(responseResult.reason), + const results = await Promise.allSettled([ + requestBody ?? Promise.resolve({ bytes: new Uint8Array(), text: '' }), + responseBody, ]); - } - const error = responseResult.status === 'rejected' - ? responseResult.reason - : requestResult.status === 'rejected' - ? requestResult.reason - : undefined; - if (error === undefined) { - if (requestCancelled) { - log.trace( - 'webui_mutation_terminal outcome=cancelled reason=request_cancelled status=%d elapsedMs=%d', - response.status, - Date.now() - startedAt, - ); - return; + const [requestResult, responseResult] = results; + + if (requestBody && requestResult.status === 'fulfilled') { + traceBody('request_body', requestResult.value); } + + if (requestBody && requestResult.status === 'rejected') { + log.trace( + 'webui_mutation_branch branch=request_body_failed error=%j', + requestResult.reason instanceof Error + ? requestResult.reason.message + : String(requestResult.reason), + ); + } + + if (responseResult.status === 'fulfilled') { + traceBody('response', responseResult.value, response); + } else { + log.trace(() => [ + 'webui_mutation_branch branch=response_body_failed status=%d statusText=%j headers=%s error=%j', + response.status, + response.statusText, + renderParamsVerbose([...response.headers.entries()]), + responseResult.reason instanceof Error + ? responseResult.reason.message + : String(responseResult.reason), + ]); + } + + const error = + responseResult.status === 'rejected' + ? responseResult.reason + : requestResult.status === 'rejected' + ? requestResult.reason + : undefined; + + if (error === undefined) { + if (requestCancelled) { + log.trace( + 'webui_mutation_terminal outcome=cancelled reason=request_cancelled status=%d elapsedMs=%d', + response.status, + Date.now() - startedAt, + ); + return; + } + + log.trace( + 'webui_mutation_terminal outcome=%s reason=%s status=%d elapsedMs=%d', + response.ok ? 'completed' : 'failed', + response.ok ? 'response_completed' : 'http_status', + response.status, + Date.now() - startedAt, + ); + return; + } + log.trace( - 'webui_mutation_terminal outcome=%s reason=%s status=%d elapsedMs=%d', - response.ok ? 'completed' : 'failed', - response.ok ? 'response_completed' : 'http_status', - response.status, - Date.now() - startedAt, + 'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d', + error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed', + error instanceof Error && error.name === 'AbortError' + ? 'body_cancelled' + : 'body_read_failed', + error instanceof Error ? error.message : String(error), + Date.now() - startedAt, ); - return; - } - log.trace( - 'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d', - error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed', - error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed', - error instanceof Error ? error.message : String(error), - Date.now() - startedAt, - ); } function failureOutcome(error: unknown): { - outcome: 'failed' | 'timeout' | 'cancelled'; - reason: string; + outcome: 'failed' | 'timeout' | 'cancelled'; + reason: string; } { - if (error instanceof Error && error.name === 'TimeoutError') { - return { outcome: 'timeout', reason: 'handler_timeout' }; - } - if (error instanceof Error && error.name === 'AbortError') { - return { outcome: 'cancelled', reason: 'handler_cancelled' }; - } - return { outcome: 'failed', reason: 'handler_threw' }; + if (error instanceof Error && error.name === 'TimeoutError') { + return { outcome: 'timeout', reason: 'handler_timeout' }; + } + + if (error instanceof Error && error.name === 'AbortError') { + return { outcome: 'cancelled', reason: 'handler_cancelled' }; + } + + return { outcome: 'failed', reason: 'handler_threw' }; } /** Trace one authenticated WebUI write without consuming its live streams. */ export function traceAuthenticatedWebuiMutation( - request: Request, - next: () => Promise, + request: Request, + next: () => Promise, ): Promise { - if (!shouldTraceMutation(request)) return next(); - - return runWithTraceRequest(async () => { - const startedAt = Date.now(); - const requestHeaders = [...request.headers.entries()]; - const pathname = new URL(request.url).pathname; - let requestBody: Promise | null = null; - - log.trace(() => [ - 'webui_mutation_start method=%j url=%j headers=%s', - request.method, - request.url, - renderParamsVerbose(requestHeaders), - ]); - - if (!STREAMED_REQUEST_PATHS.has(pathname)) { - try { - requestBody = captureBody(request.clone()); - } catch (error) { - log.trace( - 'webui_mutation_terminal outcome=failed reason=request_clone_failed error=%j elapsedMs=%d', - error instanceof Error ? error.message : String(error), - Date.now() - startedAt, - ); + if (!shouldTraceMutation(request)) { return next(); - } } - try { - const response = await next(); - if (STREAMED_RESPONSE_PATHS.has(pathname)) { - return traceStreamedResponse(response, requestBody, startedAt); - } - let responseBody: Promise; - try { - responseBody = captureBody(response.clone()); - } catch (error) { - void traceRequestBody(requestBody).then(() => { - log.trace( - 'webui_mutation_terminal outcome=failed reason=response_clone_failed error=%j elapsedMs=%d', - error instanceof Error ? error.message : String(error), - Date.now() - startedAt, - ); - }); - return response; - } + return runWithTraceRequest(async () => { + const startedAt = Date.now(); + const requestHeaders = [...request.headers.entries()]; + const pathname = new URL(request.url).pathname; + let requestBody: Promise | null = null; - void settleMutation( - requestBody, - responseBody, - response, - startedAt, - STREAMED_REQUEST_PATHS.has(pathname) && request.signal.aborted, - ); - return response; - } catch (error) { - await traceRequestBody(requestBody); - const failure = failureOutcome(error); - log.trace( - 'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d', - failure.outcome, - failure.reason, - error instanceof Error ? error.message : String(error), - Date.now() - startedAt, - ); - throw error; - } - }); + log.trace(() => [ + 'webui_mutation_start method=%j url=%j headers=%s', + request.method, + request.url, + renderParamsVerbose(requestHeaders), + ]); + + if (!STREAMED_REQUEST_PATHS.has(pathname)) { + try { + requestBody = captureBody(request.clone()); + } catch (error) { + log.trace( + 'webui_mutation_terminal outcome=failed reason=request_clone_failed error=%j elapsedMs=%d', + error instanceof Error ? error.message : String(error), + Date.now() - startedAt, + ); + return next(); + } + } + + try { + const response = await next(); + + if (STREAMED_RESPONSE_PATHS.has(pathname)) { + return traceStreamedResponse(response, requestBody, startedAt); + } + + let responseBody: Promise; + + try { + responseBody = captureBody(response.clone()); + } catch (error) { + void traceRequestBody(requestBody).then(() => { + log.trace( + 'webui_mutation_terminal outcome=failed reason=response_clone_failed error=%j elapsedMs=%d', + error instanceof Error ? error.message : String(error), + Date.now() - startedAt, + ); + }); + return response; + } + + void settleMutation( + requestBody, + responseBody, + response, + startedAt, + STREAMED_REQUEST_PATHS.has(pathname) && request.signal.aborted, + ); + return response; + } catch (error) { + await traceRequestBody(requestBody); + const failure = failureOutcome(error); + log.trace( + 'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d', + failure.outcome, + failure.reason, + error instanceof Error ? error.message : String(error), + Date.now() - startedAt, + ); + throw error; + } + }); } diff --git a/packages/core/src/webui/onebot-token-policy.ts b/packages/core/src/webui/onebot-token-policy.ts index ff670686..4d78d66a 100644 --- a/packages/core/src/webui/onebot-token-policy.ts +++ b/packages/core/src/webui/onebot-token-policy.ts @@ -3,22 +3,34 @@ import type { OneBotConfig } from '@snowluma/onebot/types'; import { isLoopbackClientIp } from './client-ip'; function isLoopbackBindHost(host: string | undefined): boolean { - const value = host?.trim().toLowerCase().replace(/^\[|\]$/gu, '').replace(/\.$/u, '') ?? ''; - if (!value) return false; - if (value === 'localhost' || value.endsWith('.localhost')) return true; - return isLoopbackClientIp(value); + const value = + host + ?.trim() + .toLowerCase() + .replace(/^\[|\]$/gu, '') + .replace(/\.$/u, '') ?? ''; + + if (!value) { + return false; + } + + if (value === 'localhost' || value.endsWith('.localhost')) { + return true; + } + + return isLoopbackClientIp(value); } export class OneBotAccessTokenPolicyError extends Error { - constructor(message: string) { - super(message); - this.name = 'OneBotAccessTokenPolicyError'; - } + constructor(message: string) { + super(message); + this.name = 'OneBotAccessTokenPolicyError'; + } } export interface OneBotAccessTokenPolicyOptions { - clientIp: string; - uin: string; + clientIp: string; + uin: string; } type InboundKind = 'httpServers' | 'wsServers'; @@ -26,63 +38,77 @@ type InboundKind = 'httpServers' | 'wsServers'; const INBOUND_KINDS: readonly InboundKind[] = ['httpServers', 'wsServers']; function sameTokenAtPreviousIdentity( - previous: OneBotConfig['networks'][InboundKind], - next: OneBotConfig['networks'][InboundKind], - nextName: string, - nextToken: string, - index: number, + previous: OneBotConfig['networks'][InboundKind], + next: OneBotConfig['networks'][InboundKind], + nextName: string, + nextToken: string, + index: number, ): boolean { - const named = previous.find((adapter) => adapter.name === nextName); - if (named && (named.accessToken ?? '') === nextToken) return true; - // Preserve a legacy token when the operator only renames the same list item. - // Reordering keeps names stable and is covered by the lookup above. - const sameIndex = previous[index]; - return sameIndex !== undefined - && !next.some((adapter) => adapter.name === sameIndex.name) - && (sameIndex.accessToken ?? '') === nextToken; + const named = previous.find((adapter) => adapter.name === nextName); + + if (named && (named.accessToken ?? '') === nextToken) { + return true; + } + + // Preserve a legacy token when the operator only renames the same list item. + // Reordering keeps names stable and is covered by the lookup above. + const sameIndex = previous[index]; + return ( + sameIndex !== undefined && + !next.some((adapter) => adapter.name === sameIndex.name) && + (sameIndex.accessToken ?? '') === nextToken + ); } export function validateOneBotAccessTokenChanges( - previous: OneBotConfig | null, - next: OneBotConfig, - options: OneBotAccessTokenPolicyOptions, + previous: OneBotConfig | null, + next: OneBotConfig, + options: OneBotAccessTokenPolicyOptions, ): void { - const allowEmptyFromClient = isLoopbackClientIp(options.clientIp); - for (const kind of INBOUND_KINDS) { - const previousList = previous?.networks[kind] ?? []; - const nextList = next.networks[kind]; - for (let index = 0; index < nextList.length; index += 1) { - const adapter = nextList[index]; - const token = adapter.accessToken ?? ''; - if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) continue; + const allowEmptyFromClient = isLoopbackClientIp(options.clientIp); - if (!token) { - if (!allowEmptyFromClient && !isLoopbackBindHost(adapter.host)) { - throw new OneBotAccessTokenPolicyError( - `节点“${adapter.name}”未绑定本机地址,远程保存必须填写令牌;请生成令牌或将主机改为 127.0.0.1。`, - ); + for (const kind of INBOUND_KINDS) { + const previousList = previous?.networks[kind] ?? []; + const nextList = next.networks[kind]; + + for (let index = 0; index < nextList.length; index += 1) { + const adapter = nextList[index]; + const token = adapter.accessToken ?? ''; + + if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) { + continue; + } + + if (!token) { + if (!allowEmptyFromClient && !isLoopbackBindHost(adapter.host)) { + throw new OneBotAccessTokenPolicyError( + `节点“${adapter.name}”未绑定本机地址,远程保存必须填写令牌;请生成令牌或将主机改为 127.0.0.1。`, + ); + } + + continue; + } + + const host = adapter.host ?? '0.0.0.0'; + const assessment = assessAccessToken(token, [ + options.uin, + adapter.name, + kind, + host, + adapter.port, + ]); + + if (assessment.reason === 'too-short') { + throw new OneBotAccessTokenPolicyError( + `节点“${adapter.name}”的令牌至少需要 16 个字符;请重新生成或继续补充。`, + ); + } + + if (!assessment.acceptable) { + throw new OneBotAccessTokenPolicyError( + `节点“${adapter.name}”的令牌容易被猜中;请重新生成随机令牌。`, + ); + } } - continue; - } - - const host = adapter.host ?? '0.0.0.0'; - const assessment = assessAccessToken(token, [ - options.uin, - adapter.name, - kind, - host, - adapter.port, - ]); - if (assessment.reason === 'too-short') { - throw new OneBotAccessTokenPolicyError( - `节点“${adapter.name}”的令牌至少需要 16 个字符;请重新生成或继续补充。`, - ); - } - if (!assessment.acceptable) { - throw new OneBotAccessTokenPolicyError( - `节点“${adapter.name}”的令牌容易被猜中;请重新生成随机令牌。`, - ); - } } - } } diff --git a/packages/core/src/webui/port.ts b/packages/core/src/webui/port.ts index a273896b..fd943723 100644 --- a/packages/core/src/webui/port.ts +++ b/packages/core/src/webui/port.ts @@ -1,26 +1,33 @@ import net from 'net'; function isPortAvailable(port: number, host = '127.0.0.1'): Promise { - return new Promise((resolve) => { - const server = net.createServer(); - let settled = false; - const finalize = (ok: boolean) => { - if (settled) return; - settled = true; - try { - server.close(() => resolve(ok)); - } catch { - resolve(ok); - } - }; - server.once('error', () => finalize(false)); - server.once('listening', () => finalize(true)); - try { - server.listen(port, host); - } catch { - finalize(false); - } - }); + return new Promise((resolve) => { + const server = net.createServer(); + let settled = false; + + const finalize = (ok: boolean) => { + if (settled) { + return; + } + + settled = true; + + try { + server.close(() => resolve(ok)); + } catch { + resolve(ok); + } + }; + + server.once('error', () => finalize(false)); + server.once('listening', () => finalize(true)); + + try { + server.listen(port, host); + } catch { + finalize(false); + } + }); } /** @@ -28,15 +35,23 @@ function isPortAvailable(port: number, host = '127.0.0.1'): Promise { * Skips reserved/invalid port numbers. */ export async function findAvailablePort( - start: number, - options: { maxTries?: number; host?: string } = {}, + start: number, + options: { maxTries?: number; host?: string } = {}, ): Promise { - const { maxTries = 50, host = '127.0.0.1' } = options; - let port = Math.max(1, Math.min(65535, Math.trunc(start))); - for (let i = 0; i < maxTries; i++) { - if (port > 65535) break; - if (await isPortAvailable(port, host)) return port; - port += 1; - } - throw new Error(`No available TCP port found near ${start}`); + const { maxTries = 50, host = '127.0.0.1' } = options; + let port = Math.max(1, Math.min(65535, Math.trunc(start))); + + for (let i = 0; i < maxTries; i++) { + if (port > 65535) { + break; + } + + if (await isPortAvailable(port, host)) { + return port; + } + + port += 1; + } + + throw new Error(`No available TCP port found near ${start}`); } diff --git a/packages/core/src/webui/request-security.ts b/packages/core/src/webui/request-security.ts index dfdf6b5c..77e44781 100644 --- a/packages/core/src/webui/request-security.ts +++ b/packages/core/src/webui/request-security.ts @@ -7,59 +7,63 @@ const AVATAR_SESSION_COOKIE = 'snowluma_avatar_session'; const AVATAR_SESSION_MAX_AGE_SECONDS = 24 * 60 * 60; function isJsonMediaType(value: string | undefined): boolean { - const mediaType = value?.split(';', 1)[0]?.trim().toLowerCase() ?? ''; - return mediaType === 'application/json' || mediaType.endsWith('+json'); + const mediaType = value?.split(';', 1)[0]?.trim().toLowerCase() ?? ''; + return mediaType === 'application/json' || mediaType.endsWith('+json'); } /** Install guards before the login route is registered. */ export function registerLoginRequestSecurity(app: Hono): void { - app.use('/api/login', bodyLimit({ - maxSize: LOGIN_BODY_LIMIT_BYTES, - onError: (c) => c.json({ success: false, message: '请求体过大' }, 413), - })); - app.use('/api/login', async (c, next) => { - if (!isJsonMediaType(c.req.header('content-type'))) { - return c.json({ success: false, message: 'Content-Type 必须为 application/json' }, 415); - } - return next(); - }); + app.use( + '/api/login', + bodyLimit({ + maxSize: LOGIN_BODY_LIMIT_BYTES, + onError: (c) => c.json({ success: false, message: '请求体过大' }, 413), + }), + ); + app.use('/api/login', async (c, next) => { + if (!isJsonMediaType(c.req.header('content-type'))) { + return c.json({ success: false, message: 'Content-Type 必须为 application/json' }, 415); + } + + return next(); + }); } /** Minimal response policy that does not restrict the current script/style bundle. */ export const webuiSecurityHeaders: MiddlewareHandler = async (c, next) => { - await next(); - c.res.headers.set('X-Frame-Options', 'DENY'); - c.res.headers.set('X-Content-Type-Options', 'nosniff'); - c.res.headers.set('Referrer-Policy', 'no-referrer'); - c.res.headers.set( - 'Content-Security-Policy', - "frame-ancestors 'none'; base-uri 'self'; object-src 'none'", - ); + await next(); + c.res.headers.set('X-Frame-Options', 'DENY'); + c.res.headers.set('X-Content-Type-Options', 'nosniff'); + c.res.headers.set('Referrer-Policy', 'no-referrer'); + c.res.headers.set( + 'Content-Security-Policy', + "frame-ancestors 'none'; base-uri 'self'; object-src 'none'", + ); }; export function extractBearerToken(request: Request): string { - const authorization = request.headers.get('authorization'); - return authorization?.startsWith('Bearer ') ? authorization.slice(7) : ''; + const authorization = request.headers.get('authorization'); + return authorization?.startsWith('Bearer ') ? authorization.slice(7) : ''; } const avatarCookieOptions = (secure: boolean) => ({ - httpOnly: true, - sameSite: 'Strict' as const, - secure, - path: '/avatar', + httpOnly: true, + sameSite: 'Strict' as const, + secure, + path: '/avatar', }); export function setAvatarSessionCookie(c: Context, token: string, secure: boolean): void { - setCookie(c, AVATAR_SESSION_COOKIE, token, { - ...avatarCookieOptions(secure), - maxAge: AVATAR_SESSION_MAX_AGE_SECONDS, - }); + setCookie(c, AVATAR_SESSION_COOKIE, token, { + ...avatarCookieOptions(secure), + maxAge: AVATAR_SESSION_MAX_AGE_SECONDS, + }); } export function clearAvatarSessionCookie(c: Context, secure: boolean): void { - deleteCookie(c, AVATAR_SESSION_COOKIE, avatarCookieOptions(secure)); + deleteCookie(c, AVATAR_SESSION_COOKIE, avatarCookieOptions(secure)); } export function readAvatarSessionToken(c: Context): string { - return getCookie(c, AVATAR_SESSION_COOKIE) ?? ''; + return getCookie(c, AVATAR_SESSION_COOKIE) ?? ''; } diff --git a/packages/core/src/webui/restore.ts b/packages/core/src/webui/restore.ts index 42e24251..e9a03330 100644 --- a/packages/core/src/webui/restore.ts +++ b/packages/core/src/webui/restore.ts @@ -2,78 +2,74 @@ import { createLogger } from '@snowluma/common/logger'; import { randomUUID } from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; -import { - prepareRestorePlan, - RestorePreflightError, - type RestoreMigration, -} from './backup'; +import { prepareRestorePlan, RestorePreflightError, type RestoreMigration } from './backup'; const log = createLogger('WebUI.Restore'); export type RestorePhase = 'preflight' | 'snapshot' | 'stage' | 'commit' | 'rollback' | 'cleanup'; export interface RestoreOperation { - phase: Exclude; - operation: - | 'copy-current' - | 'write-staged' - | 'chmod-staged' - | 'rename-staged' - | 'restore-current' - | 'remove-created' - | 'remove-transaction'; - file?: string; + phase: Exclude; + operation: + | 'copy-current' + | 'write-staged' + | 'chmod-staged' + | 'rename-staged' + | 'restore-current' + | 'remove-created' + | 'remove-transaction'; + file?: string; } export interface RestoreBackupOptions { - configDir: string; - restoreCredentials: boolean; - /** Deterministic id for tests/diagnostics; production normally omits it. */ - transactionId?: string; - /** Filesystem-boundary fault hook used by the transaction fault matrix. */ - beforeOperation?: (operation: RestoreOperation) => void; + configDir: string; + restoreCredentials: boolean; + /** Deterministic id for tests/diagnostics; production normally omits it. */ + transactionId?: string; + /** Filesystem-boundary fault hook used by the transaction fault matrix. */ + beforeOperation?: (operation: RestoreOperation) => void; } export interface RestoreBackupResult { - transactionId: string; - restored: string[]; - skipped: string[]; - migrated: RestoreMigration[]; - restartRequiredToApply: boolean; + transactionId: string; + restored: string[]; + skipped: string[]; + migrated: RestoreMigration[]; + restartRequiredToApply: boolean; } export class RestoreTransactionError extends Error { - readonly phase: RestorePhase; - readonly transactionId: string; - readonly rollbackSucceeded?: boolean; - readonly snapshotDir?: string; - readonly committed: boolean; - readonly failedFiles: string[]; + readonly phase: RestorePhase; + readonly transactionId: string; + readonly rollbackSucceeded?: boolean; + readonly snapshotDir?: string; + readonly committed: boolean; + readonly failedFiles: string[]; - constructor(options: { - phase: RestorePhase; - transactionId: string; - message: string; - cause: unknown; - rollbackSucceeded?: boolean; - snapshotDir?: string; - committed?: boolean; - failedFiles?: string[]; - }) { - super(options.message, { cause: options.cause }); - this.name = 'RestoreTransactionError'; - this.phase = options.phase; - this.transactionId = options.transactionId; - this.rollbackSucceeded = options.rollbackSucceeded; - this.snapshotDir = options.snapshotDir; - this.committed = options.committed ?? false; - this.failedFiles = options.failedFiles ?? []; - } + constructor(options: { + phase: RestorePhase; + transactionId: string; + message: string; + cause: unknown; + rollbackSucceeded?: boolean; + snapshotDir?: string; + committed?: boolean; + failedFiles?: string[]; + }) { + super(options.message, { cause: options.cause }); + this.name = 'RestoreTransactionError'; + this.phase = options.phase; + this.transactionId = options.transactionId; + this.rollbackSucceeded = options.rollbackSucceeded; + this.snapshotDir = options.snapshotDir; + this.committed = options.committed ?? false; + this.failedFiles = options.failedFiles ?? []; + } } interface CommittedFile { - name: string; - existed: boolean; + name: string; + existed: boolean; } /** @@ -85,307 +81,365 @@ interface CommittedFile { * rollback retains the transaction directory and reports its recovery path. */ export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): RestoreBackupResult { - const transactionId = options.transactionId ?? randomUUID(); - if (!/^[A-Za-z0-9_-]+$/.test(transactionId)) { - throw new Error('restore transactionId must contain only letters, numbers, _ or -'); - } - const configDir = path.resolve(options.configDir); - const readCurrent = (name: string): Buffer | null => { - const file = path.join(configDir, name); - try { - return fs.readFileSync(file); - } catch (error) { - if (isMissingPathError(error)) return null; - throw error; - } - }; - const listCurrentOneBotNames = (): string[] => { - try { - return fs.readdirSync(configDir); - } catch (error) { - if (isMissingPathError(error)) return []; - throw error; - } - }; + const transactionId = options.transactionId ?? randomUUID(); - log.info('restore transaction=%s phase=preflight', transactionId); - let prepared: ReturnType; - try { - prepared = prepareRestorePlan(parsed, { - restoreCredentials: options.restoreCredentials, - readCurrent, - listCurrentOneBotNames, - }); - } catch (error) { - const file = error instanceof RestorePreflightError ? error.file : undefined; - log.warn( - 'restore transaction=%s phase=preflight file=%s failed error=%s', - transactionId, - file ?? '-', - errorMessage(error), - ); - throw new RestoreTransactionError({ - phase: 'preflight', - transactionId, - message: `restore preflight failed: ${errorMessage(error)}`, - cause: error, - failedFiles: file ? [file] : [], - }); - } - const names = prepared.restore.map((file) => file.name); - log.info('restore transaction=%s phase=preflight-complete files=%s', transactionId, names.join(',')); + if (!/^[A-Za-z0-9_-]+$/.test(transactionId)) { + throw new Error('restore transactionId must contain only letters, numbers, _ or -'); + } - if (prepared.restore.length === 0) { - return { - transactionId, - restored: [], - skipped: prepared.skipped, - migrated: prepared.migrated, - restartRequiredToApply: false, + const configDir = path.resolve(options.configDir); + + const readCurrent = (name: string): Buffer | null => { + const file = path.join(configDir, name); + + try { + return fs.readFileSync(file); + } catch (error) { + if (isMissingPathError(error)) { + return null; + } + + throw error; + } }; - } - const transactionDir = path.join(configDir, `.restore-transaction-${transactionId}`); - const snapshotRoot = path.join(transactionDir, 'snapshot'); - const stagedRoot = path.join(transactionDir, 'staged'); - const rollbackRoot = path.join(transactionDir, 'rollback'); - const existed = new Map(); - const committed: CommittedFile[] = []; - let phase: 'snapshot' | 'stage' | 'commit' = 'snapshot'; - let activeFile: string | undefined; - let transactionCreated = false; + const listCurrentOneBotNames = (): string[] => { + try { + return fs.readdirSync(configDir); + } catch (error) { + if (isMissingPathError(error)) { + return []; + } - try { - fs.mkdirSync(configDir, { recursive: true }); - fs.mkdirSync(transactionDir, { mode: 0o700 }); - transactionCreated = true; - fs.chmodSync(transactionDir, 0o700); + throw error; + } + }; - log.info('restore transaction=%s phase=snapshot files=%s', transactionId, names.join(',')); - for (const file of prepared.restore) { - activeFile = file.name; - const live = path.join(configDir, file.name); - let wasPresent: boolean; - try { - fs.lstatSync(live); - wasPresent = true; - } catch (error) { - if (!isMissingPathError(error)) throw error; - wasPresent = false; - } - existed.set(file.name, wasPresent); - if (!wasPresent) continue; - const snapshot = path.join(snapshotRoot, file.name); - fs.mkdirSync(path.dirname(snapshot), { recursive: true }); - invoke(options, { phase: 'snapshot', operation: 'copy-current', file: file.name }); - fs.copyFileSync(live, snapshot); - } + log.info('restore transaction=%s phase=preflight', transactionId); + let prepared: ReturnType; - phase = 'stage'; - log.info('restore transaction=%s phase=stage files=%s', transactionId, names.join(',')); - for (const file of prepared.restore) { - activeFile = file.name; - const staged = path.join(stagedRoot, file.name); - fs.mkdirSync(path.dirname(staged), { recursive: true }); - invoke(options, { phase: 'stage', operation: 'write-staged', file: file.name }); - fs.writeFileSync(staged, file.data, { flag: 'wx', mode: file.mode }); - invoke(options, { phase: 'stage', operation: 'chmod-staged', file: file.name }); - fs.chmodSync(staged, file.mode); - } - - phase = 'commit'; - log.info('restore transaction=%s phase=commit files=%s', transactionId, names.join(',')); - for (const file of prepared.restore) { - activeFile = file.name; - const staged = path.join(stagedRoot, file.name); - const live = path.join(configDir, file.name); - fs.mkdirSync(path.dirname(live), { recursive: true }); - invoke(options, { phase: 'commit', operation: 'rename-staged', file: file.name }); - fs.renameSync(staged, live); - committed.push({ name: file.name, existed: existed.get(file.name) === true }); - } - activeFile = undefined; - } catch (error) { - if (phase !== 'commit') { - const cleanupError = transactionCreated ? removeTransaction(options, transactionDir) : null; - if (cleanupError) { - log.error( - 'restore transaction=%s phase=cleanup failed-after=%s file=%s original-error=%s cleanup-error=%s', - transactionId, - phase, - activeFile ?? '-', - errorMessage(error), - errorMessage(cleanupError), + try { + prepared = prepareRestorePlan(parsed, { + restoreCredentials: options.restoreCredentials, + readCurrent, + listCurrentOneBotNames, + }); + } catch (error) { + const file = error instanceof RestorePreflightError ? error.file : undefined; + log.warn( + 'restore transaction=%s phase=preflight file=%s failed error=%s', + transactionId, + file ?? '-', + errorMessage(error), ); throw new RestoreTransactionError({ - phase: 'cleanup', - transactionId, - message: `restore ${phase} failed and transaction cleanup also failed`, - cause: new AggregateError([error, cleanupError], `restore ${phase} and cleanup both failed`), - snapshotDir: transactionDir, - failedFiles: activeFile ? [activeFile] : [], + phase: 'preflight', + transactionId, + message: `restore preflight failed: ${errorMessage(error)}`, + cause: error, + failedFiles: file ? [file] : [], }); - } - log.warn( - 'restore transaction=%s phase=%s file=%s failed error=%s', - transactionId, - phase, - activeFile ?? '-', - errorMessage(error), - ); - throw new RestoreTransactionError({ - phase, - transactionId, - message: `restore ${phase} failed before live commit`, - cause: error, - failedFiles: activeFile ? [activeFile] : [], - }); } - const rollbackErrors = rollbackCommitted(options, configDir, snapshotRoot, rollbackRoot, committed); - if (rollbackErrors.length > 0) { - const failedFiles = rollbackErrors.map((entry) => entry.name); - const rollbackDetails = rollbackErrors - .map((entry) => `${entry.name}:${errorMessage(entry.error)}`) - .join(';'); - log.error( - 'restore transaction=%s phase=rollback commit-file=%s commit-error=%s failed=%s snapshot=%s', + const names = prepared.restore.map((file) => file.name); + log.info( + 'restore transaction=%s phase=preflight-complete files=%s', transactionId, - activeFile ?? '-', - errorMessage(error), - rollbackDetails, - transactionDir, - ); - throw new RestoreTransactionError({ - phase: 'rollback', - transactionId, - message: 'restore commit failed and rollback was incomplete', - cause: new AggregateError( - [error, ...rollbackErrors.map((entry) => entry.error)], - 'restore commit and rollback both failed', - ), - rollbackSucceeded: false, - snapshotDir: transactionDir, - committed: committed.length > 0, - failedFiles, - }); + names.join(','), + ); + + if (prepared.restore.length === 0) { + return { + transactionId, + restored: [], + skipped: prepared.skipped, + migrated: prepared.migrated, + restartRequiredToApply: false, + }; + } + + const transactionDir = path.join(configDir, `.restore-transaction-${transactionId}`); + const snapshotRoot = path.join(transactionDir, 'snapshot'); + const stagedRoot = path.join(transactionDir, 'staged'); + const rollbackRoot = path.join(transactionDir, 'rollback'); + const existed = new Map(); + const committed: CommittedFile[] = []; + let phase: 'snapshot' | 'stage' | 'commit' = 'snapshot'; + let activeFile: string | undefined; + let transactionCreated = false; + + try { + fs.mkdirSync(configDir, { recursive: true }); + fs.mkdirSync(transactionDir, { mode: 0o700 }); + transactionCreated = true; + fs.chmodSync(transactionDir, 0o700); + + log.info('restore transaction=%s phase=snapshot files=%s', transactionId, names.join(',')); + + for (const file of prepared.restore) { + activeFile = file.name; + const live = path.join(configDir, file.name); + let wasPresent: boolean; + + try { + fs.lstatSync(live); + wasPresent = true; + } catch (error) { + if (!isMissingPathError(error)) { + throw error; + } + + wasPresent = false; + } + + existed.set(file.name, wasPresent); + + if (!wasPresent) { + continue; + } + + const snapshot = path.join(snapshotRoot, file.name); + fs.mkdirSync(path.dirname(snapshot), { recursive: true }); + invoke(options, { phase: 'snapshot', operation: 'copy-current', file: file.name }); + fs.copyFileSync(live, snapshot); + } + + phase = 'stage'; + log.info('restore transaction=%s phase=stage files=%s', transactionId, names.join(',')); + + for (const file of prepared.restore) { + activeFile = file.name; + const staged = path.join(stagedRoot, file.name); + fs.mkdirSync(path.dirname(staged), { recursive: true }); + invoke(options, { phase: 'stage', operation: 'write-staged', file: file.name }); + fs.writeFileSync(staged, file.data, { flag: 'wx', mode: file.mode }); + invoke(options, { phase: 'stage', operation: 'chmod-staged', file: file.name }); + fs.chmodSync(staged, file.mode); + } + + phase = 'commit'; + log.info('restore transaction=%s phase=commit files=%s', transactionId, names.join(',')); + + for (const file of prepared.restore) { + activeFile = file.name; + const staged = path.join(stagedRoot, file.name); + const live = path.join(configDir, file.name); + fs.mkdirSync(path.dirname(live), { recursive: true }); + invoke(options, { phase: 'commit', operation: 'rename-staged', file: file.name }); + fs.renameSync(staged, live); + committed.push({ name: file.name, existed: existed.get(file.name) === true }); + } + + activeFile = undefined; + } catch (error) { + if (phase !== 'commit') { + const cleanupError = transactionCreated + ? removeTransaction(options, transactionDir) + : null; + + if (cleanupError) { + log.error( + 'restore transaction=%s phase=cleanup failed-after=%s file=%s original-error=%s cleanup-error=%s', + transactionId, + phase, + activeFile ?? '-', + errorMessage(error), + errorMessage(cleanupError), + ); + throw new RestoreTransactionError({ + phase: 'cleanup', + transactionId, + message: `restore ${phase} failed and transaction cleanup also failed`, + cause: new AggregateError( + [error, cleanupError], + `restore ${phase} and cleanup both failed`, + ), + snapshotDir: transactionDir, + failedFiles: activeFile ? [activeFile] : [], + }); + } + + log.warn( + 'restore transaction=%s phase=%s file=%s failed error=%s', + transactionId, + phase, + activeFile ?? '-', + errorMessage(error), + ); + throw new RestoreTransactionError({ + phase, + transactionId, + message: `restore ${phase} failed before live commit`, + cause: error, + failedFiles: activeFile ? [activeFile] : [], + }); + } + + const rollbackErrors = rollbackCommitted( + options, + configDir, + snapshotRoot, + rollbackRoot, + committed, + ); + + if (rollbackErrors.length > 0) { + const failedFiles = rollbackErrors.map((entry) => entry.name); + const rollbackDetails = rollbackErrors + .map((entry) => `${entry.name}:${errorMessage(entry.error)}`) + .join(';'); + log.error( + 'restore transaction=%s phase=rollback commit-file=%s commit-error=%s failed=%s snapshot=%s', + transactionId, + activeFile ?? '-', + errorMessage(error), + rollbackDetails, + transactionDir, + ); + throw new RestoreTransactionError({ + phase: 'rollback', + transactionId, + message: 'restore commit failed and rollback was incomplete', + cause: new AggregateError( + [error, ...rollbackErrors.map((entry) => entry.error)], + 'restore commit and rollback both failed', + ), + rollbackSucceeded: false, + snapshotDir: transactionDir, + committed: committed.length > 0, + failedFiles, + }); + } + + const cleanupError = removeTransaction(options, transactionDir); + + if (cleanupError) { + log.error( + 'restore transaction=%s phase=cleanup failed-after=rollback commit-file=%s commit-error=%s cleanup-error=%s snapshot=%s', + transactionId, + activeFile ?? '-', + errorMessage(error), + errorMessage(cleanupError), + transactionDir, + ); + throw new RestoreTransactionError({ + phase: 'cleanup', + transactionId, + message: + 'restore commit failed, rollback succeeded, but transaction cleanup failed', + cause: new AggregateError( + [error, cleanupError], + 'restore commit and post-rollback cleanup both failed', + ), + rollbackSucceeded: true, + snapshotDir: transactionDir, + failedFiles: activeFile ? [activeFile] : [], + }); + } + + log.warn( + 'restore transaction=%s phase=commit file=%s failed rollback=complete error=%s', + transactionId, + activeFile ?? '-', + errorMessage(error), + ); + throw new RestoreTransactionError({ + phase: 'commit', + transactionId, + message: 'restore commit failed; every committed file was rolled back', + cause: error, + rollbackSucceeded: true, + failedFiles: activeFile ? [activeFile] : [], + }); } const cleanupError = removeTransaction(options, transactionDir); + if (cleanupError) { - log.error( - 'restore transaction=%s phase=cleanup failed-after=rollback commit-file=%s commit-error=%s cleanup-error=%s snapshot=%s', - transactionId, - activeFile ?? '-', - errorMessage(error), - errorMessage(cleanupError), - transactionDir, - ); - throw new RestoreTransactionError({ - phase: 'cleanup', - transactionId, - message: 'restore commit failed, rollback succeeded, but transaction cleanup failed', - cause: new AggregateError([error, cleanupError], 'restore commit and post-rollback cleanup both failed'), - rollbackSucceeded: true, - snapshotDir: transactionDir, - failedFiles: activeFile ? [activeFile] : [], - }); + log.error( + 'restore transaction=%s phase=cleanup failed-after=commit cleanup-error=%s snapshot=%s', + transactionId, + errorMessage(cleanupError), + transactionDir, + ); + throw new RestoreTransactionError({ + phase: 'cleanup', + transactionId, + message: 'restore committed successfully, but transaction cleanup failed', + cause: cleanupError, + snapshotDir: transactionDir, + committed: true, + }); } - log.warn( - 'restore transaction=%s phase=commit file=%s failed rollback=complete error=%s', - transactionId, - activeFile ?? '-', - errorMessage(error), - ); - throw new RestoreTransactionError({ - phase: 'commit', - transactionId, - message: 'restore commit failed; every committed file was rolled back', - cause: error, - rollbackSucceeded: true, - failedFiles: activeFile ? [activeFile] : [], - }); - } - const cleanupError = removeTransaction(options, transactionDir); - if (cleanupError) { - log.error( - 'restore transaction=%s phase=cleanup failed-after=commit cleanup-error=%s snapshot=%s', - transactionId, - errorMessage(cleanupError), - transactionDir, - ); - throw new RestoreTransactionError({ - phase: 'cleanup', - transactionId, - message: 'restore committed successfully, but transaction cleanup failed', - cause: cleanupError, - snapshotDir: transactionDir, - committed: true, - }); - } - - log.info('restore transaction=%s phase=complete files=%s', transactionId, names.join(',')); - return { - transactionId, - restored: names, - skipped: prepared.skipped, - migrated: prepared.migrated, - restartRequiredToApply: true, - }; + log.info('restore transaction=%s phase=complete files=%s', transactionId, names.join(',')); + return { + transactionId, + restored: names, + skipped: prepared.skipped, + migrated: prepared.migrated, + restartRequiredToApply: true, + }; } function rollbackCommitted( - options: RestoreBackupOptions, - configDir: string, - snapshotRoot: string, - rollbackRoot: string, - committed: readonly CommittedFile[], + options: RestoreBackupOptions, + configDir: string, + snapshotRoot: string, + rollbackRoot: string, + committed: readonly CommittedFile[], ): Array<{ name: string; error: unknown }> { - const errors: Array<{ name: string; error: unknown }> = []; - for (const file of [...committed].reverse()) { - const live = path.join(configDir, file.name); - try { - if (!file.existed) { - invoke(options, { phase: 'rollback', operation: 'remove-created', file: file.name }); - fs.rmSync(live, { force: true }); - continue; - } - const snapshot = path.join(snapshotRoot, file.name); - const rollback = path.join(rollbackRoot, file.name); - fs.mkdirSync(path.dirname(rollback), { recursive: true }); - invoke(options, { phase: 'rollback', operation: 'restore-current', file: file.name }); - fs.copyFileSync(snapshot, rollback); - fs.chmodSync(rollback, fs.statSync(snapshot).mode & 0o777); - fs.renameSync(rollback, live); - } catch (error) { - errors.push({ name: file.name, error }); + const errors: Array<{ name: string; error: unknown }> = []; + + for (const file of [...committed].reverse()) { + const live = path.join(configDir, file.name); + + try { + if (!file.existed) { + invoke(options, { + phase: 'rollback', + operation: 'remove-created', + file: file.name, + }); + fs.rmSync(live, { force: true }); + continue; + } + + const snapshot = path.join(snapshotRoot, file.name); + const rollback = path.join(rollbackRoot, file.name); + fs.mkdirSync(path.dirname(rollback), { recursive: true }); + invoke(options, { phase: 'rollback', operation: 'restore-current', file: file.name }); + fs.copyFileSync(snapshot, rollback); + fs.chmodSync(rollback, fs.statSync(snapshot).mode & 0o777); + fs.renameSync(rollback, live); + } catch (error) { + errors.push({ name: file.name, error }); + } } - } - return errors; + + return errors; } function removeTransaction(options: RestoreBackupOptions, transactionDir: string): unknown | null { - try { - invoke(options, { phase: 'cleanup', operation: 'remove-transaction' }); - fs.rmSync(transactionDir, { recursive: true, force: true }); - return null; - } catch (error) { - return error; - } + try { + invoke(options, { phase: 'cleanup', operation: 'remove-transaction' }); + fs.rmSync(transactionDir, { recursive: true, force: true }); + return null; + } catch (error) { + return error; + } } function invoke(options: RestoreBackupOptions, operation: RestoreOperation): void { - options.beforeOperation?.(operation); + options.beforeOperation?.(operation); } function errorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error); + return error instanceof Error ? error.message : String(error); } function isMissingPathError(error: unknown): boolean { - return typeof error === 'object' - && error !== null - && 'code' in error - && error.code === 'ENOENT'; + return ( + typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT' + ); } diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 606c8f79..0a7bf2ea 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -2,37 +2,46 @@ import { serve } from '@hono/node-server'; import { serveStatic } from '@hono/node-server/serve-static'; import type { HookManager, HookProcessInfo } from '@snowluma/bridge'; import { - clearManagedLogs, - configureFileTransport, - getLogStorageStatus, + clearManagedLogs, + configureFileTransport, + getLogStorageStatus, } from '@snowluma/common/log-file-transport'; import { - createLogger, - getLogLevel, - getLogSnapshot, - getRecentLogs, - logInitialWebuiCredentials, - LOG_LEVELS, - setLogLevel, - subscribeLogs, + createLogger, + getLogLevel, + getLogSnapshot, + getRecentLogs, + logInitialWebuiCredentials, + LOG_LEVELS, + setLogLevel, + subscribeLogs, } from '@snowluma/common/logger'; import { - assertValidOneBotConfig, - loadOneBotConfig, - OneBotConfigValidationError, - saveOneBotConfig, + assertValidOneBotConfig, + loadOneBotConfig, + OneBotConfigValidationError, + saveOneBotConfig, } from '@snowluma/onebot/config'; import { loadGlobalSettings, saveGlobalSettings } from '@snowluma/onebot/global-config'; import type { OneBotManager } from '@snowluma/onebot/manager'; -import { - clearInactiveStreamStorage, - snapshotStreamStorage, -} from '@snowluma/onebot/stream-storage'; +import { clearInactiveStreamStorage, snapshotStreamStorage } from '@snowluma/onebot/stream-storage'; import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types'; -import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime'; +import { + readRuntimeConfig, + updateRuntimeConfig, + resolveRuntimeEnvOverrides, +} from '@snowluma/common/runtime'; import { execSync } from 'child_process'; import { randomBytes } from 'crypto'; -import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs'; +import { + chmodSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'fs'; import { createServer as createHttpsServer } from 'https'; import { Hono, type Context } from 'hono'; import os from 'os'; @@ -41,22 +50,26 @@ import { fileURLToPath } from 'url'; import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth'; import { completeWebuiLogin, invalidateOtherSessions } from './webui-login'; import { - beginTotpEnrollment, - confirmTotpEnrollment, - decideSecondFactorLogin, - regenerateRecoveryCodes, + beginTotpEnrollment, + confirmTotpEnrollment, + decideSecondFactorLogin, + regenerateRecoveryCodes, } from './totp'; import { - EULA_ACCEPT_ENV, - getAgreementsPayload, - isConsentRequired, - loadAgreements, - PRIVACY_ACCEPT_ENV, - recordConsent, - resolveEnvironmentConsent, + EULA_ACCEPT_ENV, + getAgreementsPayload, + isConsentRequired, + loadAgreements, + PRIVACY_ACCEPT_ENV, + recordConsent, + resolveEnvironmentConsent, } from './consent'; import { requireTlsContext, resolveTlsContext, validateTlsPair } from './tls'; -import { coerceSettingsPatch, evaluateSettingsSave, tlsCertDeletionBlocked } from './system-settings'; +import { + coerceSettingsPatch, + evaluateSettingsSave, + tlsCertDeletionBlocked, +} from './system-settings'; import { checkListenerExposure } from './listener-exposure'; import { buildBackup } from './backup'; import { restoreBackup, RestoreTransactionError, type RestorePhase } from './restore'; @@ -71,19 +84,19 @@ import { comparableConnectionSnapshot } from './connection-snapshot'; import { traceAuthenticatedWebuiMutation } from './mutation-trace'; import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { - OneBotAccessTokenPolicyError, - validateOneBotAccessTokenChanges, + OneBotAccessTokenPolicyError, + validateOneBotAccessTokenChanges, } from './onebot-token-policy'; import { findAvailablePort } from './port'; import { - clearBackgroundImage, - loadUiConfig, - MAX_BACKGROUND_BYTES, - publicAppearance, - readBackgroundImage, - saveUiConfig, - sniffImageMime, - writeBackgroundImage, + clearBackgroundImage, + loadUiConfig, + MAX_BACKGROUND_BYTES, + publicAppearance, + readBackgroundImage, + saveUiConfig, + sniffImageMime, + writeBackgroundImage, } from './ui-config'; import { currentVersion, getUpdateInfo } from './update-check'; import { buildFullTraceDownload } from './log-export'; @@ -93,30 +106,33 @@ import { StorageManagementService } from './storage-management'; import { registerStorageRoutes } from './storage-routes'; import { LogStorageSettingsManager } from './storage-settings'; import { - clearAvatarSessionCookie, - extractBearerToken, - readAvatarSessionToken, - registerLoginRequestSecurity, - setAvatarSessionCookie, - webuiSecurityHeaders, + clearAvatarSessionCookie, + extractBearerToken, + readAvatarSessionToken, + registerLoginRequestSecurity, + setAvatarSessionCookie, + webuiSecurityHeaders, } from './request-security'; const log = createLogger('WebUI'); const __dirname = path.dirname(fileURLToPath(import.meta.url)); interface SessionInfo { - expiresAt: number; - mustChangePassword: boolean; + expiresAt: number; + mustChangePassword: boolean; } const sessionTokens = new Map(); const loginAttempts = new Map(); -const totpEnrollments = new Map(); +const totpEnrollments = new Map< + string, + { + secret: string; + issuer: string; + accountName: string; + expiresAt: number; + } +>(); const LOGIN_MAX_ATTEMPTS = 5; const LOGIN_LOCKOUT_MS = 15 * 60 * 1000; @@ -127,92 +143,101 @@ const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000; const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60; export interface RestoreFailureBody { - success: false; - message: string; - transactionId: string; - phase: RestorePhase; - committed: boolean; - rollbackSucceeded?: boolean; - snapshotDir?: string; - failedFiles: string[]; + success: false; + message: string; + transactionId: string; + phase: RestorePhase; + committed: boolean; + rollbackSucceeded?: boolean; + snapshotDir?: string; + failedFiles: string[]; } /** Translate transaction facts into an operator-facing HTTP failure. */ export function describeRestoreFailure(error: RestoreTransactionError): { - status: 400 | 500; - body: RestoreFailureBody; + status: 400 | 500; + body: RestoreFailureBody; } { - const detail = error.cause instanceof Error ? error.cause.message : error.message; - let message: string; + const detail = error.cause instanceof Error ? error.cause.message : error.message; + let message: string; - if (error.phase === 'preflight') { - message = `备份校验失败:${detail}`; - } else if (error.rollbackSucceeded === false) { - const recovery = error.snapshotDir ? `,恢复资料保留在 ${error.snapshotDir}` : ''; - message = `恢复失败,且自动回滚不完整。请勿重启或继续修改配置;事务 ID:${error.transactionId}${recovery}。请检查服务器日志。`; - } else if (error.committed) { - const retained = error.snapshotDir ? `,临时事务资料保留在 ${error.snapshotDir}` : ''; - message = `配置已恢复,但临时事务目录清理失败;重启后配置仍会生效。事务 ID:${error.transactionId}${retained}。请检查服务器日志。`; - } else if (error.phase === 'cleanup') { - const configState = error.rollbackSucceeded === true ? '当前配置已自动回滚' : '当前配置未改动'; - const retained = error.snapshotDir ? `,临时事务资料保留在 ${error.snapshotDir}` : ''; - message = `恢复失败,${configState},但临时事务目录清理失败;事务 ID:${error.transactionId}${retained}。请检查服务器日志。`; - } else if (error.rollbackSucceeded === true) { - message = `恢复失败,当前配置已自动回滚。事务 ID:${error.transactionId}。请检查服务器日志。`; - } else { - message = `恢复失败,当前配置未改动。事务 ID:${error.transactionId}。请检查服务器日志。`; - } + if (error.phase === 'preflight') { + message = `备份校验失败:${detail}`; + } else if (error.rollbackSucceeded === false) { + const recovery = error.snapshotDir ? `,恢复资料保留在 ${error.snapshotDir}` : ''; + message = `恢复失败,且自动回滚不完整。请勿重启或继续修改配置;事务 ID:${error.transactionId}${recovery}。请检查服务器日志。`; + } else if (error.committed) { + const retained = error.snapshotDir ? `,临时事务资料保留在 ${error.snapshotDir}` : ''; + message = `配置已恢复,但临时事务目录清理失败;重启后配置仍会生效。事务 ID:${error.transactionId}${retained}。请检查服务器日志。`; + } else if (error.phase === 'cleanup') { + const configState = + error.rollbackSucceeded === true ? '当前配置已自动回滚' : '当前配置未改动'; + const retained = error.snapshotDir ? `,临时事务资料保留在 ${error.snapshotDir}` : ''; + message = `恢复失败,${configState},但临时事务目录清理失败;事务 ID:${error.transactionId}${retained}。请检查服务器日志。`; + } else if (error.rollbackSucceeded === true) { + message = `恢复失败,当前配置已自动回滚。事务 ID:${error.transactionId}。请检查服务器日志。`; + } else { + message = `恢复失败,当前配置未改动。事务 ID:${error.transactionId}。请检查服务器日志。`; + } - return { - status: error.phase === 'preflight' ? 400 : 500, - body: { - success: false, - message, - transactionId: error.transactionId, - phase: error.phase, - committed: error.committed, - ...(error.rollbackSucceeded === undefined ? {} : { rollbackSucceeded: error.rollbackSucceeded }), - ...(error.snapshotDir === undefined ? {} : { snapshotDir: error.snapshotDir }), - failedFiles: error.failedFiles, - }, - }; + return { + status: error.phase === 'preflight' ? 400 : 500, + body: { + success: false, + message, + transactionId: error.transactionId, + phase: error.phase, + committed: error.committed, + ...(error.rollbackSucceeded === undefined + ? {} + : { rollbackSucceeded: error.rollbackSucceeded }), + ...(error.snapshotDir === undefined ? {} : { snapshotDir: error.snapshotDir }), + failedFiles: error.failedFiles, + }, + }; } function isMissingPath(error: unknown): boolean { - return error instanceof Error && 'code' in error && error.code === 'ENOENT'; + return error instanceof Error && 'code' in error && error.code === 'ENOENT'; } /** Read one allowlisted config file; I/O failures other than absence are fatal. */ export function readBackupConfigFile(configDir: string, name: string): Buffer | null { - try { - return readFileSync(path.join(configDir, name)); - } catch (error) { - if (isMissingPath(error)) return null; - throw error; - } + try { + return readFileSync(path.join(configDir, name)); + } catch (error) { + if (isMissingPath(error)) { + return null; + } + + throw error; + } } /** List per-account OneBot config candidates; an unreadable directory is fatal. */ export function listPerUinOneBotConfigFiles(configDir: string): string[] { - try { - return readdirSync(configDir).filter((name) => /^onebot_\d+\.json$/.test(name)); - } catch (error) { - if (isMissingPath(error)) return []; - throw error; - } + try { + return readdirSync(configDir).filter((name) => /^onebot_\d+\.json$/.test(name)); + } catch (error) { + if (isMissingPath(error)) { + return []; + } + + throw error; + } } // Endpoints that an auth-required-but-must-change-password session can still hit. const MUST_CHANGE_ALLOWLIST = new Set([ - '/api/status', - '/api/auth/state', - '/api/auth/check-strength', - '/api/auth/change-password', - // Consent is collected AFTER login but BEFORE the forced password change, so - // reading + recording it must be reachable while the session mustChangePassword. - '/api/agreements', - '/api/agreements/record-consent', - '/api/logout', + '/api/status', + '/api/auth/state', + '/api/auth/check-strength', + '/api/auth/change-password', + // Consent is collected AFTER login but BEFORE the forced password change, so + // reading + recording it must be reachable while the session mustChangePassword. + '/api/agreements', + '/api/agreements/record-consent', + '/api/logout', ]); // Endpoints reachable while consent is still pending. Everything else is 403'd @@ -221,11 +246,11 @@ const MUST_CHANGE_ALLOWLIST = new Set([ // not merely a frontend convention. Ordered BEFORE the must-change gate so a // fresh install must consent first, then set its password. const CONSENT_ALLOWLIST = new Set([ - '/api/status', - '/api/auth/state', - '/api/agreements', - '/api/agreements/record-consent', - '/api/logout', + '/api/status', + '/api/auth/state', + '/api/agreements', + '/api/agreements/record-consent', + '/api/logout', ]); // uin = QQ number; 5–10 digits (real QQ UINs fit in uint32, max 4294967295). @@ -238,1593 +263,2113 @@ const UIN_REGEX = /^\d{5,10}$/; const avatarCache = new Map(); function purgeExpiredTokens() { - const now = Date.now(); - for (const [token, info] of sessionTokens) { - if (now > info.expiresAt) sessionTokens.delete(token); - } - for (const [ip, attempt] of loginAttempts) { - if (now > attempt.resetAt) loginAttempts.delete(ip); - } - for (const [token, enrollment] of totpEnrollments) { - if (now > enrollment.expiresAt) totpEnrollments.delete(token); - } + const now = Date.now(); + + for (const [token, info] of sessionTokens) { + if (now > info.expiresAt) { + sessionTokens.delete(token); + } + } + + for (const [ip, attempt] of loginAttempts) { + if (now > attempt.resetAt) { + loginAttempts.delete(ip); + } + } + + for (const [token, enrollment] of totpEnrollments) { + if (now > enrollment.expiresAt) { + totpEnrollments.delete(token); + } + } } function sanitizeTotpLabelPart(value: unknown, fallback: string): string { - if (typeof value !== 'string') return fallback; - const trimmed = value.replace(/[\r\n\t]/g, '').trim(); - if (!trimmed) return fallback; - return trimmed.slice(0, 64); + if (typeof value !== 'string') { + return fallback; + } + + const trimmed = value.replace(/[\r\n\t]/g, '').trim(); + + if (!trimmed) { + return fallback; + } + + return trimmed.slice(0, 64); } function defaultTotpAccountName(): string { - const host = os.hostname().trim(); - return host || 'admin'; + const host = os.hostname().trim(); + return host || 'admin'; } - 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`, { - headers: { - 'User-Agent': 'SnowLuma WebUI', - Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8', - }, - }); - if (!response.ok) throw new Error(`avatar upstream responded with ${response.status}`); - const contentType = response.headers.get('content-type') || 'image/jpeg'; - const body = new Uint8Array(await response.arrayBuffer()); - return { body, contentType }; + const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, { + headers: { + 'User-Agent': 'SnowLuma WebUI', + Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8', + }, + }); + + if (!response.ok) { + throw new Error(`avatar upstream responded with ${response.status}`); + } + + const contentType = response.headers.get('content-type') || 'image/jpeg'; + const body = new Uint8Array(await response.arrayBuffer()); + return { body, contentType }; } // ── Host system info (cached at module level, invariant over process lifetime) ── function detectDistro(): string { - // Helper: extract major.minor.patch from a kernel version string - const parseKernel = (v: string): string | null => { const m = v.match(/(\d+\.\d+\.\d+)/); return m?.[1] ?? null; }; - - // ── Linux ────────────────────────────────────────────────────────── - if (os.platform() === 'linux') { - const kernelRelease = os.release(); - const kernelVer = parseKernel(kernelRelease); - - // Normalize RHEL-family distro names before comparison. - // /proc/version typically shows "Red Hat" (GCC build tag) even on - // Rocky / Alma / Oracle Linux, while /etc/os-release carries the - // actual distro name. Treat the whole family as a single group so - // they are never considered "disagreeing". - const isRhelFamily = (name: string): boolean => - /^(red hat|centos|rocky|alma|oracle|scientific|anolis|tencentos|bclinux|opencloudos)/.test(name); - - // Extract distro version from kernel release string. - // Distros embed their version in the kernel ABI / build tag: - // Debian: "6.8.12-1-deb13-amd64" → 13 - // RHEL family: "4.18.0-513.el9.x86_64" → 9 - // Fedora: "6.8.12-300.fc40.x86_64" → 40 - // Amazon Linux: "6.1.158-178.288.amzn2023" → 2023 - // Mageia: "6.8.12-1.mga10" → 10 - const kernelDistroVer = (distro: string | null): string | null => { - if (!distro) return null; - const lr = kernelRelease.toLowerCase(); - const ld = distro.toLowerCase(); - if (ld === 'debian') { const m = lr.match(/deb(\d+)/); if (m) return m[1]; } - if (isRhelFamily(ld)) { const m = lr.match(/el(\d+)/); if (m) return m[1]; } - if (ld === 'fedora') { const m = lr.match(/fc(\d+)/); if (m) return m[1]; } - if (ld === 'amazon' || ld.includes('amazon')) { const m = lr.match(/amzn(\d+)/); if (m) return m[1]; } - if (ld === 'mageia') { const m = lr.match(/mga(\d+)/); if (m) return m[1]; } - if (ld === 'armbian') { const m = lr.match(/armbian(\d+)/); if (m) return m[1]; } - if (ld === 'dietpi') { const m = lr.match(/dietpi(\d+)/); if (m) return m[1]; } - if (ld.includes('libreelec')) { const m = lr.match(/libreelec(\d+)/); if (m) return m[1]; } - if (ld.includes('coreelec')) { const m = lr.match(/coreelec(\d+)/); if (m) return m[1]; } - return null; + // Helper: extract major.minor.patch from a kernel version string + const parseKernel = (v: string): string | null => { + const m = v.match(/(\d+\.\d+\.\d+)/); + return m?.[1] ?? null; }; - // Source A: /proc/version (host kernel build, crosses container boundary) - let hostName: string | null = null; - try { - const raw = readFileSync('/proc/version', 'utf8').trim(); - const vm = raw.match(/^Linux version\s+(\S+)/); - if (vm) { - // Step 1: kernel release string — embedded distros embed their name - // here (e.g. "6.6.16-armbian", "6.1.60-dietpi"). More reliable than - // the GCC build tag, which often shows the cross-compilation toolchain - // (e.g. "Ubuntu" for Armbian / DietPi) rather than the actual OS. - const releaseStr = vm[1].toLowerCase(); - const releaseNameMatch = releaseStr.match(/(armbian|dietpi|libreelec|coreelec)/); - if (releaseNameMatch) { - const nameMap: Record = { - armbian: 'Armbian', - dietpi: 'DietPi', - libreelec: 'LibreELEC', - coreelec: 'CoreELEC', - }; - hostName = nameMap[releaseNameMatch[1]] ?? releaseNameMatch[1]; - } else { - // Step 2: GCC build tag — matches the distribution that compiled - // the running kernel (e.g. "(Ubuntu ...)", "(Debian ...)", - // "(Red Hat ...)"). - const dm = raw.match(/\b(Debian|Ubuntu|Red Hat|CentOS|Fedora|Alpine|Arch|Gentoo|SUSE|Proxmox|OpenWrt|Deepin|Kylin|openEuler|Anolis|UOS|Linux Mint|Slackware|Manjaro|NixOS|Void|Mageia|Kali|Amazon|Solus|Alibaba|Armbian|DietPi|Raspbian)\b/i); - hostName = dm ? dm[1] : null; - } - } - } catch { /* source A unavailable */ } + // ── Linux ────────────────────────────────────────────────────────── + if (os.platform() === 'linux') { + const kernelRelease = os.release(); + const kernelVer = parseKernel(kernelRelease); - // Source B: /etc/os-release (container / local OS) - let osReleaseName: string | null = null; - let osReleaseVer: string | null = null; - try { - for (const f of ['/etc/os-release', '/usr/lib/os-release']) { - if (!existsSync(f)) continue; - const raw = readFileSync(f, 'utf8'); - const get = (k: string) => { const m = raw.match(new RegExp(`^${k}=("?)(.+?)\\1$`, 'm')); return m?.[2] ?? null; }; - const pretty = get('PRETTY_NAME') || get('NAME'); - const ver = get('VERSION_ID'); - if (pretty) { - const nm = pretty.match(/^([^0-9]+)/); - osReleaseName = nm ? nm[1].trim() : pretty; - osReleaseVer = ver; - break; - } - } - } catch { /* source B unavailable */ } + // Normalize RHEL-family distro names before comparison. + // /proc/version typically shows "Red Hat" (GCC build tag) even on + // Rocky / Alma / Oracle Linux, while /etc/os-release carries the + // actual distro name. Treat the whole family as a single group so + // they are never considered "disagreeing". + const isRhelFamily = (name: string): boolean => + /^(red hat|centos|rocky|alma|oracle|scientific|anolis|tencentos|bclinux|opencloudos)/.test( + name, + ); - // Decide which source to trust for the distro name & version - let finalName: string; - let finalVer: string | null; + // Extract distro version from kernel release string. + // Distros embed their version in the kernel ABI / build tag: + // Debian: "6.8.12-1-deb13-amd64" → 13 + // RHEL family: "4.18.0-513.el9.x86_64" → 9 + // Fedora: "6.8.12-300.fc40.x86_64" → 40 + // Amazon Linux: "6.1.158-178.288.amzn2023" → 2023 + // Mageia: "6.8.12-1.mga10" → 10 + const kernelDistroVer = (distro: string | null): string | null => { + if (!distro) { + return null; + } + + const lr = kernelRelease.toLowerCase(); + const ld = distro.toLowerCase(); + + if (ld === 'debian') { + const m = lr.match(/deb(\d+)/); + + if (m) { + return m[1]; + } + } + + if (isRhelFamily(ld)) { + const m = lr.match(/el(\d+)/); + + if (m) { + return m[1]; + } + } + + if (ld === 'fedora') { + const m = lr.match(/fc(\d+)/); + + if (m) { + return m[1]; + } + } + + if (ld === 'amazon' || ld.includes('amazon')) { + const m = lr.match(/amzn(\d+)/); + + if (m) { + return m[1]; + } + } + + if (ld === 'mageia') { + const m = lr.match(/mga(\d+)/); + + if (m) { + return m[1]; + } + } + + if (ld === 'armbian') { + const m = lr.match(/armbian(\d+)/); + + if (m) { + return m[1]; + } + } + + if (ld === 'dietpi') { + const m = lr.match(/dietpi(\d+)/); + + if (m) { + return m[1]; + } + } + + if (ld.includes('libreelec')) { + const m = lr.match(/libreelec(\d+)/); + + if (m) { + return m[1]; + } + } + + if (ld.includes('coreelec')) { + const m = lr.match(/coreelec(\d+)/); + + if (m) { + return m[1]; + } + } + + return null; + }; + + // Source A: /proc/version (host kernel build, crosses container boundary) + let hostName: string | null = null; - if (hostName && osReleaseName) { - // Normalize and compare: e.g. "Debian" vs "Debian GNU/Linux" → match. - // RHEL family members (Red Hat, CentOS, Rocky, Alma, Oracle, Scientific) - // are normalised to the same group — /proc/version usually shows "Red Hat" - // (GCC build tag) even when the actual distro is Rocky / Alma / Oracle. - const a = hostName.toLowerCase(); - const b = osReleaseName.toLowerCase(); - if (a.includes(b) || b.includes(a) || (isRhelFamily(a) && isRhelFamily(b))) { - // Agree → prefer version from kernel release, fall back to os-release - finalName = osReleaseName; - finalVer = kernelDistroVer(hostName) ?? osReleaseVer; - } else { - // Disagree → host kernel build wins (crosses container boundary) - finalName = hostName; - finalVer = kernelDistroVer(hostName); - } - } else if (hostName) { - finalName = hostName; - finalVer = kernelDistroVer(hostName); - } else if (osReleaseName) { - finalName = osReleaseName; - finalVer = kernelDistroVer(osReleaseName) ?? osReleaseVer; - } else { - // Source C: legacy release files - for (const [path, prefix] of [ - ['/etc/alpine-release', 'Alpine Linux '], - ['/etc/redhat-release', ''], - ['/etc/debian_version', 'Debian '], - ] as [string, string][]) { try { - if (existsSync(path)) { - const raw = prefix + readFileSync(path, 'utf8').trim(); - return kernelVer ? `${raw} (kernel ${kernelVer})` : raw; - } - } catch { /* try next */ } - } - return kernelVer ? `Linux (kernel ${kernelVer})` : 'Linux'; + const raw = readFileSync('/proc/version', 'utf8').trim(); + const vm = raw.match(/^Linux version\s+(\S+)/); + + if (vm) { + // Step 1: kernel release string — embedded distros embed their name + // here (e.g. "6.6.16-armbian", "6.1.60-dietpi"). More reliable than + // the GCC build tag, which often shows the cross-compilation toolchain + // (e.g. "Ubuntu" for Armbian / DietPi) rather than the actual OS. + const releaseStr = vm[1].toLowerCase(); + const releaseNameMatch = releaseStr.match(/(armbian|dietpi|libreelec|coreelec)/); + + if (releaseNameMatch) { + const nameMap: Record = { + armbian: 'Armbian', + dietpi: 'DietPi', + libreelec: 'LibreELEC', + coreelec: 'CoreELEC', + }; + hostName = nameMap[releaseNameMatch[1]] ?? releaseNameMatch[1]; + } else { + // Step 2: GCC build tag — matches the distribution that compiled + // the running kernel (e.g. "(Ubuntu ...)", "(Debian ...)", + // "(Red Hat ...)"). + const dm = raw.match( + /\b(Debian|Ubuntu|Red Hat|CentOS|Fedora|Alpine|Arch|Gentoo|SUSE|Proxmox|OpenWrt|Deepin|Kylin|openEuler|Anolis|UOS|Linux Mint|Slackware|Manjaro|NixOS|Void|Mageia|Kali|Amazon|Solus|Alibaba|Armbian|DietPi|Raspbian)\b/i, + ); + hostName = dm ? dm[1] : null; + } + } + } catch { + /* source A unavailable */ + } + + // Source B: /etc/os-release (container / local OS) + let osReleaseName: string | null = null; + let osReleaseVer: string | null = null; + + try { + for (const f of ['/etc/os-release', '/usr/lib/os-release']) { + if (!existsSync(f)) { + continue; + } + + const raw = readFileSync(f, 'utf8'); + + const get = (k: string) => { + const m = raw.match(new RegExp(`^${k}=("?)(.+?)\\1$`, 'm')); + return m?.[2] ?? null; + }; + + const pretty = get('PRETTY_NAME') || get('NAME'); + const ver = get('VERSION_ID'); + + if (pretty) { + const nm = pretty.match(/^([^0-9]+)/); + osReleaseName = nm ? nm[1].trim() : pretty; + osReleaseVer = ver; + break; + } + } + } catch { + /* source B unavailable */ + } + + // Decide which source to trust for the distro name & version + let finalName: string; + let finalVer: string | null; + + if (hostName && osReleaseName) { + // Normalize and compare: e.g. "Debian" vs "Debian GNU/Linux" → match. + // RHEL family members (Red Hat, CentOS, Rocky, Alma, Oracle, Scientific) + // are normalised to the same group — /proc/version usually shows "Red Hat" + // (GCC build tag) even when the actual distro is Rocky / Alma / Oracle. + const a = hostName.toLowerCase(); + const b = osReleaseName.toLowerCase(); + + if (a.includes(b) || b.includes(a) || (isRhelFamily(a) && isRhelFamily(b))) { + // Agree → prefer version from kernel release, fall back to os-release + finalName = osReleaseName; + finalVer = kernelDistroVer(hostName) ?? osReleaseVer; + } else { + // Disagree → host kernel build wins (crosses container boundary) + finalName = hostName; + finalVer = kernelDistroVer(hostName); + } + } else if (hostName) { + finalName = hostName; + finalVer = kernelDistroVer(hostName); + } else if (osReleaseName) { + finalName = osReleaseName; + finalVer = kernelDistroVer(osReleaseName) ?? osReleaseVer; + } else { + // Source C: legacy release files + for (const [path, prefix] of [ + ['/etc/alpine-release', 'Alpine Linux '], + ['/etc/redhat-release', ''], + ['/etc/debian_version', 'Debian '], + ] as [string, string][]) { + try { + if (existsSync(path)) { + const raw = prefix + readFileSync(path, 'utf8').trim(); + return kernelVer ? `${raw} (kernel ${kernelVer})` : raw; + } + } catch { + /* try next */ + } + } + + return kernelVer ? `Linux (kernel ${kernelVer})` : 'Linux'; + } + + // Unified output: (kernel ) + const base = finalVer ? `${finalName} ${finalVer}` : finalName; + return kernelVer ? `${base} (kernel ${kernelVer})` : base; } - // Unified output: (kernel ) - const base = finalVer ? `${finalName} ${finalVer}` : finalName; - return kernelVer ? `${base} (kernel ${kernelVer})` : base; - } + // ── Windows ──────────────────────────────────────────────────────── + if (os.platform() === 'win32') { + try { + const productName = execSync( + 'reg query "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" /v ProductName', + { encoding: 'utf8', timeout: 3000, stdio: 'pipe' }, + ); + const m = productName.match(/ProductName\s+REG_SZ\s+(.+)/); + let name = m ? m[1].trim() : `Windows ${os.release()}`; - // ── Windows ──────────────────────────────────────────────────────── - if (os.platform() === 'win32') { - try { - const productName = execSync( - 'reg query "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" /v ProductName', - { encoding: 'utf8', timeout: 3000, stdio: 'pipe' }, - ); - const m = productName.match(/ProductName\s+REG_SZ\s+(.+)/); - let name = m ? m[1].trim() : `Windows ${os.release()}`; - // ProductName is still "Windows 10 Pro" on Windows 11 — check build number. - try { - const buildOut = execSync( - 'reg query "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" /v CurrentBuildNumber', - { encoding: 'utf8', timeout: 3000, stdio: 'pipe' }, - ); - const bm = buildOut.match(/CurrentBuildNumber\s+REG_SZ\s+(\d+)/); - if (bm && parseInt(bm[1], 10) >= 22000) { - name = name.replace(/^Windows 10/, 'Windows 11'); + // ProductName is still "Windows 10 Pro" on Windows 11 — check build number. + try { + const buildOut = execSync( + 'reg query "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion" /v CurrentBuildNumber', + { encoding: 'utf8', timeout: 3000, stdio: 'pipe' }, + ); + const bm = buildOut.match(/CurrentBuildNumber\s+REG_SZ\s+(\d+)/); + + if (bm && parseInt(bm[1], 10) >= 22000) { + name = name.replace(/^Windows 10/, 'Windows 11'); + } + } catch { + /* keep name as-is */ + } + + return name; + } catch { + /* fall through */ } - } catch { /* keep name as-is */ } - return name; - } catch { /* fall through */ } - return `Windows ${os.release()}`; - } - return os.platform(); + return `Windows ${os.release()}`; + } + + return os.platform(); } function normalizeArch(arch: string): string { - const map: Record = { - loong64: 'LoongArch', - riscv64: 'RISC-V', - mips: 'MIPS', - mipsel: 'MIPS (LE)', - arm: 'ARM', - arm64: 'ARM64', - x64: 'x86_64', - ia32: 'x86', - s390: 'S/390', - s390x: 'S/390x', - ppc: 'PowerPC', - ppc64: 'PowerPC64', - ppc64le: 'PowerPC64 (LE)', - }; - return map[arch] ?? arch; + const map: Record = { + loong64: 'LoongArch', + riscv64: 'RISC-V', + mips: 'MIPS', + mipsel: 'MIPS (LE)', + arm: 'ARM', + arm64: 'ARM64', + x64: 'x86_64', + ia32: 'x86', + s390: 'S/390', + s390x: 'S/390x', + ppc: 'PowerPC', + ppc64: 'PowerPC64', + ppc64le: 'PowerPC64 (LE)', + }; + return map[arch] ?? arch; } -const CACHED_DISTRO = (() => { try { return detectDistro(); } catch { return os.platform(); } })(); +const CACHED_DISTRO = (() => { + try { + return detectDistro(); + } catch { + return os.platform(); + } +})(); const CACHED_ARCH_LABEL = normalizeArch(os.arch()); export async function initWebUI( - desiredPort: number = 5099, - oneBotManager: OneBotManager, - hookManager?: HookManager, - notificationManager?: NotificationManager, - listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: StateBus } = {}, + desiredPort: number = 5099, + oneBotManager: OneBotManager, + hookManager?: HookManager, + notificationManager?: NotificationManager, + listener: { + host?: string; + tlsEnabled?: boolean; + trustProxy?: string; + stateBus?: StateBus; + } = {}, ): Promise<{ port: number; stop: () => Promise }> { - const host = listener.host || '127.0.0.1'; - const tlsEnabled = listener.tlsEnabled === true; - const bootCheck = checkListenerExposure({ - webuiHost: host, - tlsEnabled, - pairOk: resolveTlsContext('config').ok, - }); - if (!bootCheck.ok) { - const reason = bootCheck.code === 'invalid-bind-host' - ? `bind host is not a valid TCP address: ${host}` - : 'TLS is enabled but the certificate/private-key pair is unusable'; - throw new Error(`WebUI listener cannot start: ${reason}`); - } - // 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); - // Security decisions must not silently turn an unreadable socket peer into - // localhost. The regular resolver keeps its compatibility fallback for - // rate-limit bucketing; this resolver fails closed with an empty address. - const getSecurityClientIp = makeClientIpResolver(trustProxyMode, ''); - - // Connection-status diff loop: OneBot adapters don't emit events for - // listening/connected/client-count changes, so we poll the snapshot at - // 500ms and publish 'connections' to the StateBus when it actually - // moves. One loop per server lifetime, lives until process exit (the - // setInterval is .unref'd inside the loop so it doesn't pin the event - // loop on shutdown). - // - // `pickComparable` strips `adapter.detail` — that's a localised human - // string assembled with HH:MM:SS timestamps from the last webhook - // delivery; including it in the diff would make every webhook event - // produce a publish (defeating the diff). We compare name + kind + status, - // plus the structured `lastErrorAt`: a new apply failure must refresh its - // error/time even when the adapter was already degraded. The SSE handler - // still ships the FULL snapshot (with `detail` and `lastError`) — it's only - // the diff key that's pruned. - // - // Trade-off: the rendered detail string (e.g. "3 个客户端", "上次推送 - // 14:53:01") only refreshes on the next SSE push or on the 30s REST - // reconcile — not in real time. The user's original reported bugs were - // about process / account edges (which DO push instantly); refreshing - // adapter detail strings at sub-second cadence wasn't required. If it - // becomes one, surface client-count as a structured field on - // AdapterStatus and include it in the comparable. - let connectionDiffLoop: ReturnType | undefined; - if (listener.stateBus) { - connectionDiffLoop = startConnectionDiffLoop({ - bus: listener.stateBus, - getSnapshot: () => oneBotManager.getConnectionStatuses(), - pickComparable: comparableConnectionSnapshot, - intervalMs: 500, + const host = listener.host || '127.0.0.1'; + const tlsEnabled = listener.tlsEnabled === true; + const bootCheck = checkListenerExposure({ + webuiHost: host, + tlsEnabled, + pairOk: resolveTlsContext('config').ok, }); - } - // 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()) { - log.warn('dev mode enabled with the configured development credential'); - log.warn('dev mode skips config/webui.json and password rotation'); - } else if (initialPassword) { - log.info('════════════════════════════════════════════════════════════════'); - log.info(' ★ WebUI 初始登录凭据 / Initial WebUI Credentials ★'); - log.info(' 请立即登录并修改密码 —— 关闭程序后此密码无法找回。'); - log.info(' 若跳过初始改密,下次启动将自动生成新的随机密码。'); - log.info(' Log in and change the password now; it will not be shown again.'); - log.info('────────────────────────────────────────────────────────────────'); - logInitialWebuiCredentials(initialPassword); - log.info('════════════════════════════════════════════════════════════════'); - } else if (auth.mustChangePassword()) { - log.warn('password change is still required'); - } - log.info('login rate-limit keyed by: %s', describeTrustProxy(trustProxyMode)); - if (trustProxyMode.kind === 'all') { - log.warn('SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For'); - } - - // Memoized once at startup (agreements version is fixed per process; a text - // change ships with a redeploy that restarts us). Flipped to false the moment - // consent is recorded, so the middleware never touches disk per request. - const environmentConsent = resolveEnvironmentConsent(); - let consentGatePending = isConsentRequired(); - if (environmentConsent.accepted) { - log.info( - 'EULA/PRIVACY consent supplied by %s and %s (agreements version=%s)', - EULA_ACCEPT_ENV, - PRIVACY_ACCEPT_ENV, - loadAgreements().version, - ); - } else if (environmentConsent.eulaAccepted || environmentConsent.privacyAccepted) { - log.warn( - 'partial environment consent ignored; set both %s=1 and %s=1 to accept the agreements', - EULA_ACCEPT_ENV, - PRIVACY_ACCEPT_ENV, - ); - } else if (consentGatePending) { - log.info('awaiting EULA/PRIVACY consent before the panel unlocks'); - } - - const app = new Hono(); - app.use('*', webuiSecurityHeaders); - registerLoginRequestSecurity(app); - const storageManagement = new StorageManagementService({ - dataDir: 'data', - getLogStatus: getLogStorageStatus, - clearLogs: clearManagedLogs, - temporary: { - snapshot: snapshotStreamStorage, - clearInactive: clearInactiveStreamStorage, - }, - // Connection statuses include active and still-retiring generations. - // A retiring instance may still hold SQLite handles after disappearing - // from getInstances(), so it must continue to block destructive cleanup. - listOnlineAccounts: () => oneBotManager.getConnectionStatuses() - .map((account) => ({ uin: account.uin, nickname: account.nickname })), - }); - const logStorageSettings = new LogStorageSettingsManager({ - readPersisted: readRuntimeConfig, - readEnvOverrides: () => resolveRuntimeEnvOverrides(process.env), - readEffective: getLogStorageStatus, - persist: updateRuntimeConfig, - apply: configureFileTransport, - }); - - // ─── Anti-indexing ─────────────────────────────────────────────────────── - // The WebUI is an admin surface that has no business showing up in - // search results — even the login page leaks the existence of a - // SnowLuma instance to anyone scanning the IP. Three overlapping - // signals: a hard X-Robots-Tag on every response, a robots.txt for - // crawlers that read it before pages, and a in the - // SPA shell for the case where a proxy strips headers. - app.use('*', async (c, next) => { - await next(); - c.res.headers.set( - 'X-Robots-Tag', - 'noindex, nofollow, noarchive, nosnippet, noimageindex', - ); - }); - - app.get('/robots.txt', (c) => { - c.res.headers.set('Content-Type', 'text/plain; charset=utf-8'); - return c.body('User-agent: *\nDisallow: /\n'); - }); - - // ─── Auth middleware ───────────────────────────────────────────────────── - app.use('/api/*', async (c, next) => { - const reqPath = c.req.path; - // `/api/ui/public` serves the cosmetic appearance subset to the - // pre-auth login page, so it must skip the bearer check. It exposes - // nothing sensitive (no layout, no secrets) — see ui-config.ts. - if (reqPath === '/api/login' || reqPath === '/api/ui/public') return next(); - - const token = extractBearerToken(c.req.raw); - if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401); - - const info = sessionTokens.get(token); - if (!info || Date.now() > info.expiresAt) { - return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401); + if (!bootCheck.ok) { + const reason = + bootCheck.code === 'invalid-bind-host' + ? `bind host is not a valid TCP address: ${host}` + : 'TLS is enabled but the certificate/private-key pair is unusable'; + throw new Error(`WebUI listener cannot start: ${reason}`); } - // Consent gate (before the password gate): block everything outside the - // consent allowlist until the operator has accepted the current agreements. - // `consentGatePending` is memoized (see below) so this is a Set lookup, not - // a disk read, on the hot path. - if (consentGatePending && !CONSENT_ALLOWLIST.has(reqPath)) { - return c.json( - { status: 'failed', message: '请先阅读并同意用户协议与隐私政策', consentRequired: true }, - 403, - ); + // 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); + // Security decisions must not silently turn an unreadable socket peer into + // localhost. The regular resolver keeps its compatibility fallback for + // rate-limit bucketing; this resolver fails closed with an empty address. + const getSecurityClientIp = makeClientIpResolver(trustProxyMode, ''); + + // Connection-status diff loop: OneBot adapters don't emit events for + // listening/connected/client-count changes, so we poll the snapshot at + // 500ms and publish 'connections' to the StateBus when it actually + // moves. One loop per server lifetime, lives until process exit (the + // setInterval is .unref'd inside the loop so it doesn't pin the event + // loop on shutdown). + // + // `pickComparable` strips `adapter.detail` — that's a localised human + // string assembled with HH:MM:SS timestamps from the last webhook + // delivery; including it in the diff would make every webhook event + // produce a publish (defeating the diff). We compare name + kind + status, + // plus the structured `lastErrorAt`: a new apply failure must refresh its + // error/time even when the adapter was already degraded. The SSE handler + // still ships the FULL snapshot (with `detail` and `lastError`) — it's only + // the diff key that's pruned. + // + // Trade-off: the rendered detail string (e.g. "3 个客户端", "上次推送 + // 14:53:01") only refreshes on the next SSE push or on the 30s REST + // reconcile — not in real time. The user's original reported bugs were + // about process / account edges (which DO push instantly); refreshing + // adapter detail strings at sub-second cadence wasn't required. If it + // becomes one, surface client-count as a structured field on + // AdapterStatus and include it in the comparable. + let connectionDiffLoop: ReturnType | undefined; + + if (listener.stateBus) { + connectionDiffLoop = startConnectionDiffLoop({ + bus: listener.stateBus, + getSnapshot: () => oneBotManager.getConnectionStatuses(), + pickComparable: comparableConnectionSnapshot, + intervalMs: 500, + }); } - if (info.mustChangePassword && !MUST_CHANGE_ALLOWLIST.has(reqPath)) { - return c.json({ status: 'failed', message: '请先修改密码', mustChangePassword: true }, 403); + // 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()) { + log.warn('dev mode enabled with the configured development credential'); + log.warn('dev mode skips config/webui.json and password rotation'); + } else if (initialPassword) { + log.info('════════════════════════════════════════════════════════════════'); + log.info(' ★ WebUI 初始登录凭据 / Initial WebUI Credentials ★'); + log.info(' 请立即登录并修改密码 —— 关闭程序后此密码无法找回。'); + log.info(' 若跳过初始改密,下次启动将自动生成新的随机密码。'); + log.info(' Log in and change the password now; it will not be shown again.'); + log.info('────────────────────────────────────────────────────────────────'); + logInitialWebuiCredentials(initialPassword); + log.info('════════════════════════════════════════════════════════════════'); + } else if (auth.mustChangePassword()) { + log.warn('password change is still required'); } - c.set('sessionToken' as never, token); - c.res = await traceAuthenticatedWebuiMutation(c.req.raw, async () => { - await next(); - return c.res; - }); - }); + log.info('login rate-limit keyed by: %s', describeTrustProxy(trustProxyMode)); - // Periodic janitor — keeps sessionTokens / loginAttempts from growing - // unbounded and replaces the per-request O(n) sweep we used to do. - const tokenJanitor = setInterval(purgeExpiredTokens, 60_000); - tokenJanitor.unref?.(); - - // ─── Login ─────────────────────────────────────────────────────────────── - app.post('/api/login', async (c) => { - const ip = getClientIp(c); - const now = Date.now(); - const attempt = loginAttempts.get(ip); - if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) { - const waitSec = Math.ceil((attempt.resetAt - now) / 1000); - return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429); - } - - let body: unknown; - try { - body = await c.req.json(); - } catch { - return c.json({ success: false, message: '请求格式错误' }, 400); - } - - const result = completeWebuiLogin(auth, body, now); - if (result.kind === 'bad-request') { - return c.json({ success: false, message: '请求格式错误' }, 400); - } - if (result.kind === 'bad-password' || result.kind === 'bad-second-factor') { - const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS }; - current.count += 1; - if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS; - loginAttempts.set(ip, current); - const message = result.kind === 'bad-second-factor' ? '验证码不正确' : '密码错误'; - return c.json({ success: false, message }, 401); - } - if (result.kind === 'needs-totp') { - return c.json({ success: false, needsTotp: true }); - } - - loginAttempts.delete(ip); - if (result.totpState) { - try { - auth.persistTotp(result.totpState); - } catch (err) { - log.warn('persist totp after login failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '登录失败' }, 500); - } - } - const token = randomBytes(32).toString('hex'); - sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: result.mustChangePassword }); - setAvatarSessionCookie(c, token, listener.tlsEnabled === true); - return c.json({ success: true, token, mustChangePassword: result.mustChangePassword }); - }); - - app.post('/api/logout', (c) => { - const token = c.get('sessionToken' as never) as string | undefined; - if (token) sessionTokens.delete(token); - clearAvatarSessionCookie(c, listener.tlsEnabled === true); - return c.json({ success: true }); - }); - - app.get('/api/auth/state', (c) => { - const token = c.get('sessionToken' as never) as string | undefined; - const info = token ? sessionTokens.get(token) : undefined; - return c.json({ - mustChangePassword: info?.mustChangePassword ?? auth.mustChangePassword(), - }); - }); - - app.post('/api/auth/check-strength', async (c) => { - let body: { password?: unknown }; - try { - body = await c.req.json(); - } catch { - return c.json({ rules: evaluatePasswordRules(''), valid: false }); - } - const pwd = typeof body.password === 'string' ? body.password : ''; - return c.json({ rules: evaluatePasswordRules(pwd), valid: isStrongPassword(pwd) }); - }); - - app.post('/api/auth/change-password', async (c) => { - let body: { oldPassword?: unknown; newPassword?: unknown }; - try { - body = await c.req.json(); - } catch { - return c.json({ success: false, message: '请求格式错误' }, 400); - } - const oldPassword = typeof body.oldPassword === 'string' ? body.oldPassword : ''; - const newPassword = typeof body.newPassword === 'string' ? body.newPassword : ''; - if (!auth.verify(oldPassword)) { - return c.json({ success: false, message: '当前密码不正确' }, 401); - } - if (!isStrongPassword(newPassword)) { - return c.json( - { success: false, message: '新密码不符合强度要求', rules: evaluatePasswordRules(newPassword) }, - 400, - ); - } - if (oldPassword === newPassword) { - return c.json({ success: false, message: '新密码不得与旧密码相同' }, 400); - } - try { - auth.setPassword(newPassword, oldPassword); - } catch (err) { - log.warn('change password failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '密码修改失败' }, 400); - } - // Invalidate every session, including the current one. If the old - // password was compromised, the attacker may already hold the current - // token; rotating credentials must rotate sessions too. - sessionTokens.clear(); - clearAvatarSessionCookie(c, listener.tlsEnabled === true); - log.info('password updated; all sessions invalidated'); - return c.json({ success: true, requireRelogin: true }); - }); - - const totpDisabledInDev = () => auth.isDevMode(); - - app.get('/api/auth/totp', (c) => { - if (totpDisabledInDev()) { - return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); - } - return c.json(auth.totpStatus()); - }); - - app.post('/api/auth/totp/begin', async (c) => { - if (totpDisabledInDev()) { - return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); - } - if (auth.totpEnabled()) { - return c.json({ success: false, message: '2FA 已开启' }, 409); - } - const token = c.get('sessionToken' as never) as string; - let body: Record = {}; - try { - const parsed = await c.req.json(); - if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { - body = parsed as Record; - } - } catch { - body = {}; - } - const issuer = sanitizeTotpLabelPart(body.issuer, DEFAULT_TOTP_ISSUER); - const accountName = sanitizeTotpLabelPart(body.accountName, defaultTotpAccountName()); - const now = Date.now(); - const existing = totpEnrollments.get(token); - const secret = existing && existing.expiresAt > now ? existing.secret : undefined; - const enrollment = beginTotpEnrollment({ issuer, accountName, secret }); - totpEnrollments.set(token, { - secret: enrollment.secret, - issuer, - accountName, - expiresAt: now + TOTP_ENROLL_TTL_MS, - }); - return c.json({ - success: true, - secret: enrollment.secret, - otpauthUrl: enrollment.otpauthUrl, - issuer: enrollment.issuer, - accountName: enrollment.accountName, - }); - }); - - app.post('/api/auth/totp/confirm', async (c) => { - if (totpDisabledInDev()) { - return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); - } - if (auth.totpEnabled()) { - return c.json({ success: false, message: '2FA 已开启' }, 409); - } - const token = c.get('sessionToken' as never) as string; - let body: { password?: unknown; code?: unknown }; - try { - body = await c.req.json(); - } catch { - return c.json({ success: false, message: '请求格式错误' }, 400); - } - const password = typeof body.password === 'string' ? body.password : ''; - const code = typeof body.code === 'string' ? body.code : ''; - if (!auth.verify(password)) { - return c.json({ success: false, message: '当前密码不正确' }, 401); - } - const pending = totpEnrollments.get(token); - if (!pending || pending.expiresAt <= Date.now()) { - totpEnrollments.delete(token); - return c.json({ success: false, message: '请先开始绑定' }, 400); - } - try { - const enabled = confirmTotpEnrollment({ - password, - secret: pending.secret, - code, - label: `${pending.issuer} (${pending.accountName})`, - atMs: Date.now(), - }); - auth.persistTotp(enabled.state); - totpEnrollments.delete(token); - invalidateOtherSessions(sessionTokens, token); - log.info('webui 2FA enabled; other sessions invalidated'); - return c.json({ success: true, recoveryCodes: enabled.recoveryCodes }); - } catch (err) { - log.warn('totp confirm failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '验证码不正确' }, 401); - } - }); - - app.post('/api/auth/totp/disable', async (c) => { - if (totpDisabledInDev()) { - return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); - } - if (!auth.totpEnabled()) { - return c.json({ success: false, message: '2FA 未开启' }, 400); - } - const token = c.get('sessionToken' as never) as string; - let body: { password?: unknown; totp?: unknown; recoveryCode?: unknown }; - try { - body = await c.req.json(); - } catch { - return c.json({ success: false, message: '请求格式错误' }, 400); - } - const password = typeof body.password === 'string' ? body.password : ''; - if (!auth.verify(password)) { - return c.json({ success: false, message: '当前密码不正确' }, 401); - } - const decision = decideSecondFactorLogin({ - totpEnabled: true, - state: auth.totpState(), - password, - totp: typeof body.totp === 'string' ? body.totp : undefined, - recoveryCode: typeof body.recoveryCode === 'string' ? body.recoveryCode : undefined, - atMs: Date.now(), - }); - if (decision.kind !== 'ok') { - return c.json({ success: false, message: '验证码不正确' }, 401); - } - auth.persistTotp(undefined); - totpEnrollments.delete(token); - invalidateOtherSessions(sessionTokens, token); - log.info('webui 2FA disabled; other sessions invalidated'); - return c.json({ success: true }); - }); - - app.post('/api/auth/totp/recovery-codes', async (c) => { - if (totpDisabledInDev()) { - return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); - } - const state = auth.totpState(); - if (!state) { - return c.json({ success: false, message: '2FA 未开启' }, 400); - } - let body: { password?: unknown; totp?: unknown }; - try { - body = await c.req.json(); - } catch { - return c.json({ success: false, message: '请求格式错误' }, 400); - } - const password = typeof body.password === 'string' ? body.password : ''; - const totp = typeof body.totp === 'string' ? body.totp : ''; - if (!auth.verify(password)) { - return c.json({ success: false, message: '当前密码不正确' }, 401); - } - try { - const next = regenerateRecoveryCodes({ - password, - state, - totp, - atMs: Date.now(), - }); - auth.persistTotp(next.state); - log.info('webui 2FA recovery codes regenerated'); - return c.json({ success: true, recoveryCodes: next.recoveryCodes }); - } catch (err) { - log.warn('totp recovery regenerate failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '验证码不正确' }, 401); - } - }); - - // ─── EULA / PRIVACY consent ────────────────────────────────────────────── - // Both are bearer-gated (consent is collected AFTER login) and live in the - // consent + must-change allowlists so they're reachable during onboarding. - // The version is content-derived, so consent is stable across app upgrades - // and re-prompted only when the agreement text itself changes. - app.get('/api/agreements', (c) => c.json(getAgreementsPayload())); - - app.post('/api/agreements/record-consent', async (c) => { - let body: { version?: unknown }; - try { - body = await c.req.json(); - } catch { - return c.json({ success: false, message: '请求格式错误' }, 400); - } - const version = typeof body.version === 'string' ? body.version : ''; - const current = loadAgreements().version; - // Reject a stale/blank version so a client that read an older agreement set - // can't record consent that the server would then treat as current. - if (!version || version !== current) { - return c.json( - { success: false, message: '协议版本已更新,请刷新后重新确认', currentVersion: current }, - 409, - ); - } - try { - recordConsent(version); - } catch (err) { - log.warn('record consent failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500); - } - consentGatePending = false; // unlock the rest of the API for this process - log.info('agreements consent recorded (version=%s)', version); - return c.json({ success: true, version }); - }); - - // ─── Avatar proxy (uin validated) ──────────────────────────────────────── - app.get('/avatar/:uin', async (c) => { - const sessionToken = readAvatarSessionToken(c); - const session = sessionTokens.get(sessionToken); - if (!session || Date.now() > session.expiresAt) { - if (sessionToken) sessionTokens.delete(sessionToken); - return c.text('unauthorized', 401); - } - const uin = c.req.param('uin'); - if (!UIN_REGEX.test(uin)) return c.text('invalid uin', 400); - - const now = Date.now(); - let cached = avatarCache.get(uin); - if (!cached || cached.expiresAt <= now) { - try { - const avatar = await fetchQqAvatar(uin); - cached = { ...avatar, expiresAt: now + AVATAR_CACHE_TTL_MS }; - avatarCache.set(uin, cached); - } catch (err) { - log.warn('failed to proxy avatar for UIN %s: %s', uin, err instanceof Error ? err.message : String(err)); - if (!cached) return c.text('avatar unavailable', 502); - } - } - return new Response(cached.body, { - headers: { - 'Content-Type': cached.contentType, - 'Cache-Control': `private, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`, - Vary: 'Cookie', - }, - }); - }); - - // ─── Background image (unauth, like /avatar) ───────────────────────────── - // The login page needs to render the operator's background before auth, so - // this route is intentionally public. It only serves a file the operator - // themselves uploaded. Cache-busting is via the `?v=` version the client - // appends; the bytes for a given version are immutable. - app.get('/ui-asset/background', (c) => { - const asset = readBackgroundImage(); - if (!asset) return c.text('no background', 404); - return new Response(new Uint8Array(asset.bytes), { - headers: { - 'Content-Type': asset.mime, - 'Cache-Control': 'public, max-age=31536000, immutable', - // Defence-in-depth: never let an uploaded blob be interpreted as - // anything but the sniffed image type. - 'X-Content-Type-Options': 'nosniff', - }, - }); - }); - - // ─── Read-only API ─────────────────────────────────────────────────────── - app.get('/api/status', (c) => { - // Refresh the path-scoped avatar cookie for a still-valid localStorage - // session (for example after upgrading from a version without the cookie). - const token = c.get('sessionToken' as never) as string; - setAvatarSessionCookie(c, token, listener.tlsEnabled === true); - return c.json({ status: 'running' }); - }); - - // Advisory update check — compares the running build against the latest - // GitHub stable release and links the user to it. Read-only: SnowLuma - // never downloads or applies the update itself. `?force=1` bypasses the - // server-side cache (the "立即检查" button). Never errors out — a failed - // check returns `{ hasUpdate: false, error }` and the UI degrades quietly. - app.get('/api/update/check', async (c) => { - const force = c.req.query('force') === 'true' || c.req.query('force') === '1'; - return c.json(await getUpdateInfo(force)); - }); - - let lastCpuTimes: { idle: number; total: number }[] | null = null; - function sampleCpuLoad(): number[] { - const cpus = os.cpus(); - const current = cpus.map((cpu) => { - const t = cpu.times; - const total = t.user + t.nice + t.sys + t.idle + t.irq; - return { idle: t.idle, total }; - }); - if (!lastCpuTimes || lastCpuTimes.length !== current.length) { - lastCpuTimes = current; - return current.map(() => 0); - } - const usage = current.map((cur, i) => { - const prev = lastCpuTimes![i]; - const totalDiff = cur.total - prev.total; - const idleDiff = cur.idle - prev.idle; - if (totalDiff <= 0) return 0; - return Math.max(0, Math.min(100, ((totalDiff - idleDiff) / totalDiff) * 100)); - }); - lastCpuTimes = current; - return usage; - } - - app.get('/api/system', (c) => { - const cpus = os.cpus(); - const usage = sampleCpuLoad(); - const totalMem = os.totalmem(); - const freeMem = os.freemem(); - const usedMem = totalMem - freeMem; - const runtimeMemory = process.memoryUsage(); - return c.json({ - hostname: os.hostname(), - platform: os.platform(), - arch: os.arch(), - archLabel: CACHED_ARCH_LABEL, - release: os.release(), - distro: CACHED_DISTRO, - uptime: os.uptime(), - processUptime: process.uptime(), - nodeVersion: process.version, - cpu: { - model: cpus[0]?.model ?? 'unknown', - cores: cpus.length, - speedMHz: cpus[0]?.speed ?? 0, - loadAvg: os.loadavg(), - perCore: usage, - average: usage.length ? usage.reduce((s, v) => s + v, 0) / usage.length : 0, - }, - memory: { - total: totalMem, - free: freeMem, - used: usedMem, - usagePercent: totalMem ? (usedMem / totalMem) * 100 : 0, - }, - runtime: { - pid: process.pid, - rss: runtimeMemory.rss, - heapTotal: runtimeMemory.heapTotal, - heapUsed: runtimeMemory.heapUsed, - external: runtimeMemory.external, - arrayBuffers: runtimeMemory.arrayBuffers, - }, - }); - }); - - // ── 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); - const evaluated = evaluateSettingsSave( - readRuntimeConfig(), - coerced.patch, - resolveTlsContext('config').ok, - ); - if (!evaluated.ok) return c.json({ success: false, message: evaluated.error }, 400); - const saved = updateRuntimeConfig(evaluated.patch); - return c.json({ - success: true, - settings: { - webuiPort: saved.webuiPort, - webuiHost: saved.webuiHost, - tlsEnabled: saved.webuiTls?.enabled ?? false, - trustProxy: saved.trustProxy ?? '', - }, - restartRequiredToApply: true, - }); - }); - - registerStorageRoutes(app, { - storage: storageManagement, - settings: logStorageSettings, - audit: (event) => { - log.info( - 'storage cleanup scope=%s accountScope=%s category=%s uin=%s deletedFiles=%d freedBytes=%d failures=%d', - event.scope, - event.accountScope, - event.category ?? '-', - event.uin ?? '-', - event.deletedFiles, - event.freedBytes, - event.failureCount, - ); - }, - reportError: (operation, error) => { - log.error( - '%s failed: %s', - operation, - error instanceof Error ? (error.stack ?? error.message) : String(error), - ); - }, - }); - - 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) => { - if (tlsCertDeletionBlocked(readRuntimeConfig().webuiTls?.enabled === true)) { - return c.json({ success: false, message: '请先关闭 TLS 再删除证书' }, 400); - } - 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) ── - app.get('/api/system/backup/export', (c) => { - try { - const includeCredentials = c.req.query('credentials') === '1'; - const ts = new Date().toISOString(); - const bundle = buildBackup( - (name) => readBackupConfigFile('config', name), - listPerUinOneBotConfigFiles('config'), - { 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); - } catch (error) { - log.error('backup export failed: %s', error instanceof Error ? error.stack ?? error.message : String(error)); - return c.json({ success: false, message: '导出失败,请检查服务器日志' }, 500); - } - }); - - 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 }; - try { - const result = restoreBackup(backup, { - configDir: 'config', - restoreCredentials: restoreCredentials === true, - }); - return c.json({ success: true, ...result }); - } catch (err) { - if (err instanceof RestoreTransactionError) { - const failure = describeRestoreFailure(err); - return c.json(failure.body, failure.status); - } - log.error('backup import failed unexpectedly: %s', err instanceof Error ? err.stack ?? err.message : String(err)); - return c.json({ success: false, message: '恢复遇到未预期错误,请检查服务器日志' }, 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); - }); - - // Invoke a Stream API action (or any action) and relay every frame to the - // browser over an SSE body. The frontend reads this with fetch()+a stream - // reader (Bearer auth in the header), so — unlike /api/debug/stream — it does - // NOT need a query-token allowlist entry. Frames are never dropped. - app.post('/api/debug/invoke-stream', async (c) => { - let body: unknown; - try { body = await c.req.json(); } catch { return c.json({ status: 'failed', message: '请求格式错误' }, 400); } - const { uin, action, params } = (body ?? {}) as { uin?: unknown; action?: unknown; params?: unknown }; - if (typeof uin !== 'string' || !UIN_REGEX.test(uin)) return c.json({ status: 'failed', message: '无效的账号' }, 400); - if (typeof action !== 'string' || !action) return c.json({ status: 'failed', message: 'action 必填' }, 400); - if (params !== undefined && (typeof params !== 'object' || params === null || Array.isArray(params))) { - return c.json({ status: 'failed', message: 'params 必须是对象' }, 400); - } - const inst = oneBotManager.getInstance(uin); - if (!inst) return c.json({ status: 'failed', message: '账号不在线' }, 404); - const rawRequest = JSON.stringify({ action, params: params ?? {} }); - return buildStreamInvokeResponse( - (rq, emit, alive) => inst.invokeStream(rq, emit, alive), - rawRequest, - c.req.raw.signal, - ); - }); - - // Stream a browser-selected file to a temp path on THIS server (the bot runs - // here, not on the operator's machine), so the returned path can be fed to a - // send action's file/image/record/video param. Raw bytes in the body, - // `?filename=` for a human-readable suffix; streamed to disk with a byte cap. - app.post('/api/debug/upload', async (c) => { - try { - const result = await streamUploadToDisk(c.req.raw.body as ReadableStream | null, c.req.query('filename')); - return c.json({ status: 'ok', path: result.path, size: result.size }); - } catch (err) { - return c.json({ status: 'failed', message: err instanceof Error ? err.message : '上传失败' }, 400); - } - }); - - // Live merged SSE of OneBot events + action calls across all accounts. Taps - // are attached only while a client is connected (on-demand). A slow client is - // dropped (not back-pressured onto the bot) with a periodic drop marker. - app.get('/api/debug/stream', (c) => sseResponse(c, (ch) => { - // Drop-under-backpressure framing (unit-tested in debug-stream.ts). - const pushFrame = createFramePusher({ - desiredSize: ch.desiredSize, - enqueue: ch.raw, - encode: ch.encode, - }); - const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); }; - send({ kind: 'ready' }); - for (const inst of oneBotManager.getInstances()) { - const uin = inst.uin; - ch.onClose(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event }))); - ch.onClose(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec }))); - } - })); - - app.get('/api/qq-list', (c) => { - const instances = oneBotManager.getInstances(); - const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname })); - return c.json({ list }); - }); - - // Live OneBot adapter health per account (listening / connected / client - // counts / last-delivery), powering the dashboard's connection card. - app.get('/api/connections', (c) => { - return c.json({ list: oneBotManager.getConnectionStatuses() }); - }); - - // Combined SSE feed for the dashboard's three live resources — processes, - // qq-list, connections. Replaces the 3s REST polling tick in - // app-layout.tsx; the REST endpoints above stay for the initial fetch - // before SSE connects and for the slow (30s) reconciliation fallback. - // - // On connect: one frame per resource with the current snapshot. After - // that: a fresh snapshot per resource only when the StateBus signals a - // change (HookSession status-changed, BridgeManager session edges, the - // connection-status diff loop). 50ms per-resource debounce coalesces a - // burst (e.g. multiple HookSessions flipping status simultaneously). - const stateBus = listener.stateBus; - app.get('/api/state/stream', (c) => { - if (!stateBus) { - // Build without state-wiring (e.g. a future headless mode) — clients - // fall back to the REST endpoints. Treat as endpoint-not-here. - return c.text('state stream not configured', 503); - } - const liveBus = stateBus; - return sseResponse(c, (ch) => { - const pushFrame = createFramePusher({ - desiredSize: ch.desiredSize, - enqueue: ch.raw, - encode: ch.encode, - }); - const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); }; - send({ kind: 'ready' }); - - const handle = bindStateStream({ - bus: liveBus, - snapshot: async (resource: StateResource): Promise => { - if (resource === 'processes') { - if (!hookManager) return []; - return hookManager.listProcesses(); - } - if (resource === 'qq-list') { - return oneBotManager.getInstances().map((inst) => ({ uin: inst.uin, nickname: inst.nickname })); - } - return oneBotManager.getConnectionStatuses(); - }, - send: (frame) => send(frame), - debounceMs: 50, - }); - ch.onClose(() => handle.dispose()); - // Prime with the initial snapshot; if the client never sees the - // bus publish (idle system) it still has the current state. - void handle.sendAllInitial(); - }); - }); - - app.get('/api/logs', (c) => { - const limit = Number(c.req.query('limit') ?? 300); - return c.json({ list: getRecentLogs(limit) }); - }); - - app.get('/api/logs/export/trace', (c) => { - const exportedAt = new Date().toISOString(); - const download = buildFullTraceDownload(getLogSnapshot(), { - version: currentVersion(), - operatingSystem: os.platform(), - architecture: os.arch(), - nodeVersion: process.version, - logLevel: getLogLevel(), - exportedAt, - }); - for (const [name, value] of Object.entries(download.headers)) { - c.header(name, value); - } - return c.body(download.body); - }); - - app.get('/api/logs/level', (c) => { - return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] }); - }); - - app.post('/api/logs/level', async (c) => { - const body = await c.req.json().catch(() => null) as { level?: unknown } | null; - const next = typeof body?.level === 'string' ? body.level : ''; - if (!setLogLevel(next)) { - return c.json({ message: `invalid level: ${next}`, levels: [...LOG_LEVELS] }, 400); - } - log.info('console log level set to %s via WebUI', getLogLevel()); - return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] }); - }); - - app.get('/api/logs/stream', (c) => sseResponse(c, (ch) => { - ch.send({ type: 'ready' }); - ch.onClose(subscribeLogs((entry) => ch.send(entry))); - })); - - app.get('/api/processes', async (c) => { - if (!hookManager) return c.json({ list: [] }); - try { - return c.json({ list: await hookManager.listProcesses() }); - } catch (err) { - return c.json({ list: [], message: err instanceof Error ? err.message : String(err) }, 500); - } - }); - - // Per-process action handler. The three routes below differ only in - // which HookManager method they call. - const MAX_PID = 4_194_304; - function processAction(label: string, action: (pid: number) => Promise) { - return async (c: Context) => { - if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); - const pid = Number(c.req.param('pid')); - if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { - return c.json({ success: false, message: 'invalid pid' }, 400); - } - try { - const processInfo = await action(pid); - return c.json({ success: processInfo.status !== 'error', process: processInfo }); - } catch (err) { - log.warn('%s pid=%d failed: %s', label, pid, err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '操作失败,请检查服务器日志' }, 500); - } - }; - } - app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid))); - app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid))); - app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid))); - - app.get('/api/processes/:pid/probe-login', async (c) => { - if (!hookManager) return c.json({ info: null, message: 'hook manager is not available' }, 503); - const pid = Number(c.req.param('pid')); - if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { - return c.json({ info: null, message: 'invalid pid' }, 400); - } - try { - const info = await hookManager.probeProcessLoginInfo(pid); - return c.json({ info }); - } catch (err) { - log.warn('probe-login pid=%d failed: %s', pid, err instanceof Error ? err.message : String(err)); - return c.json({ info: null, message: '探测失败' }, 500); - } - }); - - app.get('/api/config/:uin', (c) => { - const uin = c.req.param('uin'); - if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400); - // Read-only: never write defaults to disk on a GET. The persisted - // file is created when manager.onSessionStarted boots an instance - // or when the operator POSTs from this very endpoint. - const config = loadOneBotConfig(uin); - return c.json({ config }); - }); - - app.post('/api/config/:uin', async (c) => { - const uin = c.req.param('uin'); - if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400); - let body: unknown; - try { - body = await c.req.json(); - } catch { - return c.json({ success: false, saved: false, applied: false, message: '请求格式错误' }, 400); - } - - let nextConfig: OneBotConfig; - try { - assertValidOneBotConfig(body); - nextConfig = body; - - let previousConfig: OneBotConfig | null = null; - try { - previousConfig = loadOneBotConfig(uin); - } catch (err) { - // A damaged existing file must not strand the recovery UI. Treat the - // submitted endpoints as new, apply the full policy, and let the - // subsequent atomic save either repair the file or fail visibly. + if (trustProxyMode.kind === 'all') { log.warn( - 'could not read prior OneBot config for uin=%s before save: %s', - uin, - err instanceof Error ? err.message : String(err), + 'SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For', ); - } - - validateOneBotAccessTokenChanges(previousConfig, nextConfig, { - clientIp: getSecurityClientIp(c), - uin, - }); - saveOneBotConfig(uin, nextConfig); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - if ( - err instanceof OneBotConfigValidationError - || err instanceof OneBotAccessTokenPolicyError - ) { - log.warn('reject invalid config for uin=%s: %s', uin, message); - return c.json({ success: false, saved: false, applied: false, message }, 400); - } - log.error('persist config for uin=%s failed: %s', uin, message); - return c.json({ success: false, saved: false, applied: false, message: '配置保存失败,请检查服务器日志' }, 500); } - try { - // Apply the exact validated value that was persisted above. Re-reading - // the path here would race concurrent POSTs (request A could load B and - // falsely report that A was applied). - const apply = await oneBotManager.reloadConfig(uin, nextConfig); - const message = !apply.online - ? '配置保存成功,当前会话未在线,将在下次连接时生效。' - : apply.applied - ? '配置保存成功,已热重载当前会话。' - : '配置已保存,但部分网络节点未能应用;旧节点已尽力恢复,请查看错误详情。'; - log.info( - 'Updated OneBot config for UIN=%s saved=true online=%s applied=%s failures=%d', - uin, - String(apply.online), - String(apply.applied), - apply.errors.length, - ); - return c.json({ - success: true, - saved: true, - applied: apply.applied, - online: apply.online, - errors: apply.errors, - adapters: apply.adapters, - config: body, - // Legacy compatibility: this field used to mean "a live instance was - // asked to reload". It now only claims success after the awaitable - // reconcile actually completed. - reloaded: apply.online && apply.applied, - message, - }); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - log.error('config saved but apply crashed for uin=%s: %s', uin, message); - return c.json({ - success: true, - saved: true, - applied: false, - online: oneBotManager.getInstance(uin) !== null, - reloaded: false, - errors: [{ name: 'network-manager', phase: 'reload', message, at: Date.now() }], - config: body, - message: '配置已保存,但热重载失败,请检查服务器日志。', - }); - } - }); + // Memoized once at startup (agreements version is fixed per process; a text + // change ships with a redeploy that restarts us). Flipped to false the moment + // consent is recorded, so the middleware never touches disk per request. + const environmentConsent = resolveEnvironmentConsent(); + let consentGatePending = isConsentRequired(); - // ─── Notifications (account up/down → webhook) ─────────────────────────── - // Global channel store (config/notifications.json); per-UIN opt-in lives in - // OneBotConfig.notifications.channelIds. All bearer-gated — channel URLs can - // embed secrets, so none of this is exposed unauthenticated. - app.get('/api/notifications/config', (c) => c.json({ config: loadNotificationsConfig() })); + if (environmentConsent.accepted) { + log.info( + 'EULA/PRIVACY consent supplied by %s and %s (agreements version=%s)', + EULA_ACCEPT_ENV, + PRIVACY_ACCEPT_ENV, + loadAgreements().version, + ); + } else if (environmentConsent.eulaAccepted || environmentConsent.privacyAccepted) { + log.warn( + 'partial environment consent ignored; set both %s=1 and %s=1 to accept the agreements', + EULA_ACCEPT_ENV, + PRIVACY_ACCEPT_ENV, + ); + } else if (consentGatePending) { + log.info('awaiting EULA/PRIVACY consent before the panel unlocks'); + } - app.post('/api/notifications/config', async (c) => { - const declaredLen = Number(c.req.header('content-length')); - if (Number.isFinite(declaredLen) && declaredLen > 512 * 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); - } - try { - const config = saveNotificationsConfig(body); - return c.json({ success: true, config }); - } catch (err) { - log.warn('save notifications config failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500); - } - }); - - app.get('/api/notifications/recent', (c) => { - if (!notificationManager) return c.json({ recent: [] }); - const limitRaw = Number(c.req.query('limit')); - const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(Math.trunc(limitRaw), 100) : 100; - return c.json({ recent: notificationManager.getRecent(limit) }); - }); - - app.post('/api/notifications/test', async (c) => { - if (!notificationManager) return c.json({ success: false, message: '通知子系统不可用' }, 503); - let body: { channelId?: unknown }; - try { - body = await c.req.json(); - } catch { - return c.json({ success: false, message: '请求格式错误' }, 400); - } - const channelId = typeof body.channelId === 'string' ? body.channelId : ''; - if (!channelId) return c.json({ success: false, message: '缺少 channelId' }, 400); - const result = await notificationManager.testSend(channelId); - if (!result.found) return c.json({ success: false, message: '渠道不存在' }, 404); - return c.json({ - success: result.ok, - status: result.status, - message: result.ok - ? '测试发送成功' - : `测试发送失败:${result.error ?? (result.status ? `HTTP ${result.status}` : '未知错误')}`, + const app = new Hono(); + app.use('*', webuiSecurityHeaders); + registerLoginRequestSecurity(app); + const storageManagement = new StorageManagementService({ + dataDir: 'data', + getLogStatus: getLogStorageStatus, + clearLogs: clearManagedLogs, + temporary: { + snapshot: snapshotStreamStorage, + clearInactive: clearInactiveStreamStorage, + }, + // Connection statuses include active and still-retiring generations. + // A retiring instance may still hold SQLite handles after disappearing + // from getInstances(), so it must continue to block destructive cleanup. + listOnlineAccounts: () => + oneBotManager + .getConnectionStatuses() + .map((account) => ({ uin: account.uin, nickname: account.nickname })), + }); + const logStorageSettings = new LogStorageSettingsManager({ + readPersisted: readRuntimeConfig, + readEnvOverrides: () => resolveRuntimeEnvOverrides(process.env), + readEffective: getLogStorageStatus, + persist: updateRuntimeConfig, + apply: configureFileTransport, }); - }); - // ─── Global deployment config (config/snowluma.json) ───────────────────── - // All-accounts SnowLuma knobs (rkey fallback servers + musicSignUrl). Saving - // section-merges + normalizes server-side, then hot-reloads every instance. - app.get('/api/global-config', (c) => c.json({ config: loadGlobalSettings() })); + // ─── Anti-indexing ─────────────────────────────────────────────────────── + // The WebUI is an admin surface that has no business showing up in + // search results — even the login page leaks the existence of a + // SnowLuma instance to anyone scanning the IP. Three overlapping + // signals: a hard X-Robots-Tag on every response, a robots.txt for + // crawlers that read it before pages, and a in the + // SPA shell for the case where a proxy strips headers. + app.use('*', async (c, next) => { + await next(); + c.res.headers.set('X-Robots-Tag', 'noindex, nofollow, noarchive, nosnippet, noimageindex'); + }); - app.post('/api/global-config', async (c) => { - const declaredLen = Number(c.req.header('content-length')); - if (Number.isFinite(declaredLen) && declaredLen > 512 * 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); - } - try { - const config = saveGlobalSettings(body); - oneBotManager.reloadGlobalSettings(); - return c.json({ success: true, config }); - } catch (err) { - log.warn('save global config failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500); - } - }); + app.get('/robots.txt', (c) => { + c.res.headers.set('Content-Type', 'text/plain; charset=utf-8'); + return c.body('User-agent: *\nDisallow: /\n'); + }); - // ─── WebUI customization config (config/ui.json) ───────────────────────── - // Appearance (A) + layout (C). The full config is bearer-gated; only the - // cosmetic appearance subset is exposed unauthenticated for the login page. - app.get('/api/ui', (c) => c.json({ config: loadUiConfig() })); + // ─── Auth middleware ───────────────────────────────────────────────────── + app.use('/api/*', async (c, next) => { + const reqPath = c.req.path; - app.get('/api/ui/public', (c) => c.json({ appearance: publicAppearance() })); + // `/api/ui/public` serves the cosmetic appearance subset to the + // pre-auth login page, so it must skip the bearer check. It exposes + // nothing sensitive (no layout, no secrets) — see ui-config.ts. + if (reqPath === '/api/login' || reqPath === '/api/ui/public') { + return next(); + } - app.post('/api/ui', async (c) => { - // Reject oversized bodies before buffering — the normalizer caps individual - // fields (customCss 50KB, per-widget config 4KB) but not the whole payload. - const declaredLen = Number(c.req.header('content-length')); - if (Number.isFinite(declaredLen) && declaredLen > 256 * 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); - } - try { - const config = saveUiConfig(body); - return c.json({ success: true, config }); - } catch (err) { - log.warn('save ui.json failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 400); - } - }); + const token = extractBearerToken(c.req.raw); - app.post('/api/ui/background', async (c) => { - // Early reject by Content-Length BEFORE parseBody() buffers the whole - // multipart body into memory — otherwise a multi-GB upload is fully - // materialized before the post-parse size check fires. The slack covers - // the multipart envelope (boundary + part headers); the exact decoded - // size is still enforced below. A chunked request with no Content-Length - // skips this coarse guard, but the endpoint is bearer-gated to the single - // admin, so that residual is acceptable. - const declaredLen = Number(c.req.header('content-length')); - if (Number.isFinite(declaredLen) && declaredLen > MAX_BACKGROUND_BYTES + 1024 * 1024) { - return c.json({ success: false, message: '图片过大(上限 5MB)' }, 413); - } - let file: unknown; - try { - const form = await c.req.parseBody(); - file = form['file']; - } catch { - return c.json({ success: false, message: '上传解析失败' }, 400); - } - if (!(file instanceof File)) { - return c.json({ success: false, message: '缺少图片文件' }, 400); - } - if (file.size > MAX_BACKGROUND_BYTES) { - return c.json({ success: false, message: '图片过大(上限 5MB)' }, 413); - } - const bytes = new Uint8Array(await file.arrayBuffer()); - const mime = sniffImageMime(bytes); - if (!mime) { - return c.json({ success: false, message: '仅支持 PNG / JPEG / WebP 图片' }, 415); - } - try { - const config = writeBackgroundImage(bytes, mime); - return c.json({ success: true, config }); - } catch (err) { - log.warn('write background image failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '保存图片失败,请检查服务器日志' }, 500); - } - }); + if (!token) { + return c.json({ status: 'failed', message: 'Unauthorized' }, 401); + } - app.delete('/api/ui/background', (c) => { - try { - const config = clearBackgroundImage(); - return c.json({ success: true, config }); - } catch (err) { - log.warn('clear background image failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '删除图片失败' }, 500); - } - }); + const info = sessionTokens.get(token); - // ─── Static frontend ───────────────────────────────────────────────────── - // Build path is relative to the bundled / dev __dirname. SPA fallback to - // index.html so client-side routes (if any) keep working. - const staticRoot = path.resolve(__dirname, 'client'); - app.use('/*', serveStatic({ root: staticRoot })); + if (!info || Date.now() > info.expiresAt) { + return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401); + } - const indexHtmlPath = path.join(staticRoot, 'index.html'); - app.get('*', (c) => { - // SPA fallback: only for navigations that didn't hit a static asset. - if ( - c.req.path.startsWith('/api/') || - c.req.path.startsWith('/avatar/') || - c.req.path.startsWith('/ui-asset/') - ) { - return c.text('not found', 404); + // Consent gate (before the password gate): block everything outside the + // consent allowlist until the operator has accepted the current agreements. + // `consentGatePending` is memoized (see below) so this is a Set lookup, not + // a disk read, on the hot path. + if (consentGatePending && !CONSENT_ALLOWLIST.has(reqPath)) { + return c.json( + { + status: 'failed', + message: '请先阅读并同意用户协议与隐私政策', + consentRequired: true, + }, + 403, + ); + } + + if (info.mustChangePassword && !MUST_CHANGE_ALLOWLIST.has(reqPath)) { + return c.json( + { status: 'failed', message: '请先修改密码', mustChangePassword: true }, + 403, + ); + } + + c.set('sessionToken' as never, token); + c.res = await traceAuthenticatedWebuiMutation(c.req.raw, async () => { + await next(); + return c.res; + }); + }); + + // Periodic janitor — keeps sessionTokens / loginAttempts from growing + // unbounded and replaces the per-request O(n) sweep we used to do. + const tokenJanitor = setInterval(purgeExpiredTokens, 60_000); + tokenJanitor.unref?.(); + + // ─── Login ─────────────────────────────────────────────────────────────── + app.post('/api/login', async (c) => { + const ip = getClientIp(c); + const now = Date.now(); + const attempt = loginAttempts.get(ip); + + if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) { + const waitSec = Math.ceil((attempt.resetAt - now) / 1000); + return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429); + } + + let body: unknown; + + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + + const result = completeWebuiLogin(auth, body, now); + + if (result.kind === 'bad-request') { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + + if (result.kind === 'bad-password' || result.kind === 'bad-second-factor') { + const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS }; + current.count += 1; + + if (current.count === 1) { + current.resetAt = now + LOGIN_LOCKOUT_MS; + } + + loginAttempts.set(ip, current); + const message = result.kind === 'bad-second-factor' ? '验证码不正确' : '密码错误'; + return c.json({ success: false, message }, 401); + } + + if (result.kind === 'needs-totp') { + return c.json({ success: false, needsTotp: true }); + } + + loginAttempts.delete(ip); + + if (result.totpState) { + try { + auth.persistTotp(result.totpState); + } catch (err) { + log.warn( + 'persist totp after login failed: %s', + err instanceof Error ? err.message : String(err), + ); + return c.json({ success: false, message: '登录失败' }, 500); + } + } + + const token = randomBytes(32).toString('hex'); + sessionTokens.set(token, { + expiresAt: now + TOKEN_TTL_MS, + mustChangePassword: result.mustChangePassword, + }); + setAvatarSessionCookie(c, token, listener.tlsEnabled === true); + return c.json({ success: true, token, mustChangePassword: result.mustChangePassword }); + }); + + app.post('/api/logout', (c) => { + const token = c.get('sessionToken' as never) as string | undefined; + + if (token) { + sessionTokens.delete(token); + } + + clearAvatarSessionCookie(c, listener.tlsEnabled === true); + return c.json({ success: true }); + }); + + app.get('/api/auth/state', (c) => { + const token = c.get('sessionToken' as never) as string | undefined; + const info = token ? sessionTokens.get(token) : undefined; + return c.json({ + mustChangePassword: info?.mustChangePassword ?? auth.mustChangePassword(), + }); + }); + + app.post('/api/auth/check-strength', async (c) => { + let body: { password?: unknown }; + + try { + body = await c.req.json(); + } catch { + return c.json({ rules: evaluatePasswordRules(''), valid: false }); + } + + const pwd = typeof body.password === 'string' ? body.password : ''; + return c.json({ rules: evaluatePasswordRules(pwd), valid: isStrongPassword(pwd) }); + }); + + app.post('/api/auth/change-password', async (c) => { + let body: { oldPassword?: unknown; newPassword?: unknown }; + + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + + const oldPassword = typeof body.oldPassword === 'string' ? body.oldPassword : ''; + const newPassword = typeof body.newPassword === 'string' ? body.newPassword : ''; + + if (!auth.verify(oldPassword)) { + return c.json({ success: false, message: '当前密码不正确' }, 401); + } + + if (!isStrongPassword(newPassword)) { + return c.json( + { + success: false, + message: '新密码不符合强度要求', + rules: evaluatePasswordRules(newPassword), + }, + 400, + ); + } + + if (oldPassword === newPassword) { + return c.json({ success: false, message: '新密码不得与旧密码相同' }, 400); + } + + try { + auth.setPassword(newPassword, oldPassword); + } catch (err) { + log.warn( + 'change password failed: %s', + err instanceof Error ? err.message : String(err), + ); + return c.json({ success: false, message: '密码修改失败' }, 400); + } + + // Invalidate every session, including the current one. If the old + // password was compromised, the attacker may already hold the current + // token; rotating credentials must rotate sessions too. + sessionTokens.clear(); + clearAvatarSessionCookie(c, listener.tlsEnabled === true); + log.info('password updated; all sessions invalidated'); + return c.json({ success: true, requireRelogin: true }); + }); + + const totpDisabledInDev = () => auth.isDevMode(); + + app.get('/api/auth/totp', (c) => { + if (totpDisabledInDev()) { + return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); + } + + return c.json(auth.totpStatus()); + }); + + app.post('/api/auth/totp/begin', async (c) => { + if (totpDisabledInDev()) { + return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); + } + + if (auth.totpEnabled()) { + return c.json({ success: false, message: '2FA 已开启' }, 409); + } + + const token = c.get('sessionToken' as never) as string; + let body: Record = {}; + + try { + const parsed = await c.req.json(); + + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + body = parsed as Record; + } + } catch { + body = {}; + } + + const issuer = sanitizeTotpLabelPart(body.issuer, DEFAULT_TOTP_ISSUER); + const accountName = sanitizeTotpLabelPart(body.accountName, defaultTotpAccountName()); + const now = Date.now(); + const existing = totpEnrollments.get(token); + const secret = existing && existing.expiresAt > now ? existing.secret : undefined; + const enrollment = beginTotpEnrollment({ issuer, accountName, secret }); + totpEnrollments.set(token, { + secret: enrollment.secret, + issuer, + accountName, + expiresAt: now + TOTP_ENROLL_TTL_MS, + }); + return c.json({ + success: true, + secret: enrollment.secret, + otpauthUrl: enrollment.otpauthUrl, + issuer: enrollment.issuer, + accountName: enrollment.accountName, + }); + }); + + app.post('/api/auth/totp/confirm', async (c) => { + if (totpDisabledInDev()) { + return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); + } + + if (auth.totpEnabled()) { + return c.json({ success: false, message: '2FA 已开启' }, 409); + } + + const token = c.get('sessionToken' as never) as string; + let body: { password?: unknown; code?: unknown }; + + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + + const password = typeof body.password === 'string' ? body.password : ''; + const code = typeof body.code === 'string' ? body.code : ''; + + if (!auth.verify(password)) { + return c.json({ success: false, message: '当前密码不正确' }, 401); + } + + const pending = totpEnrollments.get(token); + + if (!pending || pending.expiresAt <= Date.now()) { + totpEnrollments.delete(token); + return c.json({ success: false, message: '请先开始绑定' }, 400); + } + + try { + const enabled = confirmTotpEnrollment({ + password, + secret: pending.secret, + code, + label: `${pending.issuer} (${pending.accountName})`, + atMs: Date.now(), + }); + auth.persistTotp(enabled.state); + totpEnrollments.delete(token); + invalidateOtherSessions(sessionTokens, token); + log.info('webui 2FA enabled; other sessions invalidated'); + return c.json({ success: true, recoveryCodes: enabled.recoveryCodes }); + } catch (err) { + log.warn('totp confirm failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '验证码不正确' }, 401); + } + }); + + app.post('/api/auth/totp/disable', async (c) => { + if (totpDisabledInDev()) { + return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); + } + + if (!auth.totpEnabled()) { + return c.json({ success: false, message: '2FA 未开启' }, 400); + } + + const token = c.get('sessionToken' as never) as string; + let body: { password?: unknown; totp?: unknown; recoveryCode?: unknown }; + + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + + const password = typeof body.password === 'string' ? body.password : ''; + + if (!auth.verify(password)) { + return c.json({ success: false, message: '当前密码不正确' }, 401); + } + + const decision = decideSecondFactorLogin({ + totpEnabled: true, + state: auth.totpState(), + password, + totp: typeof body.totp === 'string' ? body.totp : undefined, + recoveryCode: typeof body.recoveryCode === 'string' ? body.recoveryCode : undefined, + atMs: Date.now(), + }); + + if (decision.kind !== 'ok') { + return c.json({ success: false, message: '验证码不正确' }, 401); + } + + auth.persistTotp(undefined); + totpEnrollments.delete(token); + invalidateOtherSessions(sessionTokens, token); + log.info('webui 2FA disabled; other sessions invalidated'); + return c.json({ success: true }); + }); + + app.post('/api/auth/totp/recovery-codes', async (c) => { + if (totpDisabledInDev()) { + return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400); + } + + const state = auth.totpState(); + + if (!state) { + return c.json({ success: false, message: '2FA 未开启' }, 400); + } + + let body: { password?: unknown; totp?: unknown }; + + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + + const password = typeof body.password === 'string' ? body.password : ''; + const totp = typeof body.totp === 'string' ? body.totp : ''; + + if (!auth.verify(password)) { + return c.json({ success: false, message: '当前密码不正确' }, 401); + } + + try { + const next = regenerateRecoveryCodes({ + password, + state, + totp, + atMs: Date.now(), + }); + auth.persistTotp(next.state); + log.info('webui 2FA recovery codes regenerated'); + return c.json({ success: true, recoveryCodes: next.recoveryCodes }); + } catch (err) { + log.warn( + 'totp recovery regenerate failed: %s', + err instanceof Error ? err.message : String(err), + ); + return c.json({ success: false, message: '验证码不正确' }, 401); + } + }); + + // ─── EULA / PRIVACY consent ────────────────────────────────────────────── + // Both are bearer-gated (consent is collected AFTER login) and live in the + // consent + must-change allowlists so they're reachable during onboarding. + // The version is content-derived, so consent is stable across app upgrades + // and re-prompted only when the agreement text itself changes. + app.get('/api/agreements', (c) => c.json(getAgreementsPayload())); + + app.post('/api/agreements/record-consent', async (c) => { + let body: { version?: unknown }; + + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + + const version = typeof body.version === 'string' ? body.version : ''; + const current = loadAgreements().version; + + // Reject a stale/blank version so a client that read an older agreement set + // can't record consent that the server would then treat as current. + if (!version || version !== current) { + return c.json( + { + success: false, + message: '协议版本已更新,请刷新后重新确认', + currentVersion: current, + }, + 409, + ); + } + + try { + recordConsent(version); + } catch (err) { + log.warn('record consent failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500); + } + + consentGatePending = false; // unlock the rest of the API for this process + log.info('agreements consent recorded (version=%s)', version); + return c.json({ success: true, version }); + }); + + // ─── Avatar proxy (uin validated) ──────────────────────────────────────── + app.get('/avatar/:uin', async (c) => { + const sessionToken = readAvatarSessionToken(c); + const session = sessionTokens.get(sessionToken); + + if (!session || Date.now() > session.expiresAt) { + if (sessionToken) { + sessionTokens.delete(sessionToken); + } + + return c.text('unauthorized', 401); + } + + const uin = c.req.param('uin'); + + if (!UIN_REGEX.test(uin)) { + return c.text('invalid uin', 400); + } + + const now = Date.now(); + let cached = avatarCache.get(uin); + + if (!cached || cached.expiresAt <= now) { + try { + const avatar = await fetchQqAvatar(uin); + cached = { ...avatar, expiresAt: now + AVATAR_CACHE_TTL_MS }; + avatarCache.set(uin, cached); + } catch (err) { + log.warn( + 'failed to proxy avatar for UIN %s: %s', + uin, + err instanceof Error ? err.message : String(err), + ); + + if (!cached) { + return c.text('avatar unavailable', 502); + } + } + } + + return new Response(cached.body, { + headers: { + 'Content-Type': cached.contentType, + 'Cache-Control': `private, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`, + Vary: 'Cookie', + }, + }); + }); + + // ─── Background image (unauth, like /avatar) ───────────────────────────── + // The login page needs to render the operator's background before auth, so + // this route is intentionally public. It only serves a file the operator + // themselves uploaded. Cache-busting is via the `?v=` version the client + // appends; the bytes for a given version are immutable. + app.get('/ui-asset/background', (c) => { + const asset = readBackgroundImage(); + + if (!asset) { + return c.text('no background', 404); + } + + return new Response(new Uint8Array(asset.bytes), { + headers: { + 'Content-Type': asset.mime, + 'Cache-Control': 'public, max-age=31536000, immutable', + // Defence-in-depth: never let an uploaded blob be interpreted as + // anything but the sniffed image type. + 'X-Content-Type-Options': 'nosniff', + }, + }); + }); + + // ─── Read-only API ─────────────────────────────────────────────────────── + app.get('/api/status', (c) => { + // Refresh the path-scoped avatar cookie for a still-valid localStorage + // session (for example after upgrading from a version without the cookie). + const token = c.get('sessionToken' as never) as string; + setAvatarSessionCookie(c, token, listener.tlsEnabled === true); + return c.json({ status: 'running' }); + }); + + // Advisory update check — compares the running build against the latest + // GitHub stable release and links the user to it. Read-only: SnowLuma + // never downloads or applies the update itself. `?force=1` bypasses the + // server-side cache (the "立即检查" button). Never errors out — a failed + // check returns `{ hasUpdate: false, error }` and the UI degrades quietly. + app.get('/api/update/check', async (c) => { + const force = c.req.query('force') === 'true' || c.req.query('force') === '1'; + return c.json(await getUpdateInfo(force)); + }); + + let lastCpuTimes: { idle: number; total: number }[] | null = null; + + function sampleCpuLoad(): number[] { + const cpus = os.cpus(); + const current = cpus.map((cpu) => { + const t = cpu.times; + const total = t.user + t.nice + t.sys + t.idle + t.irq; + return { idle: t.idle, total }; + }); + + if (!lastCpuTimes || lastCpuTimes.length !== current.length) { + lastCpuTimes = current; + return current.map(() => 0); + } + + const usage = current.map((cur, i) => { + const prev = lastCpuTimes![i]; + const totalDiff = cur.total - prev.total; + const idleDiff = cur.idle - prev.idle; + + if (totalDiff <= 0) { + return 0; + } + + return Math.max(0, Math.min(100, ((totalDiff - idleDiff) / totalDiff) * 100)); + }); + lastCpuTimes = current; + return usage; } - if (existsSync(indexHtmlPath)) { - const html = readFileSync(indexHtmlPath, 'utf8'); - return c.html(html); - } - return c.text( - 'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).', - 404, + + app.get('/api/system', (c) => { + const cpus = os.cpus(); + const usage = sampleCpuLoad(); + const totalMem = os.totalmem(); + const freeMem = os.freemem(); + const usedMem = totalMem - freeMem; + const runtimeMemory = process.memoryUsage(); + return c.json({ + hostname: os.hostname(), + platform: os.platform(), + arch: os.arch(), + archLabel: CACHED_ARCH_LABEL, + release: os.release(), + distro: CACHED_DISTRO, + uptime: os.uptime(), + processUptime: process.uptime(), + nodeVersion: process.version, + cpu: { + model: cpus[0]?.model ?? 'unknown', + cores: cpus.length, + speedMHz: cpus[0]?.speed ?? 0, + loadAvg: os.loadavg(), + perCore: usage, + average: usage.length ? usage.reduce((s, v) => s + v, 0) / usage.length : 0, + }, + memory: { + total: totalMem, + free: freeMem, + used: usedMem, + usagePercent: totalMem ? (usedMem / totalMem) * 100 : 0, + }, + runtime: { + pid: process.pid, + rss: runtimeMemory.rss, + heapTotal: runtimeMemory.heapTotal, + heapUsed: runtimeMemory.heapUsed, + external: runtimeMemory.external, + arrayBuffers: runtimeMemory.arrayBuffers, + }, + }); + }); + + // ── 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); + } + + const evaluated = evaluateSettingsSave( + readRuntimeConfig(), + coerced.patch, + resolveTlsContext('config').ok, + ); + + if (!evaluated.ok) { + return c.json({ success: false, message: evaluated.error }, 400); + } + + const saved = updateRuntimeConfig(evaluated.patch); + return c.json({ + success: true, + settings: { + webuiPort: saved.webuiPort, + webuiHost: saved.webuiHost, + tlsEnabled: saved.webuiTls?.enabled ?? false, + trustProxy: saved.trustProxy ?? '', + }, + restartRequiredToApply: true, + }); + }); + + registerStorageRoutes(app, { + storage: storageManagement, + settings: logStorageSettings, + audit: (event) => { + log.info( + 'storage cleanup scope=%s accountScope=%s category=%s uin=%s deletedFiles=%d freedBytes=%d failures=%d', + event.scope, + event.accountScope, + event.category ?? '-', + event.uin ?? '-', + event.deletedFiles, + event.freedBytes, + event.failureCount, + ); + }, + reportError: (operation, error) => { + log.error( + '%s failed: %s', + operation, + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + }, + }); + + 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) => { + if (tlsCertDeletionBlocked(readRuntimeConfig().webuiTls?.enabled === true)) { + return c.json({ success: false, message: '请先关闭 TLS 再删除证书' }, 400); + } + + 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) ── + app.get('/api/system/backup/export', (c) => { + try { + const includeCredentials = c.req.query('credentials') === '1'; + const ts = new Date().toISOString(); + const bundle = buildBackup( + (name) => readBackupConfigFile('config', name), + listPerUinOneBotConfigFiles('config'), + { 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); + } catch (error) { + log.error( + 'backup export failed: %s', + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + return c.json({ success: false, message: '导出失败,请检查服务器日志' }, 500); + } + }); + + 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; + }; + + try { + const result = restoreBackup(backup, { + configDir: 'config', + restoreCredentials: restoreCredentials === true, + }); + return c.json({ success: true, ...result }); + } catch (err) { + if (err instanceof RestoreTransactionError) { + const failure = describeRestoreFailure(err); + return c.json(failure.body, failure.status); + } + + log.error( + 'backup import failed unexpectedly: %s', + err instanceof Error ? (err.stack ?? err.message) : String(err), + ); + return c.json({ success: false, message: '恢复遇到未预期错误,请检查服务器日志' }, 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() }), ); - }); - const finalPort = await findAvailablePort(desiredPort, { host }); - if (finalPort !== desiredPort) { - log.warn('port %d is in use, using %d instead', desiredPort, finalPort); - } - boundPort = finalPort; + // 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; - // TLS is an explicit transport promise. Once enabled, an unusable pair must - // abort startup instead of silently exposing the listener over plaintext. - let tlsServe: { createServer: typeof createHttpsServer; serverOptions: { cert: Buffer; key: Buffer } } | undefined; - let scheme = 'http'; - if (listener.tlsEnabled) { - const tls = requireTlsContext('config'); - tlsServe = { createServer: createHttpsServer, serverOptions: tls }; - scheme = 'https'; - } + try { + body = await c.req.json(); + } catch { + return c.json({ status: 'failed', message: '请求格式错误' }, 400); + } - const listeningServer = await new Promise>((resolve) => { - const server = serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => { - log.info(`listening ${scheme}://${host}:${info.port}`); - resolve(server); + 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); }); - }); - return { - port: finalPort, - async stop() { - connectionDiffLoop?.dispose(); - await new Promise((resolve, reject) => { - listeningServer.close((err) => (err ? reject(err) : resolve())); - }); - }, - }; + + // Invoke a Stream API action (or any action) and relay every frame to the + // browser over an SSE body. The frontend reads this with fetch()+a stream + // reader (Bearer auth in the header), so — unlike /api/debug/stream — it does + // NOT need a query-token allowlist entry. Frames are never dropped. + app.post('/api/debug/invoke-stream', async (c) => { + let body: unknown; + + try { + body = await c.req.json(); + } catch { + return c.json({ status: 'failed', message: '请求格式错误' }, 400); + } + + const { uin, action, params } = (body ?? {}) as { + uin?: unknown; + action?: unknown; + params?: unknown; + }; + + if (typeof uin !== 'string' || !UIN_REGEX.test(uin)) { + return c.json({ status: 'failed', message: '无效的账号' }, 400); + } + + if (typeof action !== 'string' || !action) { + return c.json({ status: 'failed', message: 'action 必填' }, 400); + } + + if ( + params !== undefined && + (typeof params !== 'object' || params === null || Array.isArray(params)) + ) { + return c.json({ status: 'failed', message: 'params 必须是对象' }, 400); + } + + const inst = oneBotManager.getInstance(uin); + + if (!inst) { + return c.json({ status: 'failed', message: '账号不在线' }, 404); + } + + const rawRequest = JSON.stringify({ action, params: params ?? {} }); + return buildStreamInvokeResponse( + (rq, emit, alive) => inst.invokeStream(rq, emit, alive), + rawRequest, + c.req.raw.signal, + ); + }); + + // Stream a browser-selected file to a temp path on THIS server (the bot runs + // here, not on the operator's machine), so the returned path can be fed to a + // send action's file/image/record/video param. Raw bytes in the body, + // `?filename=` for a human-readable suffix; streamed to disk with a byte cap. + app.post('/api/debug/upload', async (c) => { + try { + const result = await streamUploadToDisk( + c.req.raw.body as ReadableStream | null, + c.req.query('filename'), + ); + return c.json({ status: 'ok', path: result.path, size: result.size }); + } catch (err) { + return c.json( + { status: 'failed', message: err instanceof Error ? err.message : '上传失败' }, + 400, + ); + } + }); + + // Live merged SSE of OneBot events + action calls across all accounts. Taps + // are attached only while a client is connected (on-demand). A slow client is + // dropped (not back-pressured onto the bot) with a periodic drop marker. + app.get('/api/debug/stream', (c) => + sseResponse(c, (ch) => { + // Drop-under-backpressure framing (unit-tested in debug-stream.ts). + const pushFrame = createFramePusher({ + desiredSize: ch.desiredSize, + enqueue: ch.raw, + encode: ch.encode, + }); + + const send = (payload: unknown) => { + if (!ch.isClosed()) { + pushFrame(payload); + } + }; + + send({ kind: 'ready' }); + + for (const inst of oneBotManager.getInstances()) { + const uin = inst.uin; + ch.onClose( + inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event })), + ); + ch.onClose(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec }))); + } + }), + ); + + app.get('/api/qq-list', (c) => { + const instances = oneBotManager.getInstances(); + const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname })); + return c.json({ list }); + }); + + // Live OneBot adapter health per account (listening / connected / client + // counts / last-delivery), powering the dashboard's connection card. + app.get('/api/connections', (c) => { + return c.json({ list: oneBotManager.getConnectionStatuses() }); + }); + + // Combined SSE feed for the dashboard's three live resources — processes, + // qq-list, connections. Replaces the 3s REST polling tick in + // app-layout.tsx; the REST endpoints above stay for the initial fetch + // before SSE connects and for the slow (30s) reconciliation fallback. + // + // On connect: one frame per resource with the current snapshot. After + // that: a fresh snapshot per resource only when the StateBus signals a + // change (HookSession status-changed, BridgeManager session edges, the + // connection-status diff loop). 50ms per-resource debounce coalesces a + // burst (e.g. multiple HookSessions flipping status simultaneously). + const stateBus = listener.stateBus; + app.get('/api/state/stream', (c) => { + if (!stateBus) { + // Build without state-wiring (e.g. a future headless mode) — clients + // fall back to the REST endpoints. Treat as endpoint-not-here. + return c.text('state stream not configured', 503); + } + + const liveBus = stateBus; + return sseResponse(c, (ch) => { + const pushFrame = createFramePusher({ + desiredSize: ch.desiredSize, + enqueue: ch.raw, + encode: ch.encode, + }); + + const send = (payload: unknown) => { + if (!ch.isClosed()) { + pushFrame(payload); + } + }; + + send({ kind: 'ready' }); + + const handle = bindStateStream({ + bus: liveBus, + snapshot: async (resource: StateResource): Promise => { + if (resource === 'processes') { + if (!hookManager) { + return []; + } + + return hookManager.listProcesses(); + } + + if (resource === 'qq-list') { + return oneBotManager + .getInstances() + .map((inst) => ({ uin: inst.uin, nickname: inst.nickname })); + } + + return oneBotManager.getConnectionStatuses(); + }, + send: (frame) => send(frame), + debounceMs: 50, + }); + ch.onClose(() => handle.dispose()); + // Prime with the initial snapshot; if the client never sees the + // bus publish (idle system) it still has the current state. + void handle.sendAllInitial(); + }); + }); + + app.get('/api/logs', (c) => { + const limit = Number(c.req.query('limit') ?? 300); + return c.json({ list: getRecentLogs(limit) }); + }); + + app.get('/api/logs/export/trace', (c) => { + const exportedAt = new Date().toISOString(); + const download = buildFullTraceDownload(getLogSnapshot(), { + version: currentVersion(), + operatingSystem: os.platform(), + architecture: os.arch(), + nodeVersion: process.version, + logLevel: getLogLevel(), + exportedAt, + }); + + for (const [name, value] of Object.entries(download.headers)) { + c.header(name, value); + } + + return c.body(download.body); + }); + + app.get('/api/logs/level', (c) => { + return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] }); + }); + + app.post('/api/logs/level', async (c) => { + const body = (await c.req.json().catch(() => null)) as { level?: unknown } | null; + const next = typeof body?.level === 'string' ? body.level : ''; + + if (!setLogLevel(next)) { + return c.json({ message: `invalid level: ${next}`, levels: [...LOG_LEVELS] }, 400); + } + + log.info('console log level set to %s via WebUI', getLogLevel()); + return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] }); + }); + + app.get('/api/logs/stream', (c) => + sseResponse(c, (ch) => { + ch.send({ type: 'ready' }); + ch.onClose(subscribeLogs((entry) => ch.send(entry))); + }), + ); + + app.get('/api/processes', async (c) => { + if (!hookManager) { + return c.json({ list: [] }); + } + + try { + return c.json({ list: await hookManager.listProcesses() }); + } catch (err) { + return c.json( + { list: [], message: err instanceof Error ? err.message : String(err) }, + 500, + ); + } + }); + + // Per-process action handler. The three routes below differ only in + // which HookManager method they call. + const MAX_PID = 4_194_304; + + function processAction(label: string, action: (pid: number) => Promise) { + return async (c: Context) => { + if (!hookManager) { + return c.json({ success: false, message: 'hook manager is not available' }, 503); + } + + const pid = Number(c.req.param('pid')); + + if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { + return c.json({ success: false, message: 'invalid pid' }, 400); + } + + try { + const processInfo = await action(pid); + return c.json({ success: processInfo.status !== 'error', process: processInfo }); + } catch (err) { + log.warn( + '%s pid=%d failed: %s', + label, + pid, + err instanceof Error ? err.message : String(err), + ); + return c.json({ success: false, message: '操作失败,请检查服务器日志' }, 500); + } + }; + } + + app.post( + '/api/processes/:pid/load', + processAction('load', (pid) => hookManager!.loadProcess(pid)), + ); + app.post( + '/api/processes/:pid/unload', + processAction('unload', (pid) => hookManager!.unloadProcess(pid)), + ); + app.post( + '/api/processes/:pid/refresh', + processAction('refresh', (pid) => hookManager!.refreshProcess(pid)), + ); + + app.get('/api/processes/:pid/probe-login', async (c) => { + if (!hookManager) { + return c.json({ info: null, message: 'hook manager is not available' }, 503); + } + + const pid = Number(c.req.param('pid')); + + if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { + return c.json({ info: null, message: 'invalid pid' }, 400); + } + + try { + const info = await hookManager.probeProcessLoginInfo(pid); + return c.json({ info }); + } catch (err) { + log.warn( + 'probe-login pid=%d failed: %s', + pid, + err instanceof Error ? err.message : String(err), + ); + return c.json({ info: null, message: '探测失败' }, 500); + } + }); + + app.get('/api/config/:uin', (c) => { + const uin = c.req.param('uin'); + + if (!UIN_REGEX.test(uin)) { + return c.json({ message: 'invalid uin' }, 400); + } + + // Read-only: never write defaults to disk on a GET. The persisted + // file is created when manager.onSessionStarted boots an instance + // or when the operator POSTs from this very endpoint. + const config = loadOneBotConfig(uin); + return c.json({ config }); + }); + + app.post('/api/config/:uin', async (c) => { + const uin = c.req.param('uin'); + + if (!UIN_REGEX.test(uin)) { + return c.json({ success: false, message: 'invalid uin' }, 400); + } + + let body: unknown; + + try { + body = await c.req.json(); + } catch { + return c.json( + { success: false, saved: false, applied: false, message: '请求格式错误' }, + 400, + ); + } + + let nextConfig: OneBotConfig; + + try { + assertValidOneBotConfig(body); + nextConfig = body; + + let previousConfig: OneBotConfig | null = null; + + try { + previousConfig = loadOneBotConfig(uin); + } catch (err) { + // A damaged existing file must not strand the recovery UI. Treat the + // submitted endpoints as new, apply the full policy, and let the + // subsequent atomic save either repair the file or fail visibly. + log.warn( + 'could not read prior OneBot config for uin=%s before save: %s', + uin, + err instanceof Error ? err.message : String(err), + ); + } + + validateOneBotAccessTokenChanges(previousConfig, nextConfig, { + clientIp: getSecurityClientIp(c), + uin, + }); + saveOneBotConfig(uin, nextConfig); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + + if ( + err instanceof OneBotConfigValidationError || + err instanceof OneBotAccessTokenPolicyError + ) { + log.warn('reject invalid config for uin=%s: %s', uin, message); + return c.json({ success: false, saved: false, applied: false, message }, 400); + } + + log.error('persist config for uin=%s failed: %s', uin, message); + return c.json( + { + success: false, + saved: false, + applied: false, + message: '配置保存失败,请检查服务器日志', + }, + 500, + ); + } + + try { + // Apply the exact validated value that was persisted above. Re-reading + // the path here would race concurrent POSTs (request A could load B and + // falsely report that A was applied). + const apply = await oneBotManager.reloadConfig(uin, nextConfig); + const message = !apply.online + ? '配置保存成功,当前会话未在线,将在下次连接时生效。' + : apply.applied + ? '配置保存成功,已热重载当前会话。' + : '配置已保存,但部分网络节点未能应用;旧节点已尽力恢复,请查看错误详情。'; + log.info( + 'Updated OneBot config for UIN=%s saved=true online=%s applied=%s failures=%d', + uin, + String(apply.online), + String(apply.applied), + apply.errors.length, + ); + return c.json({ + success: true, + saved: true, + applied: apply.applied, + online: apply.online, + errors: apply.errors, + adapters: apply.adapters, + config: body, + // Legacy compatibility: this field used to mean "a live instance was + // asked to reload". It now only claims success after the awaitable + // reconcile actually completed. + reloaded: apply.online && apply.applied, + message, + }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + log.error('config saved but apply crashed for uin=%s: %s', uin, message); + return c.json({ + success: true, + saved: true, + applied: false, + online: oneBotManager.getInstance(uin) !== null, + reloaded: false, + errors: [{ name: 'network-manager', phase: 'reload', message, at: Date.now() }], + config: body, + message: '配置已保存,但热重载失败,请检查服务器日志。', + }); + } + }); + + // ─── Notifications (account up/down → webhook) ─────────────────────────── + // Global channel store (config/notifications.json); per-UIN opt-in lives in + // OneBotConfig.notifications.channelIds. All bearer-gated — channel URLs can + // embed secrets, so none of this is exposed unauthenticated. + app.get('/api/notifications/config', (c) => c.json({ config: loadNotificationsConfig() })); + + app.post('/api/notifications/config', async (c) => { + const declaredLen = Number(c.req.header('content-length')); + + if (Number.isFinite(declaredLen) && declaredLen > 512 * 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); + } + + try { + const config = saveNotificationsConfig(body); + return c.json({ success: true, config }); + } catch (err) { + log.warn( + 'save notifications config failed: %s', + err instanceof Error ? err.message : String(err), + ); + return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500); + } + }); + + app.get('/api/notifications/recent', (c) => { + if (!notificationManager) { + return c.json({ recent: [] }); + } + + const limitRaw = Number(c.req.query('limit')); + const limit = + Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(Math.trunc(limitRaw), 100) : 100; + return c.json({ recent: notificationManager.getRecent(limit) }); + }); + + app.post('/api/notifications/test', async (c) => { + if (!notificationManager) { + return c.json({ success: false, message: '通知子系统不可用' }, 503); + } + + let body: { channelId?: unknown }; + + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + + const channelId = typeof body.channelId === 'string' ? body.channelId : ''; + + if (!channelId) { + return c.json({ success: false, message: '缺少 channelId' }, 400); + } + + const result = await notificationManager.testSend(channelId); + + if (!result.found) { + return c.json({ success: false, message: '渠道不存在' }, 404); + } + + return c.json({ + success: result.ok, + status: result.status, + message: result.ok + ? '测试发送成功' + : `测试发送失败:${result.error ?? (result.status ? `HTTP ${result.status}` : '未知错误')}`, + }); + }); + + // ─── Global deployment config (config/snowluma.json) ───────────────────── + // All-accounts SnowLuma knobs (rkey fallback servers + musicSignUrl). Saving + // section-merges + normalizes server-side, then hot-reloads every instance. + app.get('/api/global-config', (c) => c.json({ config: loadGlobalSettings() })); + + app.post('/api/global-config', async (c) => { + const declaredLen = Number(c.req.header('content-length')); + + if (Number.isFinite(declaredLen) && declaredLen > 512 * 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); + } + + try { + const config = saveGlobalSettings(body); + oneBotManager.reloadGlobalSettings(); + return c.json({ success: true, config }); + } catch (err) { + log.warn( + 'save global config failed: %s', + err instanceof Error ? err.message : String(err), + ); + return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500); + } + }); + + // ─── WebUI customization config (config/ui.json) ───────────────────────── + // Appearance (A) + layout (C). The full config is bearer-gated; only the + // cosmetic appearance subset is exposed unauthenticated for the login page. + app.get('/api/ui', (c) => c.json({ config: loadUiConfig() })); + + app.get('/api/ui/public', (c) => c.json({ appearance: publicAppearance() })); + + app.post('/api/ui', async (c) => { + // Reject oversized bodies before buffering — the normalizer caps individual + // fields (customCss 50KB, per-widget config 4KB) but not the whole payload. + const declaredLen = Number(c.req.header('content-length')); + + if (Number.isFinite(declaredLen) && declaredLen > 256 * 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); + } + + try { + const config = saveUiConfig(body); + return c.json({ success: true, config }); + } catch (err) { + log.warn('save ui.json failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 400); + } + }); + + app.post('/api/ui/background', async (c) => { + // Early reject by Content-Length BEFORE parseBody() buffers the whole + // multipart body into memory — otherwise a multi-GB upload is fully + // materialized before the post-parse size check fires. The slack covers + // the multipart envelope (boundary + part headers); the exact decoded + // size is still enforced below. A chunked request with no Content-Length + // skips this coarse guard, but the endpoint is bearer-gated to the single + // admin, so that residual is acceptable. + const declaredLen = Number(c.req.header('content-length')); + + if (Number.isFinite(declaredLen) && declaredLen > MAX_BACKGROUND_BYTES + 1024 * 1024) { + return c.json({ success: false, message: '图片过大(上限 5MB)' }, 413); + } + + let file: unknown; + + try { + const form = await c.req.parseBody(); + file = form['file']; + } catch { + return c.json({ success: false, message: '上传解析失败' }, 400); + } + + if (!(file instanceof File)) { + return c.json({ success: false, message: '缺少图片文件' }, 400); + } + + if (file.size > MAX_BACKGROUND_BYTES) { + return c.json({ success: false, message: '图片过大(上限 5MB)' }, 413); + } + + const bytes = new Uint8Array(await file.arrayBuffer()); + const mime = sniffImageMime(bytes); + + if (!mime) { + return c.json({ success: false, message: '仅支持 PNG / JPEG / WebP 图片' }, 415); + } + + try { + const config = writeBackgroundImage(bytes, mime); + return c.json({ success: true, config }); + } catch (err) { + log.warn( + 'write background image failed: %s', + err instanceof Error ? err.message : String(err), + ); + return c.json({ success: false, message: '保存图片失败,请检查服务器日志' }, 500); + } + }); + + app.delete('/api/ui/background', (c) => { + try { + const config = clearBackgroundImage(); + return c.json({ success: true, config }); + } catch (err) { + log.warn( + 'clear background image failed: %s', + err instanceof Error ? err.message : String(err), + ); + return c.json({ success: false, message: '删除图片失败' }, 500); + } + }); + + // ─── Static frontend ───────────────────────────────────────────────────── + // Build path is relative to the bundled / dev __dirname. SPA fallback to + // index.html so client-side routes (if any) keep working. + const staticRoot = path.resolve(__dirname, 'client'); + app.use('/*', serveStatic({ root: staticRoot })); + + const indexHtmlPath = path.join(staticRoot, 'index.html'); + app.get('*', (c) => { + // SPA fallback: only for navigations that didn't hit a static asset. + if ( + c.req.path.startsWith('/api/') || + c.req.path.startsWith('/avatar/') || + c.req.path.startsWith('/ui-asset/') + ) { + return c.text('not found', 404); + } + + if (existsSync(indexHtmlPath)) { + const html = readFileSync(indexHtmlPath, 'utf8'); + return c.html(html); + } + + return c.text( + 'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).', + 404, + ); + }); + + const finalPort = await findAvailablePort(desiredPort, { host }); + + if (finalPort !== desiredPort) { + log.warn('port %d is in use, using %d instead', desiredPort, finalPort); + } + + boundPort = finalPort; + + // TLS is an explicit transport promise. Once enabled, an unusable pair must + // abort startup instead of silently exposing the listener over plaintext. + let tlsServe: + | { createServer: typeof createHttpsServer; serverOptions: { cert: Buffer; key: Buffer } } + | undefined; + let scheme = 'http'; + + if (listener.tlsEnabled) { + const tls = requireTlsContext('config'); + tlsServe = { createServer: createHttpsServer, serverOptions: tls }; + scheme = 'https'; + } + + const listeningServer = await new Promise>((resolve) => { + const server = serve( + { fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, + (info) => { + log.info(`listening ${scheme}://${host}:${info.port}`); + resolve(server); + }, + ); + }); + return { + port: finalPort, + async stop() { + connectionDiffLoop?.dispose(); + await new Promise((resolve, reject) => { + listeningServer.close((err) => (err ? reject(err) : resolve())); + }); + }, + }; } diff --git a/packages/core/src/webui/sse-response.ts b/packages/core/src/webui/sse-response.ts index 6f517a8f..94e3448c 100644 --- a/packages/core/src/webui/sse-response.ts +++ b/packages/core/src/webui/sse-response.ts @@ -6,18 +6,18 @@ import { type Context } from 'hono'; * transport lifecycle (heartbeat / teardown / abort / headers). */ export interface SseChannel { - /** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */ - raw(chunk: Uint8Array): void; - /** Encode a string to bytes (shared TextEncoder). */ - encode(s: string): Uint8Array; - /** Convenience: enqueue one `data: \n\n` frame. */ - send(payload: unknown): void; - /** Register a cleanup to run once on teardown (unsubscribe / dispose). */ - onClose(fn: () => void): void; - /** True after teardown — guard sends from late subscription callbacks. */ - isClosed(): boolean; - /** Underlying controller backpressure signal, for `createFramePusher`. */ - desiredSize(): number | null; + /** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */ + raw(chunk: Uint8Array): void; + /** Encode a string to bytes (shared TextEncoder). */ + encode(s: string): Uint8Array; + /** Convenience: enqueue one `data: \n\n` frame. */ + send(payload: unknown): void; + /** Register a cleanup to run once on teardown (unsubscribe / dispose). */ + onClose(fn: () => void): void; + /** True after teardown — guard sends from late subscription callbacks. */ + isClosed(): boolean; + /** Underlying controller backpressure signal, for `createFramePusher`. */ + desiredSize(): number | null; } /** @@ -33,37 +33,71 @@ export interface SseChannel { * teardown-order / header change had to be kept in sync across all three. */ export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response { - const stream = new ReadableStream({ - start(controller) { - const encoder = new TextEncoder(); - let closed = false; - let heartbeat: ReturnType | undefined; - const cleanups: Array<() => void> = []; - const teardown = () => { - if (closed) return; - closed = true; - if (heartbeat) clearInterval(heartbeat); - for (const fn of cleanups) { try { fn(); } catch { /* ignore */ } } - try { controller.close(); } catch { /* ignore */ } - }; - const raw = (chunk: Uint8Array) => { - if (closed) return; - try { controller.enqueue(chunk); } catch { teardown(); } - }; - const ch: SseChannel = { - raw, - encode: (s) => encoder.encode(s), - send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)), - onClose: (fn) => { cleanups.push(fn); }, - isClosed: () => closed, - desiredSize: () => controller.desiredSize, - }; - start(ch); - 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' }, - }); + const stream = new ReadableStream({ + start(controller) { + const encoder = new TextEncoder(); + let closed = false; + let heartbeat: ReturnType | undefined; + const cleanups: Array<() => void> = []; + + const teardown = () => { + if (closed) { + return; + } + + closed = true; + + if (heartbeat) { + clearInterval(heartbeat); + } + + for (const fn of cleanups) { + try { + fn(); + } catch { + /* ignore */ + } + } + + try { + controller.close(); + } catch { + /* ignore */ + } + }; + + const raw = (chunk: Uint8Array) => { + if (closed) { + return; + } + + try { + controller.enqueue(chunk); + } catch { + teardown(); + } + }; + + const ch: SseChannel = { + raw, + encode: (s) => encoder.encode(s), + send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)), + onClose: (fn) => { + cleanups.push(fn); + }, + isClosed: () => closed, + desiredSize: () => controller.desiredSize, + }; + start(ch); + 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', + }, + }); } diff --git a/packages/core/src/webui/state-bus.ts b/packages/core/src/webui/state-bus.ts index 0bfd1544..567bdb76 100644 --- a/packages/core/src/webui/state-bus.ts +++ b/packages/core/src/webui/state-bus.ts @@ -22,46 +22,57 @@ export type StateResource = 'processes' | 'qq-list' | 'connections'; export type StateListener = (resource: StateResource) => void; export class StateBus { - private readonly listeners = new Set(); - private disposed = false; + private readonly listeners = new Set(); + private disposed = false; - /** Subscribe to every publish; returns an unsubscribe handle. Calling - * the handle more than once is a no-op. */ - subscribe(listener: StateListener): () => void { - if (this.disposed) return () => undefined; - this.listeners.add(listener); - let active = true; - return () => { - if (!active) return; - active = false; - this.listeners.delete(listener); - }; - } + /** Subscribe to every publish; returns an unsubscribe handle. Calling + * the handle more than once is a no-op. */ + subscribe(listener: StateListener): () => void { + if (this.disposed) { + return () => undefined; + } - /** Notify every CURRENTLY-subscribed listener that `resource` is stale. - * Iterates a frozen snapshot of the subscriber set so add/remove during - * the emit don't change which listeners see THIS publish; subscriber - * exceptions are isolated and do not abort the fan-out. */ - publish(resource: StateResource): void { - if (this.disposed) return; - // Snapshot the current subscribers — any subscribe()/unsubscribe() - // called by a listener during the fan-out takes effect only for the - // NEXT publish, not this one. - const snapshot = [...this.listeners]; - for (const fn of snapshot) { - try { - fn(resource); - } catch { - // Subscriber-internal failure is its own problem. The bus's job - // is to keep delivery moving — surfacing an error here would - // partially abort the fan-out and create skip-the-listener bugs. - } + this.listeners.add(listener); + let active = true; + + return () => { + if (!active) { + return; + } + + active = false; + this.listeners.delete(listener); + }; } - } - /** Drop every subscriber and refuse future subscribes / publishes. */ - dispose(): void { - this.disposed = true; - this.listeners.clear(); - } + /** Notify every CURRENTLY-subscribed listener that `resource` is stale. + * Iterates a frozen snapshot of the subscriber set so add/remove during + * the emit don't change which listeners see THIS publish; subscriber + * exceptions are isolated and do not abort the fan-out. */ + publish(resource: StateResource): void { + if (this.disposed) { + return; + } + + // Snapshot the current subscribers — any subscribe()/unsubscribe() + // called by a listener during the fan-out takes effect only for the + // NEXT publish, not this one. + const snapshot = [...this.listeners]; + + for (const fn of snapshot) { + try { + fn(resource); + } catch { + // Subscriber-internal failure is its own problem. The bus's job + // is to keep delivery moving — surfacing an error here would + // partially abort the fan-out and create skip-the-listener bugs. + } + } + } + + /** Drop every subscriber and refuse future subscribes / publishes. */ + dispose(): void { + this.disposed = true; + this.listeners.clear(); + } } diff --git a/packages/core/src/webui/state-stream.ts b/packages/core/src/webui/state-stream.ts index b51c4896..768f770b 100644 --- a/packages/core/src/webui/state-stream.ts +++ b/packages/core/src/webui/state-stream.ts @@ -17,112 +17,140 @@ import type { StateBus, StateResource } from './state-bus'; export interface StateStreamFrame { - resource: StateResource; - data: unknown; + resource: StateResource; + data: unknown; } export interface BindStateStreamOptions { - bus: StateBus; - /** Read the current snapshot for one resource. May be sync or async. */ - snapshot: (resource: StateResource) => unknown | Promise; - /** Receive a fresh frame; called once per debounced publish. - * Exceptions are caught — a dead controller must not abort the bus - * subscription or break sibling resources. */ - send: (frame: StateStreamFrame) => void; - /** Coalesce window in milliseconds; default 50. */ - debounceMs?: number; + bus: StateBus; + /** Read the current snapshot for one resource. May be sync or async. */ + snapshot: (resource: StateResource) => unknown | Promise; + /** Receive a fresh frame; called once per debounced publish. + * Exceptions are caught — a dead controller must not abort the bus + * subscription or break sibling resources. */ + send: (frame: StateStreamFrame) => void; + /** Coalesce window in milliseconds; default 50. */ + debounceMs?: number; } export interface StateStreamHandle { - /** Emit one frame per resource using the current snapshot. Use on connect. */ - sendAllInitial(): Promise; - /** Stop subscribing + cancel pending timers. Subsequent bus publishes - * produce nothing through this binding. */ - dispose(): void; + /** Emit one frame per resource using the current snapshot. Use on connect. */ + sendAllInitial(): Promise; + /** Stop subscribing + cancel pending timers. Subsequent bus publishes + * produce nothing through this binding. */ + dispose(): void; } const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connections']; export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle { - const debounceMs = opts.debounceMs ?? 50; - const timers = new Map>(); - // Single-flight per resource: at most one in-flight flush per resource so - // an uneven snapshot latency cannot interleave sends out of order (a slow - // earlier snapshot landing AFTER a later one, leaving the client's last - // observed frame stale). Publishes arriving while a flush is in flight - // mark `pending` and rearm the debounce timer once the flush completes. - const inFlight = new Set(); - const pending = new Set(); - let disposed = false; + const debounceMs = opts.debounceMs ?? 50; + const timers = new Map>(); + // Single-flight per resource: at most one in-flight flush per resource so + // an uneven snapshot latency cannot interleave sends out of order (a slow + // earlier snapshot landing AFTER a later one, leaving the client's last + // observed frame stale). Publishes arriving while a flush is in flight + // mark `pending` and rearm the debounce timer once the flush completes. + const inFlight = new Set(); + const pending = new Set(); + let disposed = false; - const flush = async (resource: StateResource): Promise => { - if (disposed) return; - inFlight.add(resource); - try { - let data: unknown; - try { - data = await opts.snapshot(resource); - } catch { - // Per-resource snapshot failure (e.g. listProcesses threw): skip - // this frame so siblings keep flowing. The next publish for the - // same resource gets a fresh attempt. - return; - } - if (disposed) return; - try { - opts.send({ resource, data }); - } catch { - // Downstream consumer (e.g. closed SSE controller) — same isolation - // contract as snapshot failures. - } - } finally { - inFlight.delete(resource); - // If a publish arrived during the in-flight window, schedule one - // follow-up flush. Re-uses the debounce so a sustained publish - // stream produces at most one frame per (debounceMs + flushLatency), - // not back-to-back frames. - if (!disposed && pending.has(resource)) { - pending.delete(resource); - schedule(resource); - } - } - }; + const flush = async (resource: StateResource): Promise => { + if (disposed) { + return; + } - const schedule = (resource: StateResource): void => { - if (disposed) return; - if (inFlight.has(resource)) { - // Defer to the post-flush re-arm; no new timer until the in-flight - // send completes. This is the load-bearing invariant for ordering. - pending.add(resource); - return; - } - const existing = timers.get(resource); - if (existing) clearTimeout(existing); - const t = setTimeout(() => { - timers.delete(resource); - void flush(resource); - }, debounceMs); - timers.set(resource, t); - }; + inFlight.add(resource); - const unsubscribe = opts.bus.subscribe(schedule); + try { + let data: unknown; - return { - async sendAllInitial(): Promise { - if (disposed) return; - // Fire all three in parallel. Each resource's snapshot is independent - // so a slow listProcesses() doesn't gate qq-list/connections. Each - // call goes through the single-flight gate so a concurrent bus - // publish during this initial fan-out coalesces correctly. - await Promise.all(ALL_RESOURCES.map((r) => flush(r))); - }, - dispose(): void { - if (disposed) return; - disposed = true; - unsubscribe(); - for (const t of timers.values()) clearTimeout(t); - timers.clear(); - pending.clear(); - }, - }; + try { + data = await opts.snapshot(resource); + } catch { + // Per-resource snapshot failure (e.g. listProcesses threw): skip + // this frame so siblings keep flowing. The next publish for the + // same resource gets a fresh attempt. + return; + } + + if (disposed) { + return; + } + + try { + opts.send({ resource, data }); + } catch { + // Downstream consumer (e.g. closed SSE controller) — same isolation + // contract as snapshot failures. + } + } finally { + inFlight.delete(resource); + + // If a publish arrived during the in-flight window, schedule one + // follow-up flush. Re-uses the debounce so a sustained publish + // stream produces at most one frame per (debounceMs + flushLatency), + // not back-to-back frames. + if (!disposed && pending.has(resource)) { + pending.delete(resource); + schedule(resource); + } + } + }; + + const schedule = (resource: StateResource): void => { + if (disposed) { + return; + } + + if (inFlight.has(resource)) { + // Defer to the post-flush re-arm; no new timer until the in-flight + // send completes. This is the load-bearing invariant for ordering. + pending.add(resource); + return; + } + + const existing = timers.get(resource); + + if (existing) { + clearTimeout(existing); + } + + const t = setTimeout(() => { + timers.delete(resource); + void flush(resource); + }, debounceMs); + timers.set(resource, t); + }; + + const unsubscribe = opts.bus.subscribe(schedule); + + return { + async sendAllInitial(): Promise { + if (disposed) { + return; + } + + // Fire all three in parallel. Each resource's snapshot is independent + // so a slow listProcesses() doesn't gate qq-list/connections. Each + // call goes through the single-flight gate so a concurrent bus + // publish during this initial fan-out coalesces correctly. + await Promise.all(ALL_RESOURCES.map((r) => flush(r))); + }, + dispose(): void { + if (disposed) { + return; + } + + disposed = true; + unsubscribe(); + + for (const t of timers.values()) { + clearTimeout(t); + } + + timers.clear(); + pending.clear(); + }, + }; } diff --git a/packages/core/src/webui/state-wiring.ts b/packages/core/src/webui/state-wiring.ts index 276a9874..83198398 100644 --- a/packages/core/src/webui/state-wiring.ts +++ b/packages/core/src/webui/state-wiring.ts @@ -23,52 +23,58 @@ import { StateBus } from './state-bus'; import type { BridgeManager } from '../bridge/manager'; export interface StateWiring { - /** The bus the SSE handler subscribes to. */ - readonly bus: StateBus; - /** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */ - onSessionsChanged: () => void; - /** Hook into a BridgeManager so its session edges publish 'qq-list' and - * 'connections'. Can be called at most once per wiring (subsequent calls - * add duplicate listeners). */ - bindBridgeManager(bm: BridgeManager): void; - /** Drop every listener + neuter the bus so further publishes do nothing. */ - dispose(): void; + /** The bus the SSE handler subscribes to. */ + readonly bus: StateBus; + /** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */ + onSessionsChanged: () => void; + /** Hook into a BridgeManager so its session edges publish 'qq-list' and + * 'connections'. Can be called at most once per wiring (subsequent calls + * add duplicate listeners). */ + bindBridgeManager(bm: BridgeManager): void; + /** Drop every listener + neuter the bus so further publishes do nothing. */ + dispose(): void; } export function createStateWiring(): StateWiring { - const bus = new StateBus(); - let disposed = false; + const bus = new StateBus(); + let disposed = false; - const publish = (resource: Parameters[0]): void => { - if (disposed) return; - bus.publish(resource); - }; + const publish = (resource: Parameters[0]): void => { + if (disposed) { + return; + } - return { - bus, - onSessionsChanged: () => publish('processes'), - bindBridgeManager(bm: BridgeManager): void { - // Account appeared: the qq-list response gains an entry and the - // connections response gains the new account's adapter row. Two - // distinct resource invalidations, in source-of-truth order - // (account exists → only then can adapters be enumerated for it). - bm.addSessionStartedListener(() => { - publish('qq-list'); - publish('connections'); - }); - // Account disappeared: same two resources shrink, same order so a - // racy WebUI receiving both events independently sees the qq-list - // shrink before it tries to render connections for a uin that's - // about to vanish. - bm.addSessionClosedListener(() => { - publish('qq-list'); - publish('connections'); - }); - }, - dispose(): void { - if (disposed) return; - disposed = true; - bus.dispose(); - }, - }; + bus.publish(resource); + }; + + return { + bus, + onSessionsChanged: () => publish('processes'), + bindBridgeManager(bm: BridgeManager): void { + // Account appeared: the qq-list response gains an entry and the + // connections response gains the new account's adapter row. Two + // distinct resource invalidations, in source-of-truth order + // (account exists → only then can adapters be enumerated for it). + bm.addSessionStartedListener(() => { + publish('qq-list'); + publish('connections'); + }); + // Account disappeared: same two resources shrink, same order so a + // racy WebUI receiving both events independently sees the qq-list + // shrink before it tries to render connections for a uin that's + // about to vanish. + bm.addSessionClosedListener(() => { + publish('qq-list'); + publish('connections'); + }); + }, + dispose(): void { + if (disposed) { + return; + } + + disposed = true; + bus.dispose(); + }, + }; } diff --git a/packages/core/src/webui/storage-management.ts b/packages/core/src/webui/storage-management.ts index 4eb4742b..d7f8e83b 100644 --- a/packages/core/src/webui/storage-management.ts +++ b/packages/core/src/webui/storage-management.ts @@ -1,333 +1,387 @@ import fs from 'node:fs'; import path from 'node:path'; -import type { - LogCleanupResult, - LogStorageStatus, -} from '@snowluma/common/log-file-transport'; +import type { LogCleanupResult, LogStorageStatus } from '@snowluma/common/log-file-transport'; import { isRealUin } from '@snowluma/common/uin'; export interface TemporaryStorageSnapshot { - totalBytes: number; - fileCount: number; - activeItemCount: number; + totalBytes: number; + fileCount: number; + activeItemCount: number; } export interface TemporaryCleanupResult { - deletedFiles: number; - freedBytes: number; - skippedActiveItems: number; - failures: Array<{ item: string; message: string }>; + deletedFiles: number; + freedBytes: number; + skippedActiveItems: number; + failures: Array<{ item: string; message: string }>; } export interface TemporaryStorageAdapter { - snapshot(): TemporaryStorageSnapshot; - clearInactive(): TemporaryCleanupResult; + snapshot(): TemporaryStorageSnapshot; + clearInactive(): TemporaryCleanupResult; } export interface OnlineStorageAccount { - uin: string; - nickname: string; + uin: string; + nickname: string; } export interface AccountStorageSnapshot { - uin: string; - nickname?: string; - online: boolean; - messagesBytes: number; - mediaBytes: number; - reactionsBytes: number; - totalBytes: number; + uin: string; + nickname?: string; + online: boolean; + messagesBytes: number; + mediaBytes: number; + reactionsBytes: number; + totalBytes: number; } export type PublicLogStorageStatus = Omit; export function publicLogStorageStatus(status: LogStorageStatus): PublicLogStorageStatus { - const { directory, ...publicStatus } = status; - if (!publicStatus.lastError) return publicStatus; - return { - ...publicStatus, - lastError: redactFilesystemPath(publicStatus.lastError, directory, '[日志目录]'), - }; + const { directory, ...publicStatus } = status; + + if (!publicStatus.lastError) { + return publicStatus; + } + + return { + ...publicStatus, + lastError: redactFilesystemPath(publicStatus.lastError, directory, '[日志目录]'), + }; } export interface PublicLogCleanupResult extends Omit { - status: PublicLogStorageStatus; + status: PublicLogStorageStatus; } export interface StorageSnapshot { - logs: PublicLogStorageStatus; - temporary: TemporaryStorageSnapshot; - accounts: AccountStorageSnapshot[]; - totals: { - logsBytes: number; - temporaryBytes: number; - accountDataBytes: number; - managedBytes: number; - }; + logs: PublicLogStorageStatus; + temporary: TemporaryStorageSnapshot; + accounts: AccountStorageSnapshot[]; + totals: { + logsBytes: number; + temporaryBytes: number; + accountDataBytes: number; + managedBytes: number; + }; } export type AccountStorageCategory = 'messages' | 'media' | 'reactions'; export interface AccountDataCleanupResult { - category: AccountStorageCategory; - uins: string[]; - deletedFiles: number; - freedBytes: number; - failures: Array<{ uin: string; file: string; message: string }>; + category: AccountStorageCategory; + uins: string[]; + deletedFiles: number; + freedBytes: number; + failures: Array<{ uin: string; file: string; message: string }>; } export class StorageManagementInputError extends Error { - constructor(message: string) { - super(message); - this.name = 'StorageManagementInputError'; - } + constructor(message: string) { + super(message); + this.name = 'StorageManagementInputError'; + } } export class StorageAccountOnlineError extends Error { - constructor(readonly uins: string[]) { - super(`account data cleanup requires offline accounts: ${uins.join(', ')}`); - this.name = 'StorageAccountOnlineError'; - } + constructor(readonly uins: string[]) { + super(`account data cleanup requires offline accounts: ${uins.join(', ')}`); + this.name = 'StorageAccountOnlineError'; + } } export interface StorageManagementDependencies { - dataDir: string; - getLogStatus(): LogStorageStatus; - clearLogs(): Promise; - temporary: TemporaryStorageAdapter; - listOnlineAccounts(): OnlineStorageAccount[]; + dataDir: string; + getLogStatus(): LogStorageStatus; + clearLogs(): Promise; + temporary: TemporaryStorageAdapter; + listOnlineAccounts(): OnlineStorageAccount[]; } const DATABASE_FILES = { - messages: ['messages.db', 'messages.db-wal', 'messages.db-shm', 'messages.db-journal'], - media: ['media.db', 'media.db-wal', 'media.db-shm', 'media.db-journal'], - reactions: ['reactions.db', 'reactions.db-wal', 'reactions.db-shm', 'reactions.db-journal'], + messages: ['messages.db', 'messages.db-wal', 'messages.db-shm', 'messages.db-journal'], + media: ['media.db', 'media.db-wal', 'media.db-shm', 'media.db-journal'], + reactions: ['reactions.db', 'reactions.db-wal', 'reactions.db-shm', 'reactions.db-journal'], } as const; export class StorageManagementService { - constructor(private readonly deps: StorageManagementDependencies) {} + constructor(private readonly deps: StorageManagementDependencies) {} - snapshot(): StorageSnapshot { - const logStatus = this.deps.getLogStatus(); - const logs = publicLogStorageStatus(logStatus); - const temporary = this.deps.temporary.snapshot(); - const accounts = this.accountSnapshots(); - const accountDataBytes = accounts.reduce((sum, account) => sum + account.totalBytes, 0); - return { - logs, - temporary, - accounts, - totals: { - logsBytes: logs.totalBytes, - temporaryBytes: temporary.totalBytes, - accountDataBytes, - managedBytes: logs.totalBytes + temporary.totalBytes + accountDataBytes, - }, - }; - } - - async clearLogs(): Promise { - const result = await this.deps.clearLogs(); - return { - ...result, - failures: result.failures.map((failure) => ({ - ...failure, - message: redactFilesystemPath( - failure.message, - result.status.directory, - '[日志目录]', - ), - })), - status: publicLogStorageStatus(result.status), - }; - } - - clearTemporary(): TemporaryCleanupResult { - return this.deps.temporary.clearInactive(); - } - - clearAccountData(category: string, uin: string): AccountDataCleanupResult { - const validatedCategory = validateAccountStorageCategory(category); - if (!isRealUin(uin)) { - throw new StorageManagementInputError(`invalid UIN: ${uin}`); - } - return this.clearAccountDataForUins(validatedCategory, [uin]); - } - - clearAllAccountData(category: string): AccountDataCleanupResult { - const validatedCategory = validateAccountStorageCategory(category); - const uins = listDirectoryNames(this.deps.dataDir) - .filter((name) => isRealUin(name)) - .sort((a, b) => Number(a) - Number(b)); - return this.clearAccountDataForUins(validatedCategory, uins); - } - - private clearAccountDataForUins( - category: AccountStorageCategory, - uins: string[], - ): AccountDataCleanupResult { - const hasManagedRoot = assertManagedDataRootOrMissing(this.deps.dataDir); - const onlineUins = new Set( - this.deps.listOnlineAccounts() - .map((account) => account.uin) - .filter((uin) => isRealUin(uin)), - ); - const blockedUins = uins.filter((uin) => onlineUins.has(uin)); - if (blockedUins.length > 0) throw new StorageAccountOnlineError(blockedUins); - - const failures: AccountDataCleanupResult['failures'] = []; - let deletedFiles = 0; - let freedBytes = 0; - if (!hasManagedRoot) { - return { category, uins, deletedFiles, freedBytes, failures }; - } - for (const uin of uins) { - const dir = path.join(this.deps.dataDir, uin); - if (!isManagedDirectory(dir)) continue; - for (const name of DATABASE_FILES[category]) { - const filePath = path.join(dir, name); - let bytes: number; - try { - const stat = fs.lstatSync(filePath); - if (!stat.isFile()) continue; - bytes = stat.size; - } catch (error) { - if (isMissing(error)) continue; - failures.push({ - uin, - file: name, - message: redactFilesystemPath( - errorMessage(error), - filePath, - '[账号数据库]', - ), - }); - continue; - } - try { - fs.unlinkSync(filePath); - deletedFiles += 1; - freedBytes += bytes; - } catch (error) { - if (isMissing(error)) continue; - failures.push({ - uin, - file: name, - message: redactFilesystemPath( - errorMessage(error), - filePath, - '[账号数据库]', - ), - }); - } - } - } - return { category, uins, deletedFiles, freedBytes, failures }; - } - - private accountSnapshots(): AccountStorageSnapshot[] { - const online = new Map( - this.deps.listOnlineAccounts() - .filter((account) => isRealUin(account.uin)) - .map((account) => [account.uin, account.nickname]), - ); - const uins = new Set(online.keys()); - for (const name of listDirectoryNames(this.deps.dataDir)) { - if (isRealUin(name)) uins.add(name); - } - - return [...uins] - .sort((a, b) => Number(a) - Number(b)) - .map((uin) => { - const dir = path.join(this.deps.dataDir, uin); - const managedDirectory = isManagedDirectory(dir); - const messagesBytes = managedDirectory - ? sumAllowlistedFiles(dir, DATABASE_FILES.messages) - : 0; - const mediaBytes = managedDirectory - ? sumAllowlistedFiles(dir, DATABASE_FILES.media) - : 0; - const reactionsBytes = managedDirectory - ? sumAllowlistedFiles(dir, DATABASE_FILES.reactions) - : 0; - const nickname = online.get(uin); + snapshot(): StorageSnapshot { + const logStatus = this.deps.getLogStatus(); + const logs = publicLogStorageStatus(logStatus); + const temporary = this.deps.temporary.snapshot(); + const accounts = this.accountSnapshots(); + const accountDataBytes = accounts.reduce((sum, account) => sum + account.totalBytes, 0); return { - uin, - ...(nickname ? { nickname } : {}), - online: online.has(uin), - messagesBytes, - mediaBytes, - reactionsBytes, - totalBytes: messagesBytes + mediaBytes + reactionsBytes, + logs, + temporary, + accounts, + totals: { + logsBytes: logs.totalBytes, + temporaryBytes: temporary.totalBytes, + accountDataBytes, + managedBytes: logs.totalBytes + temporary.totalBytes + accountDataBytes, + }, }; - }); - } + } + + async clearLogs(): Promise { + const result = await this.deps.clearLogs(); + return { + ...result, + failures: result.failures.map((failure) => ({ + ...failure, + message: redactFilesystemPath( + failure.message, + result.status.directory, + '[日志目录]', + ), + })), + status: publicLogStorageStatus(result.status), + }; + } + + clearTemporary(): TemporaryCleanupResult { + return this.deps.temporary.clearInactive(); + } + + clearAccountData(category: string, uin: string): AccountDataCleanupResult { + const validatedCategory = validateAccountStorageCategory(category); + + if (!isRealUin(uin)) { + throw new StorageManagementInputError(`invalid UIN: ${uin}`); + } + + return this.clearAccountDataForUins(validatedCategory, [uin]); + } + + clearAllAccountData(category: string): AccountDataCleanupResult { + const validatedCategory = validateAccountStorageCategory(category); + const uins = listDirectoryNames(this.deps.dataDir) + .filter((name) => isRealUin(name)) + .sort((a, b) => Number(a) - Number(b)); + return this.clearAccountDataForUins(validatedCategory, uins); + } + + private clearAccountDataForUins( + category: AccountStorageCategory, + uins: string[], + ): AccountDataCleanupResult { + const hasManagedRoot = assertManagedDataRootOrMissing(this.deps.dataDir); + const onlineUins = new Set( + this.deps + .listOnlineAccounts() + .map((account) => account.uin) + .filter((uin) => isRealUin(uin)), + ); + const blockedUins = uins.filter((uin) => onlineUins.has(uin)); + + if (blockedUins.length > 0) { + throw new StorageAccountOnlineError(blockedUins); + } + + const failures: AccountDataCleanupResult['failures'] = []; + let deletedFiles = 0; + let freedBytes = 0; + + if (!hasManagedRoot) { + return { category, uins, deletedFiles, freedBytes, failures }; + } + + for (const uin of uins) { + const dir = path.join(this.deps.dataDir, uin); + + if (!isManagedDirectory(dir)) { + continue; + } + + for (const name of DATABASE_FILES[category]) { + const filePath = path.join(dir, name); + let bytes: number; + + try { + const stat = fs.lstatSync(filePath); + + if (!stat.isFile()) { + continue; + } + + bytes = stat.size; + } catch (error) { + if (isMissing(error)) { + continue; + } + + failures.push({ + uin, + file: name, + message: redactFilesystemPath( + errorMessage(error), + filePath, + '[账号数据库]', + ), + }); + continue; + } + + try { + fs.unlinkSync(filePath); + deletedFiles += 1; + freedBytes += bytes; + } catch (error) { + if (isMissing(error)) { + continue; + } + + failures.push({ + uin, + file: name, + message: redactFilesystemPath( + errorMessage(error), + filePath, + '[账号数据库]', + ), + }); + } + } + } + + return { category, uins, deletedFiles, freedBytes, failures }; + } + + private accountSnapshots(): AccountStorageSnapshot[] { + const online = new Map( + this.deps + .listOnlineAccounts() + .filter((account) => isRealUin(account.uin)) + .map((account) => [account.uin, account.nickname]), + ); + const uins = new Set(online.keys()); + + for (const name of listDirectoryNames(this.deps.dataDir)) { + if (isRealUin(name)) { + uins.add(name); + } + } + + return [...uins] + .sort((a, b) => Number(a) - Number(b)) + .map((uin) => { + const dir = path.join(this.deps.dataDir, uin); + const managedDirectory = isManagedDirectory(dir); + const messagesBytes = managedDirectory + ? sumAllowlistedFiles(dir, DATABASE_FILES.messages) + : 0; + const mediaBytes = managedDirectory + ? sumAllowlistedFiles(dir, DATABASE_FILES.media) + : 0; + const reactionsBytes = managedDirectory + ? sumAllowlistedFiles(dir, DATABASE_FILES.reactions) + : 0; + const nickname = online.get(uin); + return { + uin, + ...(nickname ? { nickname } : {}), + online: online.has(uin), + messagesBytes, + mediaBytes, + reactionsBytes, + totalBytes: messagesBytes + mediaBytes + reactionsBytes, + }; + }); + } } function listDirectoryNames(dir: string): string[] { - if (!assertManagedDataRootOrMissing(dir)) return []; - try { - return fs.readdirSync(dir, { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) - .map((entry) => entry.name); - } catch (error) { - if (isMissing(error)) return []; - throw error; - } + if (!assertManagedDataRootOrMissing(dir)) { + return []; + } + + try { + return fs + .readdirSync(dir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name); + } catch (error) { + if (isMissing(error)) { + return []; + } + + throw error; + } } function assertManagedDataRootOrMissing(dir: string): boolean { - try { - const stat = fs.lstatSync(dir); - if (!stat.isDirectory()) { - throw new Error('managed data root must be a real directory'); + try { + const stat = fs.lstatSync(dir); + + if (!stat.isDirectory()) { + throw new Error('managed data root must be a real directory'); + } + + return true; + } catch (error) { + if (isMissing(error)) { + return false; + } + + throw error; } - return true; - } catch (error) { - if (isMissing(error)) return false; - throw error; - } } function sumAllowlistedFiles(dir: string, names: readonly string[]): number { - let total = 0; - for (const name of names) { - const filePath = path.join(dir, name); - try { - const stat = fs.lstatSync(filePath); - if (stat.isFile()) total += stat.size; - } catch (error) { - if (!isMissing(error)) throw error; + let total = 0; + + for (const name of names) { + const filePath = path.join(dir, name); + + try { + const stat = fs.lstatSync(filePath); + + if (stat.isFile()) { + total += stat.size; + } + } catch (error) { + if (!isMissing(error)) { + throw error; + } + } } - } - return total; + + return total; } function isMissing(error: unknown): boolean { - return error instanceof Error && 'code' in error && error.code === 'ENOENT'; + return error instanceof Error && 'code' in error && error.code === 'ENOENT'; } function isManagedDirectory(dir: string): boolean { - try { - return fs.lstatSync(dir).isDirectory(); - } catch (error) { - if (isMissing(error)) return false; - throw error; - } + try { + return fs.lstatSync(dir).isDirectory(); + } catch (error) { + if (isMissing(error)) { + return false; + } + + throw error; + } } function validateAccountStorageCategory(value: string): AccountStorageCategory { - if (value === 'messages' || value === 'media' || value === 'reactions') return value; - throw new StorageManagementInputError(`unsupported account storage category: ${value}`); + if (value === 'messages' || value === 'media' || value === 'reactions') { + return value; + } + + throw new StorageManagementInputError(`unsupported account storage category: ${value}`); } function errorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error); + return error instanceof Error ? error.message : String(error); } function redactFilesystemPath(message: string, filePath: string, label: string): string { - const absolute = path.resolve(filePath); - return message - .split(absolute).join(label) - .split(filePath).join(label); + const absolute = path.resolve(filePath); + return message.split(absolute).join(label).split(filePath).join(label); } diff --git a/packages/core/src/webui/storage-routes.ts b/packages/core/src/webui/storage-routes.ts index d1824c90..36b2cc39 100644 --- a/packages/core/src/webui/storage-routes.ts +++ b/packages/core/src/webui/storage-routes.ts @@ -1,317 +1,373 @@ import { isRealUin } from '@snowluma/common/uin'; import type { Hono } from 'hono'; import { - StorageAccountOnlineError, - StorageManagementInputError, - type AccountDataCleanupResult, - type AccountStorageCategory, - type PublicLogCleanupResult, - type StorageManagementService, - type StorageSnapshot, - type TemporaryCleanupResult, + StorageAccountOnlineError, + StorageManagementInputError, + type AccountDataCleanupResult, + type AccountStorageCategory, + type PublicLogCleanupResult, + type StorageManagementService, + type StorageSnapshot, + type TemporaryCleanupResult, } from './storage-management'; import { - StorageSettingsInputError, - StorageSettingsLockedError, - StorageSettingsTransactionError, - type LogStorageSettingsManager, + StorageSettingsInputError, + StorageSettingsLockedError, + StorageSettingsTransactionError, + type LogStorageSettingsManager, } from './storage-settings'; export const ALL_ACCOUNTS_CONFIRMATION = '清理全部账号'; type StorageCleanupRequest = - | { scope: 'logs' } - | { scope: 'temporary' } - | { scope: 'account'; category: AccountStorageCategory; uin: string } - | { - scope: 'allAccounts'; - category: AccountStorageCategory; - confirmation: typeof ALL_ACCOUNTS_CONFIRMATION; - }; + | { scope: 'logs' } + | { scope: 'temporary' } + | { scope: 'account'; category: AccountStorageCategory; uin: string } + | { + scope: 'allAccounts'; + category: AccountStorageCategory; + confirmation: typeof ALL_ACCOUNTS_CONFIRMATION; + }; type StorageCleanupResult = - | PublicLogCleanupResult - | TemporaryCleanupResult - | AccountDataCleanupResult; + PublicLogCleanupResult | TemporaryCleanupResult | AccountDataCleanupResult; export interface StorageCleanupAuditEvent { - scope: StorageCleanupRequest['scope']; - accountScope: 'global' | 'single' | 'all'; - category?: AccountStorageCategory; - uin?: string; - deletedFiles: number; - freedBytes: number; - failureCount: number; + scope: StorageCleanupRequest['scope']; + accountScope: 'global' | 'single' | 'all'; + category?: AccountStorageCategory; + uin?: string; + deletedFiles: number; + freedBytes: number; + failureCount: number; } export interface LastStorageCleanup extends StorageCleanupAuditEvent { - at: string; - skippedActiveItems?: number; - failures: Array<{ item: string; message: string }>; + at: string; + skippedActiveItems?: number; + failures: Array<{ item: string; message: string }>; } export interface StorageRouteDependencies { - storage: Pick< - StorageManagementService, - 'snapshot' - | 'clearLogs' - | 'clearTemporary' - | 'clearAccountData' - | 'clearAllAccountData' - >; - settings: Pick; - audit(event: StorageCleanupAuditEvent): void; - reportError(operation: string, error: unknown): void; - now?: () => Date; + storage: Pick< + StorageManagementService, + 'snapshot' | 'clearLogs' | 'clearTemporary' | 'clearAccountData' | 'clearAllAccountData' + >; + settings: Pick; + audit(event: StorageCleanupAuditEvent): void; + reportError(operation: string, error: unknown): void; + now?: () => Date; } export function registerStorageRoutes(app: Hono, deps: StorageRouteDependencies): void { - let lastCleanup: LastStorageCleanup | null = null; - let mutationQueue: Promise = Promise.resolve(); - const serializeMutation = (operation: () => Promise): Promise => { - const result = mutationQueue.then(operation); - mutationQueue = result.then( - () => undefined, - () => undefined, - ); - return result; - }; + let lastCleanup: LastStorageCleanup | null = null; + let mutationQueue: Promise = Promise.resolve(); - app.get('/api/system/storage', (c) => { - try { - return c.json({ - settings: deps.settings.read(), - snapshot: deps.storage.snapshot(), - lastCleanup, - }); - } catch (error) { - deps.reportError('read storage snapshot', error); - return c.json({ success: false, message: '读取存储信息失败,请检查服务器日志' }, 500); - } - }); - - app.post('/api/system/storage/settings', async (c) => { - let body: unknown; - try { - body = await c.req.json(); - } catch { - return c.json({ success: false, message: '请求格式错误' }, 400); - } - - let result: Awaited>; - try { - result = await serializeMutation(() => deps.settings.update(body)); - } catch (error) { - if (error instanceof StorageSettingsInputError) { - return c.json({ success: false, message: error.message }, 400); - } - if (error instanceof StorageSettingsLockedError) { - return c.json({ - success: false, - message: '这些设置已由环境变量锁定', - lockedFields: error.fields, - }, 409); - } - deps.reportError('update log storage settings', error); - if (error instanceof StorageSettingsTransactionError) { - deps.reportError('update log storage settings operation', error.operationError); - error.rollbackErrors.forEach((rollbackError, index) => { - deps.reportError( - `rollback log storage settings step=${String(index + 1)}`, - rollbackError, - ); - }); - return c.json({ - success: false, - message: error.rollbackErrors.length > 0 - ? '保存失败且回滚不完整,请立即检查服务器日志' - : '保存失败,原设置已恢复', - }, 500); - } - return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500); - } - - try { - return c.json({ - success: true, - settings: result.settings, - status: result.status, - snapshot: deps.storage.snapshot(), - }); - } catch (error) { - deps.reportError('refresh storage snapshot after settings update', error); - return c.json({ - success: false, - message: '设置已生效,但刷新存储统计失败,请检查服务器日志', - settings: result.settings, - status: result.status, - }, 500); - } - }); - - app.post('/api/system/storage/cleanup', async (c) => { - let body: unknown; - try { - body = await c.req.json(); - } catch { - return c.json({ success: false, message: '请求格式错误' }, 400); - } - - let request: StorageCleanupRequest; - try { - request = parseCleanupRequest(body); - } catch (error) { - const message = error instanceof Error ? error.message : '请求格式错误'; - return c.json({ success: false, message }, 400); - } - - let cleanup: StorageCleanupResult; - try { - cleanup = await serializeMutation(() => executeCleanup(deps.storage, request)); - } catch (error) { - if (error instanceof StorageAccountOnlineError) { - return c.json({ - success: false, - message: '账号在线,必须先下线后才能清理数据库', - onlineUins: error.uins, - }, 409); - } - if (error instanceof StorageManagementInputError) { - return c.json({ success: false, message: error.message }, 400); - } - deps.reportError(`clean storage scope=${request.scope}`, error); - return c.json({ success: false, message: '清理失败,请检查服务器日志' }, 500); - } - - const auditEvent: StorageCleanupAuditEvent = { - scope: request.scope, - accountScope: accountScope(request), - ...('category' in request ? { category: request.category } : {}), - ...(request.scope === 'account' ? { uin: request.uin } : {}), - deletedFiles: cleanup.deletedFiles, - freedBytes: cleanup.freedBytes, - failureCount: cleanup.failures.length, - }; - deps.audit(auditEvent); - for (const failure of cleanup.failures) { - deps.reportError( - `clean storage scope=${request.scope} item=${cleanupFailureItem(failure)}`, - new Error(failure.message), - ); - } - lastCleanup = { - at: (deps.now?.() ?? new Date()).toISOString(), - ...auditEvent, - ...('skippedActiveItems' in cleanup - ? { skippedActiveItems: cleanup.skippedActiveItems } - : {}), - failures: cleanup.failures.map((failure) => ({ - item: cleanupFailureItem(failure), - message: failure.message, - })), + const serializeMutation = (operation: () => Promise): Promise => { + const result = mutationQueue.then(operation); + mutationQueue = result.then( + () => undefined, + () => undefined, + ); + return result; }; - let snapshot: StorageSnapshot; - try { - snapshot = deps.storage.snapshot(); - } catch (error) { - deps.reportError(`refresh storage snapshot after cleanup scope=${request.scope}`, error); - return c.json({ - success: false, - message: '清理已执行,但刷新存储统计失败,请检查服务器日志', - scope: request.scope, - cleanup, - lastCleanup, - }, 500); - } + app.get('/api/system/storage', (c) => { + try { + return c.json({ + settings: deps.settings.read(), + snapshot: deps.storage.snapshot(), + lastCleanup, + }); + } catch (error) { + deps.reportError('read storage snapshot', error); + return c.json({ success: false, message: '读取存储信息失败,请检查服务器日志' }, 500); + } + }); - const success = cleanup.failures.length === 0; - return c.json({ - success, - ...(success ? {} : { message: '部分文件清理失败,请检查失败明细' }), - scope: request.scope, - cleanup, - snapshot, - lastCleanup, - }, success ? 200 : 500); - }); + app.post('/api/system/storage/settings', async (c) => { + let body: unknown; + + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + + let result: Awaited>; + + try { + result = await serializeMutation(() => deps.settings.update(body)); + } catch (error) { + if (error instanceof StorageSettingsInputError) { + return c.json({ success: false, message: error.message }, 400); + } + + if (error instanceof StorageSettingsLockedError) { + return c.json( + { + success: false, + message: '这些设置已由环境变量锁定', + lockedFields: error.fields, + }, + 409, + ); + } + + deps.reportError('update log storage settings', error); + + if (error instanceof StorageSettingsTransactionError) { + deps.reportError('update log storage settings operation', error.operationError); + error.rollbackErrors.forEach((rollbackError, index) => { + deps.reportError( + `rollback log storage settings step=${String(index + 1)}`, + rollbackError, + ); + }); + return c.json( + { + success: false, + message: + error.rollbackErrors.length > 0 + ? '保存失败且回滚不完整,请立即检查服务器日志' + : '保存失败,原设置已恢复', + }, + 500, + ); + } + + return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500); + } + + try { + return c.json({ + success: true, + settings: result.settings, + status: result.status, + snapshot: deps.storage.snapshot(), + }); + } catch (error) { + deps.reportError('refresh storage snapshot after settings update', error); + return c.json( + { + success: false, + message: '设置已生效,但刷新存储统计失败,请检查服务器日志', + settings: result.settings, + status: result.status, + }, + 500, + ); + } + }); + + app.post('/api/system/storage/cleanup', async (c) => { + let body: unknown; + + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + + let request: StorageCleanupRequest; + + try { + request = parseCleanupRequest(body); + } catch (error) { + const message = error instanceof Error ? error.message : '请求格式错误'; + return c.json({ success: false, message }, 400); + } + + let cleanup: StorageCleanupResult; + + try { + cleanup = await serializeMutation(() => executeCleanup(deps.storage, request)); + } catch (error) { + if (error instanceof StorageAccountOnlineError) { + return c.json( + { + success: false, + message: '账号在线,必须先下线后才能清理数据库', + onlineUins: error.uins, + }, + 409, + ); + } + + if (error instanceof StorageManagementInputError) { + return c.json({ success: false, message: error.message }, 400); + } + + deps.reportError(`clean storage scope=${request.scope}`, error); + return c.json({ success: false, message: '清理失败,请检查服务器日志' }, 500); + } + + const auditEvent: StorageCleanupAuditEvent = { + scope: request.scope, + accountScope: accountScope(request), + ...('category' in request ? { category: request.category } : {}), + ...(request.scope === 'account' ? { uin: request.uin } : {}), + deletedFiles: cleanup.deletedFiles, + freedBytes: cleanup.freedBytes, + failureCount: cleanup.failures.length, + }; + deps.audit(auditEvent); + + for (const failure of cleanup.failures) { + deps.reportError( + `clean storage scope=${request.scope} item=${cleanupFailureItem(failure)}`, + new Error(failure.message), + ); + } + + lastCleanup = { + at: (deps.now?.() ?? new Date()).toISOString(), + ...auditEvent, + ...('skippedActiveItems' in cleanup + ? { skippedActiveItems: cleanup.skippedActiveItems } + : {}), + failures: cleanup.failures.map((failure) => ({ + item: cleanupFailureItem(failure), + message: failure.message, + })), + }; + + let snapshot: StorageSnapshot; + + try { + snapshot = deps.storage.snapshot(); + } catch (error) { + deps.reportError( + `refresh storage snapshot after cleanup scope=${request.scope}`, + error, + ); + return c.json( + { + success: false, + message: '清理已执行,但刷新存储统计失败,请检查服务器日志', + scope: request.scope, + cleanup, + lastCleanup, + }, + 500, + ); + } + + const success = cleanup.failures.length === 0; + return c.json( + { + success, + ...(success ? {} : { message: '部分文件清理失败,请检查失败明细' }), + scope: request.scope, + cleanup, + snapshot, + lastCleanup, + }, + success ? 200 : 500, + ); + }); } function parseCleanupRequest(body: unknown): StorageCleanupRequest { - if (!isObject(body) || typeof body.scope !== 'string') { - throw new StorageManagementInputError('scope is required'); - } - - if (body.scope === 'logs' || body.scope === 'temporary') { - assertExactKeys(body, ['scope']); - return { scope: body.scope }; - } - - if (body.scope === 'account') { - assertExactKeys(body, ['scope', 'category', 'uin']); - const category = parseCategory(body.category); - if (typeof body.uin !== 'string' || !isRealUin(body.uin)) { - throw new StorageManagementInputError('invalid UIN'); + if (!isObject(body) || typeof body.scope !== 'string') { + throw new StorageManagementInputError('scope is required'); } - return { scope: 'account', category, uin: body.uin }; - } - if (body.scope === 'allAccounts') { - assertExactKeys(body, ['scope', 'category', 'confirmation']); - const category = parseCategory(body.category); - if (body.confirmation !== ALL_ACCOUNTS_CONFIRMATION) { - throw new StorageManagementInputError('all-account cleanup requires confirmation'); + if (body.scope === 'logs' || body.scope === 'temporary') { + assertExactKeys(body, ['scope']); + return { scope: body.scope }; } - return { - scope: 'allAccounts', - category, - confirmation: ALL_ACCOUNTS_CONFIRMATION, - }; - } - throw new StorageManagementInputError(`unsupported cleanup scope: ${body.scope}`); + if (body.scope === 'account') { + assertExactKeys(body, ['scope', 'category', 'uin']); + const category = parseCategory(body.category); + + if (typeof body.uin !== 'string' || !isRealUin(body.uin)) { + throw new StorageManagementInputError('invalid UIN'); + } + + return { scope: 'account', category, uin: body.uin }; + } + + if (body.scope === 'allAccounts') { + assertExactKeys(body, ['scope', 'category', 'confirmation']); + const category = parseCategory(body.category); + + if (body.confirmation !== ALL_ACCOUNTS_CONFIRMATION) { + throw new StorageManagementInputError('all-account cleanup requires confirmation'); + } + + return { + scope: 'allAccounts', + category, + confirmation: ALL_ACCOUNTS_CONFIRMATION, + }; + } + + throw new StorageManagementInputError(`unsupported cleanup scope: ${body.scope}`); } async function executeCleanup( - storage: StorageRouteDependencies['storage'], - request: StorageCleanupRequest, + storage: StorageRouteDependencies['storage'], + request: StorageCleanupRequest, ): Promise { - if (request.scope === 'logs') return storage.clearLogs(); - if (request.scope === 'temporary') return storage.clearTemporary(); - if (request.scope === 'account') { - return storage.clearAccountData(request.category, request.uin); - } - return storage.clearAllAccountData(request.category); + if (request.scope === 'logs') { + return storage.clearLogs(); + } + + if (request.scope === 'temporary') { + return storage.clearTemporary(); + } + + if (request.scope === 'account') { + return storage.clearAccountData(request.category, request.uin); + } + + return storage.clearAllAccountData(request.category); } function parseCategory(value: unknown): AccountStorageCategory { - if (value === 'messages' || value === 'media' || value === 'reactions') return value; - throw new StorageManagementInputError('unsupported account storage category'); + if (value === 'messages' || value === 'media' || value === 'reactions') { + return value; + } + + throw new StorageManagementInputError('unsupported account storage category'); } function assertExactKeys(body: Record, allowed: string[]): void { - const allowedSet = new Set(allowed); - const unknown = Object.keys(body).filter((key) => !allowedSet.has(key)); - const missing = allowed.filter((key) => !(key in body)); - if (unknown.length > 0 || missing.length > 0) { - throw new StorageManagementInputError('cleanup request has unexpected or missing fields'); - } + const allowedSet = new Set(allowed); + const unknown = Object.keys(body).filter((key) => !allowedSet.has(key)); + const missing = allowed.filter((key) => !(key in body)); + + if (unknown.length > 0 || missing.length > 0) { + throw new StorageManagementInputError('cleanup request has unexpected or missing fields'); + } } function accountScope(request: StorageCleanupRequest): StorageCleanupAuditEvent['accountScope'] { - if (request.scope === 'account') return 'single'; - if (request.scope === 'allAccounts') return 'all'; - return 'global'; + if (request.scope === 'account') { + return 'single'; + } + + if (request.scope === 'allAccounts') { + return 'all'; + } + + return 'global'; } -function cleanupFailureItem( - failure: StorageCleanupResult['failures'][number], -): string { - if ('uin' in failure) return `${failure.uin}/${failure.file}`; - if ('file' in failure) return failure.file; - return failure.item; +function cleanupFailureItem(failure: StorageCleanupResult['failures'][number]): string { + if ('uin' in failure) { + return `${failure.uin}/${failure.file}`; + } + + if ('file' in failure) { + return failure.file; + } + + return failure.item; } function isObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); + return typeof value === 'object' && value !== null && !Array.isArray(value); } diff --git a/packages/core/src/webui/storage-settings.ts b/packages/core/src/webui/storage-settings.ts index c87af328..3b48bb74 100644 --- a/packages/core/src/webui/storage-settings.ts +++ b/packages/core/src/webui/storage-settings.ts @@ -1,312 +1,328 @@ -import type { - LogStoragePolicy, - LogStorageStatus, -} from '@snowluma/common/log-file-transport'; +import type { LogStoragePolicy, LogStorageStatus } from '@snowluma/common/log-file-transport'; import { - DEFAULT_LOG_MAX_TOTAL_MB, - DEFAULT_LOG_PER_UIN, - DEFAULT_LOG_RETAIN_DAYS, - MAX_LOG_RETAIN_DAYS, - MAX_LOG_TOTAL_MB, - type RuntimeConfig, + DEFAULT_LOG_MAX_TOTAL_MB, + DEFAULT_LOG_PER_UIN, + DEFAULT_LOG_RETAIN_DAYS, + MAX_LOG_RETAIN_DAYS, + MAX_LOG_TOTAL_MB, + type RuntimeConfig, } from '@snowluma/common/runtime'; -import { - publicLogStorageStatus, - type PublicLogStorageStatus, -} from './storage-management'; +import { publicLogStorageStatus, type PublicLogStorageStatus } from './storage-management'; -export type LogStorageSettingsField = - | 'logMaxTotalMb' - | 'logRetainDays' - | 'logPerUin'; +export type LogStorageSettingsField = 'logMaxTotalMb' | 'logRetainDays' | 'logPerUin'; export interface LogStorageSettings { - logMaxTotalMb: number; - logRetainDays: number; - logPerUin: boolean; + logMaxTotalMb: number; + logRetainDays: number; + logPerUin: boolean; } export interface LogStorageSettingsState { - saved: LogStorageSettings; - effective: LogStorageSettings; - envOverrides: LogStorageSettingsField[]; + saved: LogStorageSettings; + effective: LogStorageSettings; + envOverrides: LogStorageSettingsField[]; } export interface LogStorageSettingsUpdateResult { - settings: LogStorageSettingsState; - status: PublicLogStorageStatus; + settings: LogStorageSettingsState; + status: PublicLogStorageStatus; } export class StorageSettingsInputError extends Error { - constructor(message: string) { - super(message); - this.name = 'StorageSettingsInputError'; - } + constructor(message: string) { + super(message); + this.name = 'StorageSettingsInputError'; + } } export class StorageSettingsLockedError extends Error { - constructor(readonly fields: LogStorageSettingsField[]) { - super(`settings are locked by environment variables: ${fields.join(', ')}`); - this.name = 'StorageSettingsLockedError'; - } + constructor(readonly fields: LogStorageSettingsField[]) { + super(`settings are locked by environment variables: ${fields.join(', ')}`); + this.name = 'StorageSettingsLockedError'; + } } export class StorageSettingsTransactionError extends Error { - constructor( - message: string, - readonly operationError: unknown, - readonly rollbackErrors: unknown[], - ) { - super(message, { cause: operationError }); - this.name = 'StorageSettingsTransactionError'; - } + constructor( + message: string, + readonly operationError: unknown, + readonly rollbackErrors: unknown[], + ) { + super(message, { cause: operationError }); + this.name = 'StorageSettingsTransactionError'; + } } export interface LogStorageSettingsDependencies { - readPersisted(): RuntimeConfig; - readEnvOverrides(): Partial; - readEffective(): LogStorageStatus; - persist(patch: Partial): RuntimeConfig; - apply(policy: LogStoragePolicy): Promise; + readPersisted(): RuntimeConfig; + readEnvOverrides(): Partial; + readEffective(): LogStorageStatus; + persist(patch: Partial): RuntimeConfig; + apply(policy: LogStoragePolicy): Promise; } -const SETTINGS_FIELDS: LogStorageSettingsField[] = [ - 'logMaxTotalMb', - 'logRetainDays', - 'logPerUin', -]; +const SETTINGS_FIELDS: LogStorageSettingsField[] = ['logMaxTotalMb', 'logRetainDays', 'logPerUin']; const SETTINGS_FIELD_SET = new Set(SETTINGS_FIELDS); export class LogStorageSettingsManager { - private updateQueue: Promise = Promise.resolve(); + private updateQueue: Promise = Promise.resolve(); - constructor(private readonly deps: LogStorageSettingsDependencies) {} + constructor(private readonly deps: LogStorageSettingsDependencies) {} - read(): LogStorageSettingsState { - return settingsState( - this.deps.readPersisted(), - this.deps.readEnvOverrides(), - settingsFromStatus(this.deps.readEffective()), - ); - } - - update(body: unknown): Promise { - const operation = this.updateQueue.then(() => this.performUpdate(body)); - this.updateQueue = operation.then( - () => undefined, - () => undefined, - ); - return operation; - } - - private async performUpdate(body: unknown): Promise { - const patch = coerceLogStorageSettingsPatch(body); - const previousRuntime = this.deps.readPersisted(); - const envOverrides = this.deps.readEnvOverrides(); - const previous = settingsState( - previousRuntime, - envOverrides, - settingsFromStatus(this.deps.readEffective()), - ); - const locked = SETTINGS_FIELDS.filter( - (field) => field in patch && field in envOverrides, - ); - if (locked.length > 0) throw new StorageSettingsLockedError(locked); - - const nextSaved = { ...previous.saved, ...patch }; - const nextEffective = { ...previous.effective, ...patch }; - const previousPolicy = toPolicy(previous.effective); - const nextPolicy = toPolicy(nextEffective); - - let status: LogStorageStatus; - try { - status = await this.deps.apply(nextPolicy); - assertApplied(status, nextPolicy); - } catch (error) { - const rollbackErrors = await this.rollbackRuntime(previousPolicy); - throw new StorageSettingsTransactionError( - rollbackErrors.length > 0 - ? 'failed to apply log settings and runtime rollback was incomplete' - : 'failed to apply log settings; runtime state was rolled back', - error, - rollbackErrors, - ); + read(): LogStorageSettingsState { + return settingsState( + this.deps.readPersisted(), + this.deps.readEnvOverrides(), + settingsFromStatus(this.deps.readEffective()), + ); } - let persistedRuntime: RuntimeConfig; - try { - persistedRuntime = this.deps.persist(patch); - assertPersistedSettings(persistedRuntime, nextSaved); - } catch (error) { - const rollbackErrors = await this.rollbackAll(previousPolicy, previousRuntime); - throw new StorageSettingsTransactionError( - rollbackErrors.length > 0 - ? 'failed to persist log settings and rollback was incomplete' - : 'failed to persist log settings; previous settings were restored', - error, - rollbackErrors, - ); + update(body: unknown): Promise { + const operation = this.updateQueue.then(() => this.performUpdate(body)); + this.updateQueue = operation.then( + () => undefined, + () => undefined, + ); + return operation; } - return { - settings: settingsState( - persistedRuntime, - envOverrides, - settingsFromStatus(status), - ), - status: publicLogStorageStatus(status), - }; - } + private async performUpdate(body: unknown): Promise { + const patch = coerceLogStorageSettingsPatch(body); + const previousRuntime = this.deps.readPersisted(); + const envOverrides = this.deps.readEnvOverrides(); + const previous = settingsState( + previousRuntime, + envOverrides, + settingsFromStatus(this.deps.readEffective()), + ); + const locked = SETTINGS_FIELDS.filter((field) => field in patch && field in envOverrides); - private async rollbackRuntime(policy: LogStoragePolicy): Promise { - try { - const status = await this.deps.apply(policy); - assertApplied(status, policy); - return []; - } catch (error) { - return [error]; - } - } + if (locked.length > 0) { + throw new StorageSettingsLockedError(locked); + } - private async rollbackAll( - policy: LogStoragePolicy, - runtime: RuntimeConfig, - ): Promise { - const errors = await this.rollbackRuntime(policy); - try { - this.deps.persist(runtime); - } catch (error) { - errors.push(error); + const nextSaved = { ...previous.saved, ...patch }; + const nextEffective = { ...previous.effective, ...patch }; + const previousPolicy = toPolicy(previous.effective); + const nextPolicy = toPolicy(nextEffective); + + let status: LogStorageStatus; + + try { + status = await this.deps.apply(nextPolicy); + assertApplied(status, nextPolicy); + } catch (error) { + const rollbackErrors = await this.rollbackRuntime(previousPolicy); + throw new StorageSettingsTransactionError( + rollbackErrors.length > 0 + ? 'failed to apply log settings and runtime rollback was incomplete' + : 'failed to apply log settings; runtime state was rolled back', + error, + rollbackErrors, + ); + } + + let persistedRuntime: RuntimeConfig; + + try { + persistedRuntime = this.deps.persist(patch); + assertPersistedSettings(persistedRuntime, nextSaved); + } catch (error) { + const rollbackErrors = await this.rollbackAll(previousPolicy, previousRuntime); + throw new StorageSettingsTransactionError( + rollbackErrors.length > 0 + ? 'failed to persist log settings and rollback was incomplete' + : 'failed to persist log settings; previous settings were restored', + error, + rollbackErrors, + ); + } + + return { + settings: settingsState(persistedRuntime, envOverrides, settingsFromStatus(status)), + status: publicLogStorageStatus(status), + }; + } + + private async rollbackRuntime(policy: LogStoragePolicy): Promise { + try { + const status = await this.deps.apply(policy); + assertApplied(status, policy); + return []; + } catch (error) { + return [error]; + } + } + + private async rollbackAll( + policy: LogStoragePolicy, + runtime: RuntimeConfig, + ): Promise { + const errors = await this.rollbackRuntime(policy); + + try { + this.deps.persist(runtime); + } catch (error) { + errors.push(error); + } + + return errors; } - return errors; - } } function coerceLogStorageSettingsPatch(body: unknown): Partial { - if (!isObject(body)) throw new StorageSettingsInputError('body must be an object'); - const keys = Object.keys(body); - if (keys.length === 0) throw new StorageSettingsInputError('at least one setting is required'); - const unknown = keys.filter((key) => !SETTINGS_FIELD_SET.has(key)); - if (unknown.length > 0) { - throw new StorageSettingsInputError(`unknown setting: ${unknown.join(', ')}`); - } + if (!isObject(body)) { + throw new StorageSettingsInputError('body must be an object'); + } - const patch: Partial = {}; - if ('logMaxTotalMb' in body) { - const value = body.logMaxTotalMb; - if ( - typeof value !== 'number' - || !Number.isSafeInteger(value) - || value < 1 - || value > MAX_LOG_TOTAL_MB - ) { - throw new StorageSettingsInputError( - `logMaxTotalMb must be an integer in 1..${MAX_LOG_TOTAL_MB}`, - ); + const keys = Object.keys(body); + + if (keys.length === 0) { + throw new StorageSettingsInputError('at least one setting is required'); } - patch.logMaxTotalMb = value; - } - if ('logRetainDays' in body) { - const value = body.logRetainDays; - if ( - typeof value !== 'number' - || !Number.isSafeInteger(value) - || value < 0 - || value > MAX_LOG_RETAIN_DAYS - ) { - throw new StorageSettingsInputError( - `logRetainDays must be an integer in 0..${MAX_LOG_RETAIN_DAYS}`, - ); + + const unknown = keys.filter((key) => !SETTINGS_FIELD_SET.has(key)); + + if (unknown.length > 0) { + throw new StorageSettingsInputError(`unknown setting: ${unknown.join(', ')}`); } - patch.logRetainDays = value; - } - if ('logPerUin' in body) { - if (typeof body.logPerUin !== 'boolean') { - throw new StorageSettingsInputError('logPerUin must be a boolean'); + + const patch: Partial = {}; + + if ('logMaxTotalMb' in body) { + const value = body.logMaxTotalMb; + + if ( + typeof value !== 'number' || + !Number.isSafeInteger(value) || + value < 1 || + value > MAX_LOG_TOTAL_MB + ) { + throw new StorageSettingsInputError( + `logMaxTotalMb must be an integer in 1..${MAX_LOG_TOTAL_MB}`, + ); + } + + patch.logMaxTotalMb = value; } - patch.logPerUin = body.logPerUin; - } - return patch; + + if ('logRetainDays' in body) { + const value = body.logRetainDays; + + if ( + typeof value !== 'number' || + !Number.isSafeInteger(value) || + value < 0 || + value > MAX_LOG_RETAIN_DAYS + ) { + throw new StorageSettingsInputError( + `logRetainDays must be an integer in 0..${MAX_LOG_RETAIN_DAYS}`, + ); + } + + patch.logRetainDays = value; + } + + if ('logPerUin' in body) { + if (typeof body.logPerUin !== 'boolean') { + throw new StorageSettingsInputError('logPerUin must be a boolean'); + } + + patch.logPerUin = body.logPerUin; + } + + return patch; } function settingsState( - runtime: RuntimeConfig, - envOverrides: Partial, - liveEffective?: LogStorageSettings, + runtime: RuntimeConfig, + envOverrides: Partial, + liveEffective?: LogStorageSettings, ): LogStorageSettingsState { - const saved = settingsFromRuntime(runtime); - const envOverridesList = SETTINGS_FIELDS.filter((field) => field in envOverrides); - const effective = liveEffective ?? { - ...saved, - ...settingsPatchFromRuntime(envOverrides), - }; - return { saved, effective, envOverrides: envOverridesList }; + const saved = settingsFromRuntime(runtime); + const envOverridesList = SETTINGS_FIELDS.filter((field) => field in envOverrides); + const effective = liveEffective ?? { + ...saved, + ...settingsPatchFromRuntime(envOverrides), + }; + return { saved, effective, envOverrides: envOverridesList }; } function settingsFromStatus(status: LogStorageStatus): LogStorageSettings { - const maxTotalMb = status.maxTotalBytes / (1024 * 1024); - if (!Number.isSafeInteger(maxTotalMb)) { - throw new Error('live log storage limit is not an integer number of megabytes'); - } - return { - logMaxTotalMb: maxTotalMb, - logRetainDays: status.retainDays, - logPerUin: status.perUinEnabled, - }; + const maxTotalMb = status.maxTotalBytes / (1024 * 1024); + + if (!Number.isSafeInteger(maxTotalMb)) { + throw new Error('live log storage limit is not an integer number of megabytes'); + } + + return { + logMaxTotalMb: maxTotalMb, + logRetainDays: status.retainDays, + logPerUin: status.perUinEnabled, + }; } function settingsFromRuntime(runtime: RuntimeConfig): LogStorageSettings { - return { - logMaxTotalMb: runtime.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB, - logRetainDays: runtime.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS, - logPerUin: runtime.logPerUin ?? DEFAULT_LOG_PER_UIN, - }; + return { + logMaxTotalMb: runtime.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB, + logRetainDays: runtime.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS, + logPerUin: runtime.logPerUin ?? DEFAULT_LOG_PER_UIN, + }; } function settingsPatchFromRuntime(runtime: Partial): Partial { - const patch: Partial = {}; - if (runtime.logMaxTotalMb !== undefined) patch.logMaxTotalMb = runtime.logMaxTotalMb; - if (runtime.logRetainDays !== undefined) patch.logRetainDays = runtime.logRetainDays; - if (runtime.logPerUin !== undefined) patch.logPerUin = runtime.logPerUin; - return patch; + const patch: Partial = {}; + + if (runtime.logMaxTotalMb !== undefined) { + patch.logMaxTotalMb = runtime.logMaxTotalMb; + } + + if (runtime.logRetainDays !== undefined) { + patch.logRetainDays = runtime.logRetainDays; + } + + if (runtime.logPerUin !== undefined) { + patch.logPerUin = runtime.logPerUin; + } + + return patch; } function toPolicy(settings: LogStorageSettings): LogStoragePolicy { - return { - maxTotalMb: settings.logMaxTotalMb, - retainDays: settings.logRetainDays, - perUinEnabled: settings.logPerUin, - }; + return { + maxTotalMb: settings.logMaxTotalMb, + retainDays: settings.logRetainDays, + perUinEnabled: settings.logPerUin, + }; } function assertApplied(status: LogStorageStatus, policy: LogStoragePolicy): void { - const expectedBytes = policy.maxTotalMb * 1024 * 1024; - if ( - status.state === 'warning' - || status.state === 'degraded' - || status.lastError !== undefined - || status.maxTotalBytes !== expectedBytes - || status.retainDays !== policy.retainDays - || status.perUinEnabled !== policy.perUinEnabled - ) { - throw new Error(status.lastError ?? 'log storage policy did not become effective'); - } + const expectedBytes = policy.maxTotalMb * 1024 * 1024; + + if ( + status.state === 'warning' || + status.state === 'degraded' || + status.lastError !== undefined || + status.maxTotalBytes !== expectedBytes || + status.retainDays !== policy.retainDays || + status.perUinEnabled !== policy.perUinEnabled + ) { + throw new Error(status.lastError ?? 'log storage policy did not become effective'); + } } -function assertPersistedSettings( - runtime: RuntimeConfig, - expected: LogStorageSettings, -): void { - const actual = settingsFromRuntime(runtime); - if ( - actual.logMaxTotalMb !== expected.logMaxTotalMb - || actual.logRetainDays !== expected.logRetainDays - || actual.logPerUin !== expected.logPerUin - ) { - throw new Error('persisted log storage settings do not match the requested values'); - } +function assertPersistedSettings(runtime: RuntimeConfig, expected: LogStorageSettings): void { + const actual = settingsFromRuntime(runtime); + + if ( + actual.logMaxTotalMb !== expected.logMaxTotalMb || + actual.logRetainDays !== expected.logRetainDays || + actual.logPerUin !== expected.logPerUin + ) { + throw new Error('persisted log storage settings do not match the requested values'); + } } function isObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); + return typeof value === 'object' && value !== null && !Array.isArray(value); } diff --git a/packages/core/src/webui/system-settings.ts b/packages/core/src/webui/system-settings.ts index 6bd51530..a94277e4 100644 --- a/packages/core/src/webui/system-settings.ts +++ b/packages/core/src/webui/system-settings.ts @@ -6,70 +6,82 @@ import type { RuntimeConfig } from '@snowluma/common/runtime'; import { checkListenerExposure } from './listener-exposure'; -export type SettingsPatch = Partial>; +export type SettingsPatch = Partial< + Pick +>; -export type CoerceResult = - | { ok: true; patch: SettingsPatch } - | { ok: false; error: string }; +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); + 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' }; + if (!isObject(body)) { + return { ok: false, error: 'body must be an object' }; } - 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' }; + 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; } - patch.webuiHost = body.webuiHost.trim(); - } - if ('tlsEnabled' in body) { - if (typeof body.tlsEnabled !== 'boolean') { - return { ok: false, error: 'tlsEnabled must be a boolean' }; + 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(); } - patch.webuiTls = { enabled: body.tlsEnabled }; - } - if ('trustProxy' in body) { - if (typeof body.trustProxy !== 'string') { - return { ok: false, error: 'trustProxy must be a string' }; + if ('tlsEnabled' in body) { + if (typeof body.tlsEnabled !== 'boolean') { + return { ok: false, error: 'tlsEnabled must be a boolean' }; + } + + patch.webuiTls = { enabled: body.tlsEnabled }; } - patch.trustProxy = body.trustProxy; - } - return { ok: true, patch }; + 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 }; } const SETTINGS_ERRORS: Record<'invalid-bind-host' | 'tls-pair-required', string> = { - 'invalid-bind-host': '绑定地址不是有效的 TCP 地址', - 'tls-pair-required': '启用 TLS 前请先上传有效的证书与私钥', + 'invalid-bind-host': '绑定地址不是有效的 TCP 地址', + 'tls-pair-required': '启用 TLS 前请先上传有效的证书与私钥', }; /** Validate the listener that would be persisted after applying `patch` to `current`. */ export function evaluateSettingsSave( - current: RuntimeConfig, - patch: SettingsPatch, - pairOk: boolean, + current: RuntimeConfig, + patch: SettingsPatch, + pairOk: boolean, ): CoerceResult { - const webuiHost = patch.webuiHost ?? current.webuiHost ?? '127.0.0.1'; - const tlsEnabled = patch.webuiTls?.enabled ?? current.webuiTls?.enabled ?? false; - const check = checkListenerExposure({ webuiHost, tlsEnabled, pairOk }); - if (!check.ok) return { ok: false, error: SETTINGS_ERRORS[check.code] }; - return { ok: true, patch }; + const webuiHost = patch.webuiHost ?? current.webuiHost ?? '127.0.0.1'; + const tlsEnabled = patch.webuiTls?.enabled ?? current.webuiTls?.enabled ?? false; + const check = checkListenerExposure({ webuiHost, tlsEnabled, pairOk }); + + if (!check.ok) { + return { ok: false, error: SETTINGS_ERRORS[check.code] }; + } + + return { ok: true, patch }; } export function tlsCertDeletionBlocked(tlsEnabled: boolean): boolean { - return tlsEnabled; + return tlsEnabled; } diff --git a/packages/core/src/webui/tls.ts b/packages/core/src/webui/tls.ts index b5f5ccda..63f3c9b2 100644 --- a/packages/core/src/webui/tls.ts +++ b/packages/core/src/webui/tls.ts @@ -9,63 +9,81 @@ import path from 'path'; import tls from 'tls'; export interface TlsValidation { - ok: boolean; - reason?: string; + ok: boolean; + reason?: string; } export interface TlsResolution { - ok: boolean; - cert?: Buffer; - key?: Buffer; - reason?: string; + ok: boolean; + cert?: Buffer; + key?: Buffer; + reason?: string; } export interface RequiredTlsContext { - cert: Buffer; - key: Buffer; + cert: Buffer; + key: Buffer; } function errMsg(e: unknown): string { - return e instanceof Error ? e.message : String(e); + 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)}` }; - } + 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 }; + 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 }; } /** Resolve the configured pair for an enabled listener or abort startup. */ export function requireTlsContext(configDir: string): RequiredTlsContext { - const resolved = resolveTlsContext(configDir); - if (!resolved.ok || !resolved.cert || !resolved.key) { - throw new Error(`TLS listener cannot start: ${resolved.reason ?? 'certificate pair is unusable'}`); - } - return { cert: resolved.cert, key: resolved.key }; + const resolved = resolveTlsContext(configDir); + + if (!resolved.ok || !resolved.cert || !resolved.key) { + throw new Error( + `TLS listener cannot start: ${resolved.reason ?? 'certificate pair is unusable'}`, + ); + } + + return { cert: resolved.cert, key: resolved.key }; } diff --git a/packages/core/src/webui/totp.ts b/packages/core/src/webui/totp.ts index 82cce090..6b558952 100644 --- a/packages/core/src/webui/totp.ts +++ b/packages/core/src/webui/totp.ts @@ -1,4 +1,11 @@ -import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto'; +import { + createCipheriv, + createDecipheriv, + createHash, + randomBytes, + scryptSync, + timingSafeEqual, +} from 'node:crypto'; import * as OTPAuth from 'otpauth'; const TOTP_PERIOD_SECONDS = 30; @@ -14,324 +21,431 @@ const SCRYPT_R = 8; const SCRYPT_P = 1; export interface WrappedTotpSecret { - wrapSalt: string; - iv: string; - ciphertext: string; - authTag: string; + wrapSalt: string; + iv: string; + ciphertext: string; + authTag: string; } export interface TotpPersistedState extends WrappedTotpSecret { - recoveryCodeHashes: string[]; - lastUsedStep: number; - label: string; + recoveryCodeHashes: string[]; + lastUsedStep: number; + label: string; } export interface TotpEnrollment { - secret: string; - otpauthUrl: string; - issuer: string; - accountName: string; + secret: string; + otpauthUrl: string; + issuer: string; + accountName: string; } function totpFromSecret(secretBase32: string, issuer = '', accountName = 'admin'): OTPAuth.TOTP { - return new OTPAuth.TOTP({ - issuer, - label: accountName, - algorithm: 'SHA1', - digits: TOTP_DIGITS, - period: TOTP_PERIOD_SECONDS, - secret: OTPAuth.Secret.fromBase32(secretBase32), - }); + return new OTPAuth.TOTP({ + issuer, + label: accountName, + algorithm: 'SHA1', + digits: TOTP_DIGITS, + period: TOTP_PERIOD_SECONDS, + secret: OTPAuth.Secret.fromBase32(secretBase32), + }); } export function verifyTotpCode( - secretBase32: string, - code: string, - atMs: number, - lastUsedStep?: number, + secretBase32: string, + code: string, + atMs: number, + lastUsedStep?: number, ): { ok: true; step: number } | { ok: false } { - const token = code.replace(/\s/g, ''); - if (!/^\d{6}$/.test(token)) return { ok: false }; + const token = code.replace(/\s/g, ''); - let totp: OTPAuth.TOTP; - try { - totp = totpFromSecret(secretBase32); - } catch { - return { ok: false }; - } - const delta = totp.validate({ token, timestamp: atMs, window: TOTP_WINDOW }); - if (delta === null) return { ok: false }; + if (!/^\d{6}$/.test(token)) { + return { ok: false }; + } - const step = totp.counter({ timestamp: atMs }) + delta; - if (lastUsedStep !== undefined && step === lastUsedStep) return { ok: false }; - return { ok: true, step }; + let totp: OTPAuth.TOTP; + + try { + totp = totpFromSecret(secretBase32); + } catch { + return { ok: false }; + } + + const delta = totp.validate({ token, timestamp: atMs, window: TOTP_WINDOW }); + + if (delta === null) { + return { ok: false }; + } + + const step = totp.counter({ timestamp: atMs }) + delta; + + if (lastUsedStep !== undefined && step === lastUsedStep) { + return { ok: false }; + } + + return { ok: true, step }; } function deriveWrapKey(password: string, salt: Buffer): Buffer { - return scryptSync(password, salt, WRAP_KEY_BYTES, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P }); + return scryptSync(password, salt, WRAP_KEY_BYTES, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P }); } export function wrapTotpSecret(password: string, secret: string): WrappedTotpSecret { - const wrapSalt = randomBytes(WRAP_SALT_BYTES); - const iv = randomBytes(WRAP_IV_BYTES); - const key = deriveWrapKey(password, wrapSalt); - const cipher = createCipheriv('aes-256-gcm', key, iv); - const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]); - return { - wrapSalt: wrapSalt.toString('hex'), - iv: iv.toString('hex'), - ciphertext: ciphertext.toString('hex'), - authTag: cipher.getAuthTag().toString('hex'), - }; + const wrapSalt = randomBytes(WRAP_SALT_BYTES); + const iv = randomBytes(WRAP_IV_BYTES); + const key = deriveWrapKey(password, wrapSalt); + const cipher = createCipheriv('aes-256-gcm', key, iv); + const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]); + return { + wrapSalt: wrapSalt.toString('hex'), + iv: iv.toString('hex'), + ciphertext: ciphertext.toString('hex'), + authTag: cipher.getAuthTag().toString('hex'), + }; } export function unwrapTotpSecret(password: string, wrapped: WrappedTotpSecret): string | null { - try { - const wrapSalt = Buffer.from(wrapped.wrapSalt, 'hex'); - const iv = Buffer.from(wrapped.iv, 'hex'); - const ciphertext = Buffer.from(wrapped.ciphertext, 'hex'); - const authTag = Buffer.from(wrapped.authTag, 'hex'); - if (wrapSalt.length !== WRAP_SALT_BYTES || iv.length !== WRAP_IV_BYTES || authTag.length !== 16) { - return null; + try { + const wrapSalt = Buffer.from(wrapped.wrapSalt, 'hex'); + const iv = Buffer.from(wrapped.iv, 'hex'); + const ciphertext = Buffer.from(wrapped.ciphertext, 'hex'); + const authTag = Buffer.from(wrapped.authTag, 'hex'); + + if ( + wrapSalt.length !== WRAP_SALT_BYTES || + iv.length !== WRAP_IV_BYTES || + authTag.length !== 16 + ) { + return null; + } + + const key = deriveWrapKey(password, wrapSalt); + const decipher = createDecipheriv('aes-256-gcm', key, iv); + decipher.setAuthTag(authTag); + return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8'); + } catch { + return null; } - const key = deriveWrapKey(password, wrapSalt); - const decipher = createDecipheriv('aes-256-gcm', key, iv); - decipher.setAuthTag(authTag); - return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8'); - } catch { - return null; - } } function randomRecoveryChunk(): string { - const bytes = randomBytes(4); - let chunk = ''; - for (let i = 0; i < 4; i++) { - chunk += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length]; - } - return chunk; + const bytes = randomBytes(4); + let chunk = ''; + + for (let i = 0; i < 4; i++) { + chunk += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length]; + } + + return chunk; } export function generateRecoveryCodes(): string[] { - const codes = new Set(); - while (codes.size < RECOVERY_CODE_COUNT) { - codes.add(`${randomRecoveryChunk()}-${randomRecoveryChunk()}`); - } - return [...codes]; + const codes = new Set(); + + while (codes.size < RECOVERY_CODE_COUNT) { + codes.add(`${randomRecoveryChunk()}-${randomRecoveryChunk()}`); + } + + return [...codes]; } export function normalizeRecoveryCode(code: string): string { - return code.replace(/[-\s]/g, '').toUpperCase(); + return code.replace(/[-\s]/g, '').toUpperCase(); } export function hashRecoveryCode(code: string): string { - return createHash('sha256').update(normalizeRecoveryCode(code), 'utf8').digest('hex'); + return createHash('sha256').update(normalizeRecoveryCode(code), 'utf8').digest('hex'); } function hashesEqual(left: string, right: string): boolean { - const a = Buffer.from(left, 'hex'); - const b = Buffer.from(right, 'hex'); - if (a.length !== b.length || a.length === 0) return false; - return timingSafeEqual(a, b); + const a = Buffer.from(left, 'hex'); + const b = Buffer.from(right, 'hex'); + + if (a.length !== b.length || a.length === 0) { + return false; + } + + return timingSafeEqual(a, b); } export function consumeRecoveryCode( - code: string, - hashes: readonly string[], + code: string, + hashes: readonly string[], ): { ok: true; remainingHashes: string[] } | { ok: false } { - const candidate = hashRecoveryCode(code); - const index = hashes.findIndex((hash) => hashesEqual(hash, candidate)); - if (index < 0) return { ok: false }; - return { ok: true, remainingHashes: hashes.filter((_, i) => i !== index) }; + const candidate = hashRecoveryCode(code); + const index = hashes.findIndex((hash) => hashesEqual(hash, candidate)); + + if (index < 0) { + return { ok: false }; + } + + return { ok: true, remainingHashes: hashes.filter((_, i) => i !== index) }; } export function beginTotpEnrollment(options: { - issuer: string; - accountName: string; - secret?: string; + issuer: string; + accountName: string; + secret?: string; }): TotpEnrollment { - const secret = options.secret ?? new OTPAuth.Secret({ size: 20 }).base32; - const totp = totpFromSecret(secret, options.issuer, options.accountName); - return { - secret, - otpauthUrl: totp.toString(), - issuer: options.issuer, - accountName: options.accountName, - }; + const secret = options.secret ?? new OTPAuth.Secret({ size: 20 }).base32; + const totp = totpFromSecret(secret, options.issuer, options.accountName); + return { + secret, + otpauthUrl: totp.toString(), + issuer: options.issuer, + accountName: options.accountName, + }; } export function confirmTotpEnrollment(options: { - password: string; - secret: string; - code: string; - label: string; - atMs: number; + password: string; + secret: string; + code: string; + label: string; + atMs: number; }): { state: TotpPersistedState; recoveryCodes: string[] } { - const verified = verifyTotpCode(options.secret, options.code, options.atMs); - if (!verified.ok) { - throw new Error('验证码不正确'); - } - const recoveryCodes = generateRecoveryCodes(); - return { - recoveryCodes, - state: { - ...wrapTotpSecret(options.password, options.secret), - recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode), - lastUsedStep: verified.step, - label: options.label, - }, - }; + const verified = verifyTotpCode(options.secret, options.code, options.atMs); + + if (!verified.ok) { + throw new Error('验证码不正确'); + } + + const recoveryCodes = generateRecoveryCodes(); + return { + recoveryCodes, + state: { + ...wrapTotpSecret(options.password, options.secret), + recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode), + lastUsedStep: verified.step, + label: options.label, + }, + }; } export function verifySecondFactor(options: { - password: string; - state: TotpPersistedState; - atMs: number; - totp?: string; - recoveryCode?: string; + password: string; + state: TotpPersistedState; + atMs: number; + totp?: string; + recoveryCode?: string; }): { ok: true; state: TotpPersistedState } | { ok: false } { - if (typeof options.recoveryCode === 'string' && options.recoveryCode.length > 0) { - const consumed = consumeRecoveryCode(options.recoveryCode, options.state.recoveryCodeHashes); - if (!consumed.ok) return { ok: false }; - return { ok: true, state: { ...options.state, recoveryCodeHashes: consumed.remainingHashes } }; - } - if (typeof options.totp !== 'string') return { ok: false }; - const secret = unwrapTotpSecret(options.password, options.state); - if (secret === null) return { ok: false }; - const checked = verifyTotpCode(secret, options.totp, options.atMs, options.state.lastUsedStep); - if (!checked.ok) return { ok: false }; - return { ok: true, state: { ...options.state, lastUsedStep: checked.step } }; + if (typeof options.recoveryCode === 'string' && options.recoveryCode.length > 0) { + const consumed = consumeRecoveryCode( + options.recoveryCode, + options.state.recoveryCodeHashes, + ); + + if (!consumed.ok) { + return { ok: false }; + } + + return { + ok: true, + state: { ...options.state, recoveryCodeHashes: consumed.remainingHashes }, + }; + } + + if (typeof options.totp !== 'string') { + return { ok: false }; + } + + const secret = unwrapTotpSecret(options.password, options.state); + + if (secret === null) { + return { ok: false }; + } + + const checked = verifyTotpCode(secret, options.totp, options.atMs, options.state.lastUsedStep); + + if (!checked.ok) { + return { ok: false }; + } + + return { ok: true, state: { ...options.state, lastUsedStep: checked.step } }; } export type SecondFactorDecision = - | { kind: 'needs-totp' } - | { kind: 'bad-second-factor' } - | { kind: 'ok'; state?: TotpPersistedState }; + | { kind: 'needs-totp' } + | { kind: 'bad-second-factor' } + | { kind: 'ok'; state?: TotpPersistedState }; export function decideSecondFactorLogin(options: { - totpEnabled: boolean; - state?: TotpPersistedState; - password: string; - totp?: string; - recoveryCode?: string; - atMs: number; + totpEnabled: boolean; + state?: TotpPersistedState; + password: string; + totp?: string; + recoveryCode?: string; + atMs: number; }): SecondFactorDecision { - if (!options.totpEnabled) return { kind: 'ok' }; - if (!options.state) return { kind: 'bad-second-factor' }; - const totp = typeof options.totp === 'string' && options.totp.trim().length > 0 - ? options.totp.trim() - : undefined; - const recoveryCode = typeof options.recoveryCode === 'string' && options.recoveryCode.trim().length > 0 - ? options.recoveryCode.trim() - : undefined; - if (!totp && !recoveryCode) return { kind: 'needs-totp' }; - const result = verifySecondFactor({ - password: options.password, - state: options.state, - atMs: options.atMs, - totp, - recoveryCode, - }); - if (!result.ok) return { kind: 'bad-second-factor' }; - return { kind: 'ok', state: result.state }; + if (!options.totpEnabled) { + return { kind: 'ok' }; + } + + if (!options.state) { + return { kind: 'bad-second-factor' }; + } + + const totp = + typeof options.totp === 'string' && options.totp.trim().length > 0 + ? options.totp.trim() + : undefined; + const recoveryCode = + typeof options.recoveryCode === 'string' && options.recoveryCode.trim().length > 0 + ? options.recoveryCode.trim() + : undefined; + + if (!totp && !recoveryCode) { + return { kind: 'needs-totp' }; + } + + const result = verifySecondFactor({ + password: options.password, + state: options.state, + atMs: options.atMs, + totp, + recoveryCode, + }); + + if (!result.ok) { + return { kind: 'bad-second-factor' }; + } + + return { kind: 'ok', state: result.state }; } export function regenerateRecoveryCodes(options: { - password: string; - state: TotpPersistedState; - totp: string; - atMs: number; + password: string; + state: TotpPersistedState; + totp: string; + atMs: number; }): { state: TotpPersistedState; recoveryCodes: string[] } { - const verified = verifySecondFactor({ - password: options.password, - state: options.state, - totp: options.totp, - atMs: options.atMs, - }); - if (!verified.ok) { - throw new Error('验证码不正确'); - } - const recoveryCodes = generateRecoveryCodes(); - return { - recoveryCodes, - state: { - ...verified.state, - recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode), - }, - }; + const verified = verifySecondFactor({ + password: options.password, + state: options.state, + totp: options.totp, + atMs: options.atMs, + }); + + if (!verified.ok) { + throw new Error('验证码不正确'); + } + + const recoveryCodes = generateRecoveryCodes(); + return { + recoveryCodes, + state: { + ...verified.state, + recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode), + }, + }; } export function rewrapTotpSecret( - oldPassword: string, - newPassword: string, - state: TotpPersistedState, + oldPassword: string, + newPassword: string, + state: TotpPersistedState, ): TotpPersistedState { - const secret = unwrapTotpSecret(oldPassword, state); - if (secret === null) { - throw new Error('无法使用当前密码解开 2FA 密钥'); - } - return { - ...state, - ...wrapTotpSecret(newPassword, secret), - }; + const secret = unwrapTotpSecret(oldPassword, state); + + if (secret === null) { + throw new Error('无法使用当前密码解开 2FA 密钥'); + } + + return { + ...state, + ...wrapTotpSecret(newPassword, secret), + }; } const HEX = /^[0-9a-f]+$/i; -function isWrappedShape(value: Record): value is WrappedTotpSecret & Record { - return typeof value.wrapSalt === 'string' - && HEX.test(value.wrapSalt) - && value.wrapSalt.length === WRAP_SALT_BYTES * 2 - && typeof value.iv === 'string' - && HEX.test(value.iv) - && value.iv.length === WRAP_IV_BYTES * 2 - && typeof value.ciphertext === 'string' - && HEX.test(value.ciphertext) - && value.ciphertext.length > 0 - && value.ciphertext.length % 2 === 0 - && typeof value.authTag === 'string' - && HEX.test(value.authTag) - && value.authTag.length === 32; +function isWrappedShape( + value: Record, +): value is WrappedTotpSecret & Record { + return ( + typeof value.wrapSalt === 'string' && + HEX.test(value.wrapSalt) && + value.wrapSalt.length === WRAP_SALT_BYTES * 2 && + typeof value.iv === 'string' && + HEX.test(value.iv) && + value.iv.length === WRAP_IV_BYTES * 2 && + typeof value.ciphertext === 'string' && + HEX.test(value.ciphertext) && + value.ciphertext.length > 0 && + value.ciphertext.length % 2 === 0 && + typeof value.authTag === 'string' && + HEX.test(value.authTag) && + value.authTag.length === 32 + ); } export function prepareTotpStateForRestore(value: unknown): TotpPersistedState { - if (!value || typeof value !== 'object' || Array.isArray(value)) { - throw new Error('totp state must be an object'); - } - const v = value as Record; - if (!isWrappedShape(v)) { - throw new Error('totp wrapped secret fields are invalid'); - } - if (!Array.isArray(v.recoveryCodeHashes) - || v.recoveryCodeHashes.length > RECOVERY_CODE_COUNT - || v.recoveryCodeHashes.some((hash) => typeof hash !== 'string' || !/^[0-9a-f]{64}$/i.test(hash))) { - throw new Error('totp recoveryCodeHashes must be SHA-256 hex strings'); - } - if (typeof v.lastUsedStep !== 'number' || !Number.isInteger(v.lastUsedStep) || v.lastUsedStep < 0) { - throw new Error('totp lastUsedStep must be a non-negative integer'); - } - if (typeof v.label !== 'string' || v.label.length === 0 || v.label.length > 128) { - throw new Error('totp label must be a non-empty string'); - } - const allowed = new Set(['wrapSalt', 'iv', 'ciphertext', 'authTag', 'recoveryCodeHashes', 'lastUsedStep', 'label']); - const unknown = Object.keys(v).find((key) => !allowed.has(key)); - if (unknown) throw new Error(`unknown totp field $.${unknown}`); - return { - wrapSalt: v.wrapSalt.toLowerCase(), - iv: v.iv.toLowerCase(), - ciphertext: v.ciphertext.toLowerCase(), - authTag: v.authTag.toLowerCase(), - recoveryCodeHashes: v.recoveryCodeHashes.map((hash) => (hash as string).toLowerCase()), - lastUsedStep: v.lastUsedStep, - label: v.label, - }; + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new Error('totp state must be an object'); + } + + const v = value as Record; + + if (!isWrappedShape(v)) { + throw new Error('totp wrapped secret fields are invalid'); + } + + if ( + !Array.isArray(v.recoveryCodeHashes) || + v.recoveryCodeHashes.length > RECOVERY_CODE_COUNT || + v.recoveryCodeHashes.some( + (hash) => typeof hash !== 'string' || !/^[0-9a-f]{64}$/i.test(hash), + ) + ) { + throw new Error('totp recoveryCodeHashes must be SHA-256 hex strings'); + } + + if ( + typeof v.lastUsedStep !== 'number' || + !Number.isInteger(v.lastUsedStep) || + v.lastUsedStep < 0 + ) { + throw new Error('totp lastUsedStep must be a non-negative integer'); + } + + if (typeof v.label !== 'string' || v.label.length === 0 || v.label.length > 128) { + throw new Error('totp label must be a non-empty string'); + } + + const allowed = new Set([ + 'wrapSalt', + 'iv', + 'ciphertext', + 'authTag', + 'recoveryCodeHashes', + 'lastUsedStep', + 'label', + ]); + const unknown = Object.keys(v).find((key) => !allowed.has(key)); + + if (unknown) { + throw new Error(`unknown totp field $.${unknown}`); + } + + return { + wrapSalt: v.wrapSalt.toLowerCase(), + iv: v.iv.toLowerCase(), + ciphertext: v.ciphertext.toLowerCase(), + authTag: v.authTag.toLowerCase(), + recoveryCodeHashes: v.recoveryCodeHashes.map((hash) => (hash as string).toLowerCase()), + lastUsedStep: v.lastUsedStep, + label: v.label, + }; } export function parseTotpStateLenient(value: unknown): TotpPersistedState | undefined { - if (value === undefined || value === null) return undefined; - try { - return prepareTotpStateForRestore(value); - } catch { - return undefined; - } + if (value === undefined || value === null) { + return undefined; + } + + try { + return prepareTotpStateForRestore(value); + } catch { + return undefined; + } } diff --git a/packages/core/src/webui/ui-config.ts b/packages/core/src/webui/ui-config.ts index 5fce253b..63ec06ba 100644 --- a/packages/core/src/webui/ui-config.ts +++ b/packages/core/src/webui/ui-config.ts @@ -47,153 +47,159 @@ export type TimeFormat = '12h' | '24h'; /** Full color scheme. 'default' keeps the sky theme (driven by `mode`); the * Catppuccin flavors are complete palettes that also fix light/dark. */ export type Palette = - | 'default' - | 'catppuccin-latte' | 'catppuccin-frappe' | 'catppuccin-macchiato' | 'catppuccin-mocha' - | 'rose-pine' | 'rose-pine-moon' | 'rose-pine-dawn' - | 'nord' - | 'everforest-dark' | 'everforest-light'; + | 'default' + | 'catppuccin-latte' + | 'catppuccin-frappe' + | 'catppuccin-macchiato' + | 'catppuccin-mocha' + | 'rose-pine' + | 'rose-pine-moon' + | 'rose-pine-dawn' + | 'nord' + | 'everforest-dark' + | 'everforest-light'; export interface UiBackground { - type: BackgroundType; - /** Solid-fill colour (hex). Used when type === 'solid'. */ - color: string; - /** Gradient preset id (frontend owns the catalogue). Used when type === 'gradient'. */ - gradient: string; - /** Image readability overlay: 0 (image fully visible) … 1 (fully masked). */ - imageOpacity: number; - /** Image blur in px (0…40). */ - imageBlur: number; - // ── server-managed (upload/delete endpoints only) ── - hasImage: boolean; - imageMime: string; - /** Bumped on each successful upload so the browser can cache-bust. */ - imageVersion: number; + type: BackgroundType; + /** Solid-fill colour (hex). Used when type === 'solid'. */ + color: string; + /** Gradient preset id (frontend owns the catalogue). Used when type === 'gradient'. */ + gradient: string; + /** Image readability overlay: 0 (image fully visible) … 1 (fully masked). */ + imageOpacity: number; + /** Image blur in px (0…40). */ + imageBlur: number; + // ── server-managed (upload/delete endpoints only) ── + hasImage: boolean; + imageMime: string; + /** Bumped on each successful upload so the browser can cache-bust. */ + imageVersion: number; } export interface UiAppearance { - mode: ThemeMode; - accentMode: AccentMode; - /** Preset accent id (frontend catalogue: sky/blue/violet/…). */ - accentPreset: string; - /** Custom accent colour (hex). Used when accentMode === 'custom'. */ - accentCustom: string; - accentScope: AccentScope; - darkIntensity: DarkIntensity; - /** Full color scheme; 'default' = the built-in sky theme. */ - palette: Palette; - sidebarStyle: SidebarStyle; - background: UiBackground; - /** Sans font preset id (frontend catalogue); 'custom' uses `fontSansCustom`. */ - fontSans: string; - /** Free-form sans font-family stack, used when `fontSans === 'custom'`. */ - fontSansCustom: string; - /** Mono font preset id (frontend catalogue); 'custom' uses `fontMonoCustom`. */ - fontMono: string; - /** Free-form mono font-family stack, used when `fontMono === 'custom'`. */ - fontMonoCustom: string; - /** Global UI scale, 0.9…1.2. */ - uiScale: number; - /** Corner radius in rem, 0…2. */ - radius: number; - density: Density; - /** Soften animations (transforms off, shorter durations). */ - reduceMotion: boolean; - /** Hard-disable all UI animations (stronger than reduceMotion). */ - disableMotion: boolean; - /** Use SnowLuma's adaptive cursor. */ - customPointerSystem: boolean; - /** Replace the browser context menu with SnowLuma's context menu. */ - customContextMenu: boolean; - highContrast: boolean; - sidebarPinned: boolean; - timeFormat: TimeFormat; - /** Dashboard poll interval (ms); 0 = paused. */ - pollInterval: number; - /** - * Operator custom CSS, applied AFTER auth only (never on the login page — - * `publicAppearance` strips it). Capped at 50 KB. The client injects it as - * the last