diff --git a/README.md b/README.md index 6c526501..2b16ef54 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,153 @@ -

- SnowLuma -

-

- Next Remote Protocol Framework. + SnowLuma 将 QQ 原生会话桥接到 OneBot、WebUI 与自动化工具

- Release - Build - NPM - Stars + 最新版本 + 构建状态 + SnowLuma SDK 版本 + SnowLuma MCP 版本 + GitHub Stars

- Releases · - Issues · - QQ 群 · - Telegram + 快速开始 · + 运行链路 · + 动作参考 · + SDK · + MCP · + 问题反馈

---- +SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时。它把 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,并通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口;每个账号拥有独立会话,适合机器人开发、自动化与协议研究。 -SnowLuma 是一个基于 TypeScript 的协议转换框架,旨在为 QQ 客户端提供 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准接口,支持 WebSocket/HTTP 适配、多账号并行及 WebUI 管理。 - -> ⚠️ **免责声明**:SnowLuma 是独立的第三方互操作项目,**与腾讯 / QQ 无任何隶属或授权关系**。本项目**仅供学习与技术研究**,请遵守《QQ 用户协议》及适用法律;软件按"现状"提供、不附带任何担保,使用风险自负。详见 [`EULA.md`](EULA.md)。 +> [!CAUTION] +> **使用边界**:SnowLuma 是独立的第三方互操作项目,**与腾讯 / QQ 无任何隶属或授权关系**。本项目仅供学习与技术研究,请遵守《QQ 用户协议》及适用法律;软件按“现状”提供、不附带任何担保,使用风险自负。详见 [`EULA.md`](EULA.md)。 > -> ⚠️ **Disclaimer**: SnowLuma is an independent, third-party interoperability project with **no affiliation with or endorsement by Tencent / QQ**, provided **for study and research only**, "as is" without warranty. Comply with the QQ User Agreement and applicable law; use at your own risk. See [`EULA.md`](EULA.md). +> **Disclaimer**: SnowLuma is an independent third-party interoperability project with no affiliation with or endorsement by Tencent / QQ. It is provided for study and research only, “as is” and without warranty. See [`EULA.md`](EULA.md). -## 特性 +## 运行链路 -- **OneBot v11 兼容**:支持文本、音视频、Markdown、JSON 等消息格式。 -- **高性能架构**:TypeScript 全栈,基于 pnpm monorepo 管理,核心逻辑分离。 -- **现代化管理**:内置 WebUI 面板,支持实时日志、密码热更、多账号管理。 -- **多适配器支持**:WebSocket (Server/Client)、HTTP (Server/Post)。 -- **数据持久化**:使用 SQLite 存储好友、群组等关系数据。 +

+ QQ 会话经过协议桥接与 OneBot 标准化后连接到 WebSocket、HTTP、WebUI、SDK 和 MCP +

+ +SnowLuma 将会话接入、协议解析、身份映射、OneBot 转换和网络适配拆成清晰边界。多个 QQ 账号可以并行运行,同时保持独立状态、日志与连接配置。 + +## 核心能力 + +| 场景 | SnowLuma 提供 | +| --- | --- | +| OneBot 接入 | OneBot v11 动作与事件,支持 WebSocket 服务端 / 客户端及 HTTP 服务端 / 上报 | +| 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及 JSON / XML 卡片等常见消息元素 | +| 多账号运行 | 每个 QQ 账号独立维护会话、身份映射、消息存储与网络适配器 | +| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试、密码管理与可定制总览 | +| 开发者工具 | 提供 [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) | +| 可观察错误 | 关键解析与执行失败会留下明确上下文,不以静默丢弃掩盖问题 | ## 快速开始 -1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载最新发布包并解压。 -2. 运行 `./launcher.bat` (Windows) 或 `./launcher.sh` (Linux)。 -3. 访问 `http://localhost:5099` (初始账号 `admin`,密码见控制台输出)。 +### 1. 选择发行包 -无人值守部署可同时设置 `SNOWLUMA_ACCEPT_EULA=1` 与 `SNOWLUMA_ACCEPT_PRIVACY=1` 完成协议确认。两项必须同时设置;移除任意变量后会恢复按当前协议版本检查 WebUI 同意记录。设置这些变量即表示您已阅读并同意 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md)。 +前往 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载与你的平台匹配的版本: -## 许可 / License +| 平台 | 完整版(内置 Node.js,推荐) | Lite(需要 Node.js 22+) | +| --- | --- | --- | +| Windows x64 | `SnowLuma-vX.Y.Z-win-x64.zip` | `SnowLuma-vX.Y.Z-win-x64-lite.zip` | +| Linux x64 | `SnowLuma-vX.Y.Z-linux-x64.tar.gz` | `SnowLuma-vX.Y.Z-linux-x64-lite.tar.gz` | +| Linux arm64 | `SnowLuma-vX.Y.Z-linux-arm64.tar.gz` | `SnowLuma-vX.Y.Z-linux-arm64-lite.tar.gz` | -SnowLuma 采用 **源码可见非商业许可(SnowLuma Source-Available Non-Commercial License)**,见 [`LICENSE`](LICENSE)。**这不是 OSI 开源许可**:源码公开供查看、学习与非商业自托管,但**禁止任何商业使用**(出售、转售、付费托管 / 代搭 / 代运营等),公开发布修改版须事先书面授权。随附的原生附加组件(`snowluma-*.node` 等)为专有组件,不在本许可范围内。二进制发行包另受 [`EULA.md`](EULA.md) 约束;商业授权请联系 motricseven@foxmail.com。参与贡献请阅读 [`CONTRIBUTING.md`](CONTRIBUTING.md)。 +完整版适合直接解压运行;Lite 版只移除了内置 Node.js,其余运行时依赖与 WebUI 静态资源保持一致。 -SnowLuma is under a **source-available, non-commercial** license (see [`LICENSE`](LICENSE)) — **NOT** an OSI open-source license. The source is published for study and non-commercial self-hosting; **commercial use is prohibited** without prior written permission, and the bundled native addon (`snowluma-*.node`) is proprietary and not covered by this license. +### 2. 启动 SnowLuma + +Windows 运行 `launcher.bat`。Linux 在解压目录执行: + +```bash +chmod +x launcher.sh +./launcher.sh +``` + +### 3. 打开 WebUI + +浏览器访问 [`http://localhost:5099`](http://localhost:5099)。初始账号为 `admin`,随机密码会显示在启动日志中;登录后即可接入已启动的 QQ 进程并配置 OneBot 连接。 + +
+无人值守部署:通过环境变量确认协议 + +同时设置以下两个变量可跳过 WebUI 的协议确认页面: + +```bash +SNOWLUMA_ACCEPT_EULA=1 +SNOWLUMA_ACCEPT_PRIVACY=1 +``` + +两项必须同时设置,且环境变量确认不会写入持久化同意记录。设置变量即表示运营者已阅读并同意 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md)。 + +
+ +## 选择接入方式 + +| 入口 | 适合场景 | 参考 | +| --- | --- | --- | +| WebSocket / HTTP | 对接现有 OneBot 机器人框架 | [OneBot 动作参考](docs/onebot-actions.md) | +| TypeScript SDK | 编写类型安全的客户端与消息逻辑 | [`packages/sdk`](packages/sdk/README.md) | +| MCP | 让支持 MCP 的工具查询或调用 SnowLuma 动作 | [`packages/mcp`](packages/mcp/README.md) | +| WebUI | 管理运行状态、日志、账号与连接 | 启动后访问 `http://localhost:5099` | + +## 开发与贡献 + +本地开发需要 Node.js 22+ 与项目锁定版本的 pnpm。所有日常开发基于 `dev` 分支: + +```bash +git clone https://github.com/SnowLuma/SnowLuma.git +cd SnowLuma +git checkout dev +pnpm install +pnpm typecheck +pnpm test +``` + +- 先读 [`CONTEXT.md`](CONTEXT.md) 了解模块边界与项目词汇。 +- 提交代码前阅读 [`CONTRIBUTING.md`](CONTRIBUTING.md) 与 [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md)。 +- 开发方向与已完成事项见 [`RoadMap.md`](RoadMap.md)。 + +
+主要目录 + +| 路径 | 作用 | +| --- | --- | +| `packages/protocol` | QQ 协议定义、数据包解析、消息推送与 OIDB 服务 | +| `packages/onebot` | OneBot 动作执行、事件转换与网络适配 | +| `packages/core` | 运行时编排、QQ 会话桥接与 WebUI 服务端 | +| `packages/webui` | React 管理界面 | +| `packages/sdk` | 对外发布的 TypeScript SDK | +| `packages/mcp` | 面向 MCP 客户端的动作目录与执行入口 | + +
+ +## 使用边界与许可 + +> [!IMPORTANT] +> SnowLuma 使用 **源码可见非商业许可**,**不是 OSI 开源许可**。源码可用于查看、学习、非商业自托管及私下修改;任何商业使用,以及公开发布修改版或衍生版,均需事先取得书面授权。 + +- 完整条款见 [`LICENSE`](LICENSE)。 +- 随附的原生附加组件为专有组件,不在源码许可范围内。 +- 二进制发行包另受 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md) 约束。 +- 商业授权请联系 `motricseven@foxmail.com`。 + +SnowLuma is source-available for study and non-commercial self-hosting, but it is **not OSI open source**. Commercial use and public distribution of modified or derivative versions require prior written permission. Bundled native components are proprietary and excluded from the source license. + +## 社区与支持 + +- [提交问题](https://github.com/SnowLuma/SnowLuma/issues) +- [QQ 群](https://qm.qq.com/q/g3UMLpWALe) +- [Telegram](https://t.me/napcatqq) ## 鸣谢 -参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。 - ---- +项目参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。

- + SnowLuma 贡献者

diff --git a/assets/readme/hero.svg b/assets/readme/hero.svg new file mode 100644 index 00000000..21203122 --- /dev/null +++ b/assets/readme/hero.svg @@ -0,0 +1,150 @@ + + SnowLuma — QQ 到 OneBot 的现代协议桥 + SnowLuma 将多个 QQ 原生会话经过协议、桥接与 OneBot 三层处理,连接到 WebSocket、HTTP、WebUI、SDK 与 MCP。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + QQ INTEROPERABILITY · ONEBOT V11 · MULTI-ACCOUNT + + + SnowLuma + + + + 把 QQ 原生会话,稳定地桥接到 + OneBot、WebUI 与自动化工具。 + + 一个运行时,管理多账号、动作调用、事件分发与实时状态。 + + + + + Windows x64 + + + + + Linux x64 / arm64 + + + + + + TypeScript + + + + + + LIVE SESSION ROUTING + + + + + + QQ · 01 + ONLINE + + + + + QQ · 02 + ONLINE + + + + + QQ · N + READY + + + + + + + + + + + SNOWLUMA RUNTIME + Protocol → Bridge → OneBot + 独立会话 · 类型化动作 · 可追踪事件 + + + + + + + + + + OneBot v11 + ACTIONS · EVENTS + + + + WebUI + STATUS · LOGS + + + + SDK / MCP + TOOLS · STREAMS + + + + diff --git a/assets/readme/runtime-map.svg b/assets/readme/runtime-map.svg new file mode 100644 index 00000000..497d025d --- /dev/null +++ b/assets/readme/runtime-map.svg @@ -0,0 +1,140 @@ + + SnowLuma 运行链路 + QQ 进程接入后,数据经过协议桥接、OneBot 标准化,再分发到 WebSocket、HTTP、WebUI、SDK 与 MCP。 + + + + + + + + + + + + + + + + + + + + + + + + + RUNTIME MAP · FROM SESSION TO CONSUMER + 一条事件如何穿过 SnowLuma + 每层只承担一种职责,多个 QQ 账号各自拥有独立、可追踪的会话链路。 + + + + PIPE + MAP + OUT + + + + + + + 01 · 会话接入 + + + + + + QQ · ACCOUNT 01 + QQ · ACCOUNT 02 + + + 多个 QQ 进程 + 独立接入、独立登录状态 + 每个账号单独路由 + + + + + + 02 · 协议桥接 + + + + + + PACKET → EVENT + PROTOCOL · BRIDGE + + + 解析与身份映射 + 协议数据转换为内部事件 + 异常路径保留可观察信息 + + + + + + 03 · 标准化 + + + + OneBot v11 + ACTIONS ↔ EVENTS + + + 统一动作与事件 + 参数校验、动作执行 + 事件转换与消息存储 + + + + + + 04 · 消费端 + 按场景自由组合 + + + + + WS + + + + HTTP + + + + WebUI + + + + SDK + + + + MCP + + + + 多个适配器可同时启用 + + + + + + 一次接入,统一管理运行状态、日志、连接与动作调用。 + SNOWLUMA / RUNTIME MAP + + diff --git a/package.json b/package.json index a3d8b830..a1dbe945 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "snowluma-monorepo", - "version": "1.12.2", + "version": "1.12.3", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index a3d5a52b..e67a7f4d 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/bridge", - "version": "1.12.2", + "version": "1.12.3", "private": true, "type": "module", "description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).", diff --git a/packages/bridge/src/hook-manager.ts b/packages/bridge/src/hook-manager.ts index 7c41b83a..2982ef36 100644 --- a/packages/bridge/src/hook-manager.ts +++ b/packages/bridge/src/hook-manager.ts @@ -29,6 +29,7 @@ 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; } export type HookManagerDeps = { @@ -68,7 +69,7 @@ export type HookManagerDeps = { * Responsibilities: * - Route user commands (load/unload/refresh) to the matching session. * - Route watcher diff events to the matching session. - * - Forward session events ('login' / 'disconnected') to BridgeManager. + * - Forward session events ('login' / 'disconnected' / receive health) to BridgeManager. * - Retry stuck-in-connecting sessions on every watcher tick (so a * failed connect eventually recovers without a manual refresh). * @@ -297,6 +298,9 @@ export class HookManager { 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. diff --git a/packages/bridge/src/hook-session.ts b/packages/bridge/src/hook-session.ts index 5300d4c6..ee41b298 100644 --- a/packages/bridge/src/hook-session.ts +++ b/packages/bridge/src/hook-session.ts @@ -14,6 +14,14 @@ import type { HookProcessInfo, HookProcessStatus } from './types'; * auto-login races/bypasses the pushed loginState frame). */ const LOGIN_RECONCILE_INTERVAL_MS = 3000; +/** QQ emits this response periodically while its MSF receive path is healthy. + * Seeing it once arms the watchdog; before that, silence is UNKNOWN rather + * than unhealthy so QQ versions that do not expose this command cannot be + * false-flagged. Any later recv packet proves the same end-to-end path. */ +const QQ_RECV_HEARTBEAT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat'; +const RECEIVE_STALE_AFTER_MS = 90_000; +const RECEIVE_STALE_CONFIRM_MS = 15_000; + export type HookSessionDeps = { injector: { inject: (pid: number) => HookInjectResult; @@ -53,6 +61,7 @@ export type HookSessionDeps = { * Emitted events: * 'login' (uin, packetSender) — real-UIN login detected * 'disconnected' (wasLoggedIn) — connection dropped or torn down + * 'receive-health-changed' (healthy) — receive path confirmed stale/recovered * 'status-changed' (status, error) — status field mutated * 'disposed' () — session stopped tracking this PID */ @@ -84,6 +93,11 @@ export class HookSession extends EventEmitter { private disposed = false; private loginProbeTimer: ReturnType | null = null; private probing = false; + private _receiveHealthy = true; + private receiveWatchUin = ''; + private receiveWatchArmed = false; + private receiveWatchTimer: ReturnType | null = null; + private lastReceiveAt = 0; constructor(pid: number, deps: HookSessionDeps) { super(); @@ -103,6 +117,7 @@ export class HookSession extends EventEmitter { get uin(): string { return this._uin; } get method(): string { return this._method; } get isDisposed(): boolean { return this.disposed; } + get receiveHealthy(): boolean { return this._receiveHealthy; } attachProcessInfo(info: { name?: string; path?: string }): void { if (info.name) this._name = info.name; @@ -404,6 +419,7 @@ export class HookSession extends EventEmitter { private tearDownClient(): void { this.stopLoginReconcile(); + this.resetReceiveWatch(); const client = this.client; if (client) { client.removeAllListeners(); @@ -423,7 +439,14 @@ export class HookSession extends EventEmitter { this.loggedIn = state.loggedIn && isRealUin(this._uin); // However login was observed (pushed frame or the active probe), the // safety net's job is done. - if (this.loggedIn) this.stopLoginReconcile(); + 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); + } else { + this.resetReceiveWatch(); + } // Only the connected/logged-in states are ours to set here; when fully // down we leave the status the teardown path already settled. @@ -494,6 +517,11 @@ export class HookSession extends EventEmitter { 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 @@ -517,6 +545,85 @@ export class HookSession extends EventEmitter { 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; + this._receiveHealthy = healthy; + this.emit('receive-health-changed', healthy); + } + + 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; + } } function errMsg(value: unknown): string { diff --git a/packages/bridge/tests/hook-manager-state-notify.test.ts b/packages/bridge/tests/hook-manager-state-notify.test.ts index 82ae3702..49115863 100644 --- a/packages/bridge/tests/hook-manager-state-notify.test.ts +++ b/packages/bridge/tests/hook-manager-state-notify.test.ts @@ -18,6 +18,7 @@ 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; @@ -45,7 +46,8 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): onPacket: vi.fn(), onHookLogin: vi.fn(), onPidDisconnected: vi.fn(), - } as unknown as BridgeManagerSink; + onPidReceiveHealthChanged: vi.fn(), + } as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType }; const onSessionsChanged = vi.fn(); const manager = new HookManager({ bridgeManager, @@ -61,6 +63,7 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): return { manager, pipeWatcher, + bridgeManager, onSessionsChanged, clientFactory, setProcesses: (next) => { pids = next; }, @@ -171,3 +174,42 @@ describe('HookManager.onSessionsChanged', () => { 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(); + + 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); + + 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-session.test.ts b/packages/bridge/tests/hook-session.test.ts index a9b555fe..cc7b6b28 100644 --- a/packages/bridge/tests/hook-session.test.ts +++ b/packages/bridge/tests/hook-session.test.ts @@ -652,6 +652,163 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () => }); }); +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'; + + 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) }); + } + + 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(); + + try { + firePacket(ctx, HEARTBEAT_CMD); + + vi.advanceTimersByTime(90_000); + expect(ctx.session.receiveHealthy).toBe(true); + + vi.advanceTimersByTime(15_000); + expect(ctx.session.receiveHealthy).toBe(false); + expect(healthChanges).toEqual([false]); + + firePacket(ctx, MESSAGE_CMD, '10001', 2); + + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([false, true]); + } 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(); + + try { + firePacket(ctx, MESSAGE_CMD); + + vi.advanceTimersByTime(10 * 60_000); + + 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(); + + try { + firePacket(ctx, HEARTBEAT_CMD); + + 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(); + } + }); + + 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); + + ctx.currentClient().fireLogin('20002'); + vi.advanceTimersByTime(10 * 60_000); + + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([]); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } + }); + + 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); + firePacket(ctx, MESSAGE_CMD, '20002', 2); + vi.advanceTimersByTime(10 * 60_000); + + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([]); + + firePacket(ctx, HEARTBEAT_CMD, '20002', 3); + vi.advanceTimersByTime(105_000); + + expect(ctx.session.receiveHealthy).toBe(false); + expect(healthChanges).toEqual([false]); + } finally { + ctx.session.dispose(); + vi.useRealTimers(); + } + }); + + 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); + + try { + firePacket(ctx, HEARTBEAT_CMD); + onPacket.mockClear(); + + 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(); + } + }); +}); + describe('HookSession — login reconcile does not stack concurrent probes', () => { it('skips overlapping ticks while a slow probe is in flight', async () => { vi.useFakeTimers(); diff --git a/packages/common/package.json b/packages/common/package.json index b80f4c37..a159cec7 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/common", - "version": "1.12.2", + "version": "1.12.3", "private": true, "type": "module", "description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).", diff --git a/packages/core/package.json b/packages/core/package.json index 665e0ccc..542a875b 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/core", - "version": "1.12.2", + "version": "1.12.3", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/core/src/bridge/apis/group-album.ts b/packages/core/src/bridge/apis/group-album.ts index 7a8b1205..f1a861e7 100644 --- a/packages/core/src/bridge/apis/group-album.ts +++ b/packages/core/src/bridge/apis/group-album.ts @@ -80,8 +80,9 @@ export class GroupAlbumApi { const resp = protobuf_decode(result.responseData); - if (resp.field1 !== 0) { - throw new Error(`fetch album media list error: retCode ${resp.field1 ?? 'unknown'}`); + const retCode = resp.field1 ?? 0; + if (retCode !== 0) { + throw new Error(`fetch album media list error: retCode ${retCode}`); } const data = resp.data ?? {}; diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index 8e455a39..d85a9f90 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -2,4 +2,7 @@ import type { BridgeContext } from './bridge-context'; export interface BridgeInterface extends BridgeContext { readonly activePid: number | null; + /** False only when every attached QQ process is confirmed stale. + * An unarmed watchdog remains true for compatibility. */ + readonly receiveHealthy: boolean; } diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index 8af920c4..a2fbba68 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -19,6 +19,7 @@ const log = createLogger('Bridge'); 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. */ @@ -97,6 +98,7 @@ export class Bridge implements BridgeInterface { dispose(): void { this.pids_.clear(); + this.receiveHealthByPid_.clear(); this.packetClientsByPid_.clear(); this.packetClient_ = null; this.packetClientPid_ = null; @@ -134,6 +136,10 @@ export class Bridge implements BridgeInterface { 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. @@ -153,6 +159,7 @@ export class Bridge implements BridgeInterface { detachPid(pid: number): void { this.pids_.delete(pid); + this.receiveHealthByPid_.delete(pid); this.packetClientsByPid_.delete(pid); if (this.packetClientPid_ !== pid) { @@ -177,6 +184,24 @@ export class Bridge implements BridgeInterface { 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); + } onPacket(pkt: PacketInfo): void { this.pipeline.process(pkt); } diff --git a/packages/core/src/bridge/manager.ts b/packages/core/src/bridge/manager.ts index 263d4d2e..6f60f645 100644 --- a/packages/core/src/bridge/manager.ts +++ b/packages/core/src/bridge/manager.ts @@ -60,6 +60,23 @@ export class BridgeManager { this.detachPidFromSession(pid, uin); } + 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; diff --git a/packages/core/src/webui/auth.ts b/packages/core/src/webui/auth.ts index 93e5fae0..3dcd2bba 100644 --- a/packages/core/src/webui/auth.ts +++ b/packages/core/src/webui/auth.ts @@ -64,16 +64,52 @@ function ensureConfigDir(): void { fs.mkdirSync(CONFIG_DIR, { recursive: true }); } -function isValidState(value: unknown): value is WebuiAuthState { - if (!value || typeof value !== 'object') return false; +/** + * Validate credential state before it crosses a persistence boundary. + * + * The hash/salt lengths are part of the on-disk contract: accepting any hex + * string here only postpones failure until password verification, where the + * 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; - return ( - typeof v.passwordHash === 'string' && - typeof v.passwordSalt === 'string' && - typeof v.mustChangePassword === 'boolean' && - /^[0-9a-f]+$/i.test(v.passwordHash) && - /^[0-9a-f]+$/i.test(v.passwordSalt) - ); + 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']); + const unknown = Object.keys(v).find((key) => !allowed.has(key)); + if (unknown) throw new Error(`unknown field $.${unknown}`); + return { + passwordHash: v.passwordHash, + passwordSalt: v.passwordSalt, + mustChangePassword: v.mustChangePassword, + generatedAt: v.generatedAt, + updatedAt: v.updatedAt, + }; +} + +function isValidState(value: unknown): value is WebuiAuthState { + try { + prepareWebuiAuthStateForRestore(value); + return true; + } catch { + return false; + } } function generateInitialState(initialPassword: string): WebuiAuthState { diff --git a/packages/core/src/webui/backup.ts b/packages/core/src/webui/backup.ts index 7a97a913..2feb1c4b 100644 --- a/packages/core/src/webui/backup.ts +++ b/packages/core/src/webui/backup.ts @@ -9,11 +9,23 @@ // OneBot access token, so a no-credentials backup must NOT include them. // cert.pem is public so it always travels. // -// Pure functions here (read/list/decode); the fs glue (atomic two-phase write, -// snapshot) lives in server.ts. Restore is restart-to-apply, like A1. +// Pure functions here own bundle validation and semantic preflight. Filesystem +// transaction choreography lives in restore.ts. A non-empty restore remains +// restart-to-apply, like A1. + +import { normalizeRuntimeConfig } from '@snowluma/common/runtime'; +import { isRealUin } from '@snowluma/common/uin'; +import { normalizeGlobalSettings } from '@snowluma/onebot/global-config'; +import { prepareOneBotConfigForRestore } from '@snowluma/onebot/config'; +import { isIP } from 'node:net'; +import { normalizeNotificationsConfig } from '../notifications/config'; +import { prepareWebuiAuthStateForRestore } from './auth'; +import { MAX_BACKGROUND_BYTES, normalizeStoredUiConfig, sniffImageMime } from './ui-config'; +import { validateTlsPair } from './tls'; export const BACKUP_VERSION = 1; 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. */ @@ -40,13 +52,18 @@ export const BACKUP_FILES: readonly BackupFileSpec[] = [ ]; const SPEC_BY_NAME = new Map(BACKUP_FILES.map((f) => [f.name, f])); -const PER_UIN_ONEBOT = /^onebot_\d+\.json$/; +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]); +} /** Resolve a file name (static or per-uin onebot pattern) to its spec, or null. */ export function specFor(name: string): BackupFileSpec | null { const s = SPEC_BY_NAME.get(name); if (s) return s; - if (PER_UIN_ONEBOT.test(name)) return { name, binary: false, credential: true }; + if (isPerUinOneBotName(name)) return { name, binary: false, credential: true }; return null; } @@ -71,7 +88,7 @@ export function buildBackup( const files: Record = {}; const all: BackupFileSpec[] = [ ...BACKUP_FILES, - ...perUinOnebotNames.filter((n) => PER_UIN_ONEBOT.test(n)).map((n) => ({ name: n, binary: false, credential: true })), + ...perUinOnebotNames.filter(isPerUinOneBotName).map((n) => ({ name: n, binary: false, credential: true })), ]; for (const spec of all) { if (spec.credential && !opts.includeCredentials) continue; @@ -84,8 +101,10 @@ export function buildBackup( return { version: BACKUP_VERSION, app: BACKUP_APP, createdAt, files }; } -/** Validate a parsed bundle wholesale — any defect rejects the whole import. */ -export function validateBackup(parsed: unknown): { ok: true; backup: Backup } | { ok: false; error: string } { +function validateBackupEntries( + 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' }; } @@ -97,7 +116,9 @@ export function validateBackup(parsed: unknown): { ok: true; backup: Backup } | } const files = b.files as Record; for (const [name, entry] of Object.entries(files)) { - if (!specFor(name)) return { ok: false, error: `unknown file in backup: ${name}` }; + 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}` }; @@ -106,23 +127,419 @@ export function validateBackup(parsed: unknown): { ok: true; backup: Backup } | 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; +} + +export interface RestoreMigration { + name: string; + fields: string[]; +} + +export interface PreparedRestorePlan { + 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[]; +} + +export class RestorePreflightError extends Error { + readonly file: string; + + constructor(file: string, message: string, options?: { cause?: unknown }) { + super(`${file}: ${message}`, options); + this.name = 'RestorePreflightError'; + this.file = file; + } +} + /** - * Decide what a (validated) bundle would restore: decode each non-skipped file - * to bytes. Pure — the caller (server.ts) does the atomic two-phase fs write so - * a mid-restore failure can't leave a half-applied live config. Credential - * files are skipped unless `restoreCredentials`. + * Validate every selected file semantically and materialize canonical bytes + * before the transaction is allowed to touch live configuration. */ -export function planRestore( - backup: Backup, - opts: { restoreCredentials: boolean }, -): { restore: Array<{ name: string; data: Buffer }>; skipped: string[] } { - const restore: Array<{ name: string; data: Buffer }> = []; +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); + + const restore: PreparedRestoreFile[] = []; const skipped: string[] = []; - for (const [name, entry] of Object.entries(backup.files)) { + 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) { skipped.push(name); continue; } // validated, but be defensive - if (spec.credential && !opts.restoreCredentials) { skipped.push(name); continue; } - restore.push({ name, data: Buffer.from(entry.data, entry.encoding) }); + 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 }); + } + + 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; + } + } + + 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'); +} + +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; +} + +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`); + } + 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 }); + } +} + +function prepareOneBotOrThrow( + 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 }); + } +} + +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 }); + } +} + +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 }); + } +} + +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 }; +} + +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; +} + +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 }; +} + +function assertNoLossyNormalization( + 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); + } + for (const key of Object.keys(canonical)) { + if (!Object.prototype.hasOwnProperty.call(raw, key)) additions.push(`${at}.${key}`); + } + 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`); + } + 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 isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function serializeJson(value: unknown): Buffer { + return Buffer.from(JSON.stringify(value, null, 2), 'utf8'); +} + +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}(? [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 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 (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 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 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}`, + ); } - return { restore, skipped }; } diff --git a/packages/core/src/webui/restore.ts b/packages/core/src/webui/restore.ts new file mode 100644 index 00000000..42e24251 --- /dev/null +++ b/packages/core/src/webui/restore.ts @@ -0,0 +1,391 @@ +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'; + +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; +} + +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; +} + +export interface RestoreBackupResult { + 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[]; + + 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; +} + +/** + * Restore one validated overlay as a process-level transaction. + * + * This deliberately does not promise recovery from power loss or SIGKILL. + * Within the running process, every failure before commit leaves live files + * untouched. A partial commit is rolled back when possible; incomplete + * 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; + } + }; + + 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 (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=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, + }; +} + +function rollbackCommitted( + 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 }); + } + } + 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; + } +} + +function invoke(options: RestoreBackupOptions, operation: RestoreOperation): void { + options.beforeOperation?.(operation); +} + +function errorMessage(error: unknown): string { + 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'; +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 2162de2c..45ad1ee8 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -13,7 +13,7 @@ import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/one import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime'; import { execSync } from 'child_process'; import { randomBytes } from 'crypto'; -import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, 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'; @@ -31,7 +31,8 @@ import { } from './consent'; import { resolveTlsContext, validateTlsPair } from './tls'; import { coerceSettingsPatch } from './system-settings'; -import { buildBackup, planRestore, validateBackup } from './backup'; +import { buildBackup } from './backup'; +import { restoreBackup, RestoreTransactionError, type RestorePhase } from './restore'; import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs'; import { createFramePusher } from './debug-stream'; import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools'; @@ -72,6 +73,82 @@ const TOKEN_TTL_MS = 24 * 60 * 60 * 1000; 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[]; +} + +/** Translate transaction facts into an operator-facing HTTP failure. */ +export function describeRestoreFailure(error: RestoreTransactionError): { + status: 400 | 500; + body: RestoreFailureBody; +} { + 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}。请检查服务器日志。`; + } + + 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'; +} + +/** 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; + } +} + +/** 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; + } +} + // Endpoints that an auth-required-but-must-change-password session can still hit. const MUST_CHANGE_ALLOWLIST = new Set([ '/api/status', @@ -855,27 +932,25 @@ export async function initWebUI( }); // ── Config backup / restore (Wave A2) ── - const cfgPath = (name: string) => path.join('config', name); - const readCfg = (name: string): Buffer | null => { - const p = cfgPath(name); - return existsSync(p) ? readFileSync(p) : null; - }; - - const listPerUinOnebot = (): string[] => { - try { - return existsSync('config') ? readdirSync('config').filter((n) => /^onebot_\d+\.json$/.test(n)) : []; - } catch { return []; } - }; - app.get('/api/system/backup/export', (c) => { - const includeCredentials = c.req.query('credentials') === '1'; - const ts = new Date().toISOString(); - const bundle = buildBackup(readCfg, listPerUinOnebot(), { includeCredentials }, ts); - c.header('Content-Disposition', `attachment; filename="snowluma-backup-${ts.replace(/[:.]/g, '-')}.json"`); - // Bundle may carry the TLS private key / password hash — never cache it. - c.header('Cache-Control', 'no-store, max-age=0'); - c.header('Pragma', 'no-cache'); - return c.json(bundle); + 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) => { @@ -893,50 +968,19 @@ export async function initWebUI( return c.json({ success: false, message: '请求格式错误' }, 400); } const { backup, restoreCredentials } = body as { backup?: unknown; restoreCredentials?: unknown }; - const v = validateBackup(backup); - if (!v.ok) return c.json({ success: false, message: v.error }, 400); - - const plan = planRestore(v.backup, { restoreCredentials: restoreCredentials === true }); - // Snapshot the current (about-to-be-overwritten) config so a restore is - // recoverable; one timestamped dir per import. - const snapDir = path.join('config', `.restore-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`); - // Two-phase write for near-atomicity: stage every file as a .tmp first, then - // rename them all. A failure during staging touches no live file; rename - // almost never fails, shrinking the half-applied window to near zero. - const staged: Array<{ tmp: string; dest: string; name: string }> = []; try { - for (const { name } of plan.restore) { - const src = cfgPath(name); - if (!existsSync(src)) continue; - const snap = path.join(snapDir, name); - mkdirSync(path.dirname(snap), { recursive: true }); - copyFileSync(src, snap); - } - for (const { name, data } of plan.restore) { - const dest = cfgPath(name); - mkdirSync(path.dirname(dest), { recursive: true }); - const tmp = dest + '.restore.tmp'; - writeFileSync(tmp, data, name === 'key.pem' ? { mode: 0o600 } : undefined); - staged.push({ tmp, dest, name }); - } - for (const { tmp, dest, name } of staged) { - renameSync(tmp, dest); - if (name === 'key.pem') { try { chmodSync(dest, 0o600); } catch { /* best-effort */ } } - } - return c.json({ - success: true, - restored: plan.restore.map((r) => r.name), - skipped: plan.skipped, - snapshotDir: snapDir, - restartRequiredToApply: true, + const result = restoreBackup(backup, { + configDir: 'config', + restoreCredentials: restoreCredentials === true, }); + return c.json({ success: true, ...result }); } catch (err) { - // Clean up any staged .tmp not yet renamed (staging-phase failure leaves - // the live config untouched; a rare rename-phase failure may be partial, - // recoverable from the snapshot dir). - for (const { tmp } of staged) { try { if (existsSync(tmp)) rmSync(tmp, { force: true }); } catch { /* ignore */ } } - log.warn('backup import failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '恢复失败;若为写入阶段失败则当前配置未改动,否则可从 config/.restore-backup-* 快照恢复' }, 500); + 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); } }); diff --git a/packages/core/src/webui/ui-config.ts b/packages/core/src/webui/ui-config.ts index 240d2970..b8830ac2 100644 --- a/packages/core/src/webui/ui-config.ts +++ b/packages/core/src/webui/ui-config.ts @@ -474,6 +474,11 @@ function imageStateFromParsed(parsed: unknown): ServerImageState { return sanitizeImageState(parsed.appearance.background); } +/** Normalize a complete ui.json read from disk or a backup bundle. */ +export function normalizeStoredUiConfig(value: unknown): UiConfig { + return normalizeUiConfig(value, imageStateFromParsed(value)); +} + function normalizeBackground(value: unknown, imageState: ServerImageState): UiBackground { const v = isObject(value) ? value : {}; let type = oneOf(v.type, ['none', 'solid', 'gradient', 'image'], DEFAULT_BACKGROUND.type); @@ -615,7 +620,7 @@ export function loadUiConfig(): UiConfig { const parsed = JSON.parse(raw) as unknown; // On load, the file itself is the source of truth for the server-managed // image fields — so they survive restarts (don't reset to defaults). - const normalized = normalizeUiConfig(parsed, imageStateFromParsed(parsed)); + const normalized = normalizeStoredUiConfig(parsed); // Re-persist only if normalization changed something (corrupt/old file), // so we self-heal on disk without rewriting on every boot. if (JSON.stringify(parsed) !== JSON.stringify(normalized)) { diff --git a/packages/core/tests/actions/group-album.test.ts b/packages/core/tests/actions/group-album.test.ts new file mode 100644 index 00000000..7cc2394d --- /dev/null +++ b/packages/core/tests/actions/group-album.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest'; +import type { GetMediaListResponse } from '@snowluma/proto-defs/oidb-actions/group-album'; +import { protobuf_encode } from '@snowluma/proton'; +import { GroupAlbumApi } from '../../src/bridge/apis/group-album'; +import { mockBridge } from './_helpers'; + +describe('apis/group-album', () => { + it('accepts a successful media-list response with an omitted zero retCode', async () => { + const bridge = mockBridge(); + bridge.sendRawPacket.mockResolvedValueOnce({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode({ + data: { + mediaList: [{ + type: 1, + uploader: '10001', + batchId: 123n, + uploadTime: 456n, + }], + nextAttachInfo: 'next-page', + }, + })), + }); + + const result = await new GroupAlbumApi(bridge as never).getMediaList(12345, 'album-id'); + + expect(result).toEqual({ + mediaList: [{ + type: 1, + image: null, + uploader: '10001', + batchId: '123', + uploadTime: '456', + }], + nextAttachInfo: 'next-page', + }); + }); +}); diff --git a/packages/core/tests/bridge-manager-ownership.test.ts b/packages/core/tests/bridge-manager-ownership.test.ts index 9acc8b02..974431c9 100644 --- a/packages/core/tests/bridge-manager-ownership.test.ts +++ b/packages/core/tests/bridge-manager-ownership.test.ts @@ -104,6 +104,24 @@ describe('BridgeManager PID ownership', () => { }); }); + it('reports an account healthy while any attached PID still receives packets', () => { + const manager = new BridgeManager(); + manager.onHookLogin(101, '10001', makeSender().client); + manager.onHookLogin(202, '10001', makeSender().client); + const bridge = manager.getSession('10001')!.bridge; + + expect(bridge.receiveHealthy).toBe(true); + + manager.onPidReceiveHealthChanged(101, false); + expect(bridge.receiveHealthy).toBe(true); + + manager.onPidReceiveHealthChanged(202, false); + expect(bridge.receiveHealthy).toBe(false); + + manager.onPidReceiveHealthChanged(101, true); + expect(bridge.receiveHealthy).toBe(true); + }); + it('prefers the most recently rebound live PID, then falls back by recency', async () => { const manager = new BridgeManager(); const first = makeSender(); diff --git a/packages/core/tests/msg-push-handler.test.ts b/packages/core/tests/msg-push-handler.test.ts index b3128296..6ba1dcef 100644 --- a/packages/core/tests/msg-push-handler.test.ts +++ b/packages/core/tests/msg-push-handler.test.ts @@ -66,10 +66,12 @@ function makeIdentity(members: GroupMemberInfo[] = []): IdentityService { return identity; } -function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin = GROUP_ID): PacketInfo { - const operatorBytes = operatorUid - ? protobuf_encode({ operatorField: { uid: operatorUid } }) - : new Uint8Array(0); +function makeGroupIncreasePacket( + memberUid: string, + operatorUid = '', + fromUin = GROUP_ID, + operatorBytes: Uint8Array = Buffer.from(operatorUid, 'utf8'), +): PacketInfo { const content = protobuf_encode({ groupUin: GROUP_ID, memberUid, @@ -95,6 +97,38 @@ function makeGroupIncreasePacket(memberUid: string, operatorUid = '', fromUin = }; } +function makeGroupDecreasePacket( + memberUid: string, + decreaseType: number, + operatorBytes: Uint8Array, + fromUin = GROUP_ID, +): PacketInfo { + const content = protobuf_encode({ + groupUin: GROUP_ID, + memberUid, + decreaseType, + operatorBytes, + }); + const body = protobuf_encode({ + message: { + responseHead: { fromUin }, + contentHead: { msgType: 34, timestamp: 1710000000 }, + body: { msgContent: content }, + }, + status: 0, + }); + + return { + pid: 1, + uin: SELF_UIN, + serviceCmd: MSG_PUSH_CMD, + seqId: 1, + retCode: 0, + fromClient: false, + body, + }; +} + describe('parseMsgPush group member increase', () => { it('does not fall back to the group id when a joining uid is unresolved', () => { const [event] = parseMsgPush(makeGroupIncreasePacket('u_new_member'), makeIdentity()) as GroupMemberJoin[]; @@ -106,7 +140,7 @@ describe('parseMsgPush group member increase', () => { expect(event.userUid).toBe('u_new_member'); }); - it('resolves joining uid and operator uid from the member cache when available', () => { + it('decodes the raw operator uid used by member-increase pushes (#228)', () => { const member = makeGroupMember(22222, 'u_member'); const operator = makeGroupMember(33333, 'u_operator'); const [event] = parseMsgPush( @@ -119,6 +153,58 @@ describe('parseMsgPush group member increase', () => { expect(event.userUid).toBe(member.uid); expect(event.operatorUid).toBe(operator.uid); }); + + it('reports malformed raw operator bytes with bounded context', () => { + const captured: string[] = []; + const unsubscribe = subscribeLogs((entry) => { + if (entry.scope === 'MsgPush') captured.push(entry.message); + }); + try { + const events = parseMsgPush( + makeGroupIncreasePacket('u_new_member', '', GROUP_ID, new Uint8Array([0xff])), + makeIdentity(), + ); + + expect(events).toEqual([]); + expect(captured.some((message) => + message.includes('group member increase operator UID') + && message.includes('bytes=1') + && message.includes('preview=ff'))).toBe(true); + } finally { + unsubscribe(); + } + }); +}); + +describe('parseMsgPush group member decrease', () => { + it('decodes a raw operator uid for ordinary member removals', () => { + const member = makeGroupMember(22222, 'u_member'); + const operator = makeGroupMember(33333, 'u_operator'); + const [event] = parseMsgPush( + makeGroupDecreasePacket(member.uid, 131, Buffer.from(operator.uid, 'utf8')), + makeIdentity([member, operator]), + ) as Extract[]; + + expect(event.userUin).toBe(member.uin); + expect(event.operatorUin).toBe(operator.uin); + expect(event.operatorUid).toBe(operator.uid); + expect(event.leaveType).toBe('kick'); + }); + + it('decodes nested operator info when the bot itself is kicked', () => { + const operator = makeGroupMember(33333, 'u_operator'); + const operatorBytes = protobuf_encode({ + operatorField: { uid: operator.uid }, + }); + const [event] = parseMsgPush( + makeGroupDecreasePacket('u_self', 3, operatorBytes), + makeIdentity([operator]), + ) as Extract[]; + + expect(event.operatorUin).toBe(operator.uin); + expect(event.operatorUid).toBe(operator.uid); + expect(event.leaveType).toBe('kick'); + }); }); describe('parseMsgPush Event0x210 subType=38 (acknowledged-but-silent)', () => { diff --git a/packages/core/tests/webui-backup-http.test.ts b/packages/core/tests/webui-backup-http.test.ts new file mode 100644 index 00000000..b3016c9c --- /dev/null +++ b/packages/core/tests/webui-backup-http.test.ts @@ -0,0 +1,35 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { + listPerUinOneBotConfigFiles, + readBackupConfigFile, +} from '../src/webui/server'; + +describe('backup filesystem adapter', () => { + let root: string; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-backup-http-')); + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + it('treats only a missing file as absent', () => { + expect(readBackupConfigFile(root, 'missing.json')).toBeNull(); + + fs.mkdirSync(path.join(root, 'runtime.json')); + expect(() => readBackupConfigFile(root, 'runtime.json')).toThrow(); + }); + + it('treats only a missing config directory as an empty OneBot list', () => { + expect(listPerUinOneBotConfigFiles(path.join(root, 'missing'))).toEqual([]); + + const notDirectory = path.join(root, 'not-a-directory'); + fs.writeFileSync(notDirectory, 'x'); + expect(() => listPerUinOneBotConfigFiles(notDirectory)).toThrow(); + }); +}); diff --git a/packages/core/tests/webui-backup.test.ts b/packages/core/tests/webui-backup.test.ts index e907ec13..446475b9 100644 --- a/packages/core/tests/webui-backup.test.ts +++ b/packages/core/tests/webui-backup.test.ts @@ -1,5 +1,12 @@ import { describe, it, expect } from 'vitest'; -import { BACKUP_FILES, specFor, buildBackup, validateBackup, planRestore } from '../src/webui/backup'; +import { + BACKUP_FILES, + MAX_BACKUP_DECODED_BYTES, + RestorePreflightError, + specFor, + buildBackup, + prepareRestorePlan, +} from '../src/webui/backup'; const TS = '2026-06-18T00:00:00.000Z'; @@ -39,6 +46,11 @@ describe('buildBackup', () => { ); }); + it('does not export a per-UIN file that the import allowlist must reject', () => { + const b = buildBackup(reader({ 'onebot_1.json': Buffer.from('{}') }), ['onebot_1.json'], { includeCredentials: true }, TS); + expect(b.files).toEqual({}); + }); + it('base64-encodes binary files (background image)', () => { const png = Buffer.from([0x89, 0x50, 0x4e, 0x47]); const b = buildBackup(reader({ 'ui-assets/background': png }), [], { includeCredentials: false }, TS); @@ -54,70 +66,8 @@ describe('specFor', () => { expect(specFor('onebot_.json')).toBeNull(); expect(specFor('../evil')).toBeNull(); expect(specFor('onebot_12.json.bak')).toBeNull(); - }); -}); - -describe('validateBackup', () => { - const good = { version: 1, app: 'snowluma', files: { 'runtime.json': { encoding: 'utf8', data: '{}' } } }; - - it('accepts a well-formed bundle (incl. per-uin onebot)', () => { - expect(validateBackup(good).ok).toBe(true); - expect(validateBackup({ ...good, files: { 'onebot_42.json': { encoding: 'utf8', data: '{}' } } }).ok).toBe(true); - }); - - it('rejects a non-object / wrong app / wrong version', () => { - expect(validateBackup(null).ok).toBe(false); - expect(validateBackup({ ...good, app: 'other' }).ok).toBe(false); - expect(validateBackup({ ...good, version: 999 }).ok).toBe(false); - }); - - it('rejects an unknown / path-traversal filename', () => { - expect(validateBackup({ ...good, files: { '../evil': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false); - expect(validateBackup({ ...good, files: { 'unknown.json': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false); - expect(validateBackup({ ...good, files: { 'onebot_../x.json': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false); - }); - - it('rejects a malformed entry', () => { - expect(validateBackup({ ...good, files: { 'runtime.json': { encoding: 'rot13', data: 'x' } } }).ok).toBe(false); - expect(validateBackup({ ...good, files: { 'runtime.json': { encoding: 'utf8' } } }).ok).toBe(false); - }); -}); - -describe('planRestore', () => { - it('decodes restored files to bytes (utf8 + base64)', () => { - const png = Buffer.from([1, 2, 3, 4]); - const backup = { - version: 1, app: 'snowluma', - files: { - 'runtime.json': { encoding: 'utf8' as const, data: '{"a":1}' }, - 'ui-assets/background': { encoding: 'base64' as const, data: png.toString('base64') }, - }, - }; - const { restore, skipped } = planRestore(backup, { restoreCredentials: false }); - expect(skipped).toEqual([]); - const byName = Object.fromEntries(restore.map((r) => [r.name, r.data])); - expect(byName['runtime.json'].toString()).toBe('{"a":1}'); - expect(byName['ui-assets/background'].equals(png)).toBe(true); - }); - - it('skips all credential files unless restoreCredentials', () => { - const backup = { - version: 1, app: 'snowluma', - files: { - 'runtime.json': { encoding: 'utf8' as const, data: '{}' }, - 'webui.json': { encoding: 'utf8' as const, data: '{"hash":"x"}' }, - 'key.pem': { encoding: 'utf8' as const, data: 'KEY' }, - 'onebot.json': { encoding: 'utf8' as const, data: '{"accessToken":"t"}' }, - 'onebot_7.json': { encoding: 'utf8' as const, data: '{"accessToken":"t"}' }, - }, - }; - const skip = planRestore(backup, { restoreCredentials: false }); - expect(skip.restore.map((r) => r.name)).toEqual(['runtime.json']); - expect(skip.skipped.sort()).toEqual(['key.pem', 'onebot.json', 'onebot_7.json', 'webui.json']); - const keep = planRestore(backup, { restoreCredentials: true }); - expect(keep.restore.map((r) => r.name).sort()).toEqual( - ['key.pem', 'onebot.json', 'onebot_7.json', 'runtime.json', 'webui.json'], - ); + expect(specFor('onebot_1.json')).toBeNull(); + expect(specFor('onebot_12345678901.json')).toBeNull(); }); }); @@ -126,3 +76,684 @@ it('BACKUP_FILES marks webui.json / key.pem / onebot.json as credentials, cert.p expect(creds).toEqual(['key.pem', 'onebot.json', 'webui.json']); expect(specFor('cert.pem')?.credential).toBe(false); }); + +describe('prepareRestorePlan — strict semantic preflight', () => { + const backupWith = (files: Record) => ({ + version: 1, + app: 'snowluma', + files, + }); + + it.each([ + ['non-object bundle', null, /backup must be an object/i], + ['wrong app', { version: 1, app: 'other', files: {} }, /not a SnowLuma backup/i], + ['wrong version', { version: 999, app: 'snowluma', files: {} }, /unsupported backup version/i], + [ + 'malformed entry', + { version: 1, app: 'snowluma', files: { 'runtime.json': { encoding: 'utf8' } } }, + /bad data for runtime\.json/i, + ], + ])('rejects %s through the production preflight entrypoint', (_label, input, expected) => { + expect(() => prepareRestorePlan(input, { + restoreCredentials: false, + readCurrent: () => null, + })).toThrow(expected); + }); + + it('canonicalizes a recognized older runtime config and reports added fields', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: '{"webuiPort":5099}' }, + }), + { restoreCredentials: false, readCurrent: () => null }, + ); + + expect(JSON.parse(prepared.restore[0].data.toString('utf8'))).toEqual({ + webuiPort: 5099, + hookAutoLoad: false, + webuiHost: '0.0.0.0', + webuiTls: { enabled: false }, + trustProxy: '', + }); + expect(prepared.migrated).toEqual([{ + name: 'runtime.json', + fields: ['$.hookAutoLoad', '$.trustProxy', '$.webuiHost', '$.webuiTls'], + }]); + }); + + it('rejects a present runtime value that normalization would silently replace', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: '{"webuiPort":70000}' }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrowError(expect.objectContaining>({ + name: 'RestorePreflightError', + file: 'runtime.json', + })); + }); + + it('rejects a notification channel that total normalization would silently drop', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'notifications.json': { + encoding: 'utf8', + data: JSON.stringify({ + version: 1, + debounceSeconds: 30, + channels: [{ id: 'ops', name: 'Ops', url: 'file:///tmp/leak', bodyTemplate: '{}', enabled: true }], + }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/notifications\.json.*channels/i); + }); + + it('does not validate credential files that the operator chose to skip', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'webui.json': { encoding: 'utf8', data: '{definitely broken' }, + 'runtime.json': { encoding: 'utf8', data: '{}' }, + }), + { restoreCredentials: false, readCurrent: () => null }, + ); + + expect(prepared.skipped).toEqual(['webui.json']); + expect(prepared.restore.map((entry) => entry.name)).toEqual(['runtime.json']); + }); + + it('does not require even a well-formed entry envelope for a skipped credential', () => { + const prepared = prepareRestorePlan({ + version: 1, + app: 'snowluma', + files: { + 'webui.json': { encoding: 'rot13' }, + 'runtime.json': { encoding: 'utf8', data: '{}' }, + }, + }, { restoreCredentials: false, readCurrent: () => null }); + + expect(prepared.skipped).toEqual(['webui.json']); + expect(prepared.restore.map((entry) => entry.name)).toEqual(['runtime.json']); + }); + + it('rejects malformed WebUI credential state when credential restore is enabled', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'webui.json': { + encoding: 'utf8', + data: JSON.stringify({ passwordHash: 'zz', passwordSalt: '00', mustChangePassword: false }), + }, + }), + { restoreCredentials: true, readCurrent: () => null, listCurrentOneBotNames: () => [] }, + )).toThrow(/webui\.json.*passwordHash/i); + }); + + it('does not copy malformed sensitive JSON contents into the reported error', () => { + const secret = 'super-secret-token'; + let thrown: unknown; + try { + prepareRestorePlan( + backupWith({ + 'onebot.json': { encoding: 'utf8', data: secret }, + }), + { restoreCredentials: true, readCurrent: () => null, listCurrentOneBotNames: () => [] }, + ); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + name: 'RestorePreflightError', + message: 'onebot.json: invalid JSON', + })); + expect((thrown as Error).message).not.toContain(secret); + }); + + it('rejects a background blob whose bytes are not a supported image', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'ui-assets/background': { + encoding: 'base64', + data: Buffer.from('not an image').toString('base64'), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/ui-assets\/background.*PNG.*JPEG.*WebP/i); + }); + + it('rejects an invalid effective TLS pair', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'cert.pem': { encoding: 'utf8', data: 'not a certificate' }, + 'key.pem': { encoding: 'utf8', data: 'not a private key' }, + }), + { restoreCredentials: true, readCurrent: () => null }, + )).toThrow(/cert\.pem.*key\.pem/i); + }); + + it('fails fast when TLS validation needs a malformed current runtime config', () => { + const secret = 'runtime-secret-fragment'; + let thrown: unknown; + + try { + prepareRestorePlan( + backupWith({ + 'cert.pem': { encoding: 'utf8', data: 'not a certificate' }, + }), + { + restoreCredentials: false, + readCurrent: (name) => name === 'runtime.json' ? Buffer.from(secret) : null, + }, + ); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + name: 'RestorePreflightError', + message: 'runtime.json: effective runtime config is invalid JSON', + })); + expect((thrown as Error).message).not.toContain(secret); + }); + + it('assigns restrictive modes to every credential file', () => { + const validAuth = { + passwordHash: 'ab'.repeat(64), + passwordSalt: 'cd'.repeat(16), + mustChangePassword: false, + generatedAt: TS, + updatedAt: TS, + }; + const prepared = prepareRestorePlan( + backupWith({ + 'webui.json': { encoding: 'utf8', data: JSON.stringify(validAuth) }, + }), + { restoreCredentials: true, readCurrent: () => null, listCurrentOneBotNames: () => [] }, + ); + + expect(prepared.restore).toEqual([ + expect.objectContaining({ name: 'webui.json', mode: 0o600 }), + ]); + }); + + it('rejects an encoding that does not match the allowlisted file kind', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'base64', data: Buffer.from('{}').toString('base64') }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/runtime\.json.*encoding must be utf8/i); + }); + + it('rejects non-canonical base64 instead of accepting Node partial decoding', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'ui-assets/background': { encoding: 'base64', data: '%%%%' }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/background.*canonical base64/i); + }); + + it('enforces the decoded-byte cap independently of request Content-Length', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'cert.pem': { encoding: 'utf8', data: 'x'.repeat(MAX_BACKUP_DECODED_BYTES + 1) }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/decoded bytes/i); + }); + + it('rejects lossy normalization in global SnowLuma settings', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'snowluma.json': { + encoding: 'utf8', + data: JSON.stringify({ rkey: { fallbackServers: ['file:///tmp/not-http'] }, musicSignUrl: '' }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/snowluma\.json.*fallbackServers/i); + }); + + it('rejects a present invalid UI value instead of silently defaulting it', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'ui.json': { + encoding: 'utf8', + data: JSON.stringify({ appearance: { mode: 'ultraviolet' } }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/ui\.json.*mode/i); + }); + + it('migrates a known legacy per-account OneBot layout to a canonical overlay', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + httpServers: [{ name: 'legacy-http', port: '3100' }], + messageFormat: 'string', + reportSelfMessage: true, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.mode).toBe('overlay'); + expect(canonical.networks.httpServers).toEqual([expect.objectContaining({ + name: 'legacy-http', + port: 3100, + messageFormat: 'string', + reportSelfMessage: true, + })]); + expect(prepared.migrated).toEqual([{ name: 'onebot_12345.json', fields: ['$'] }]); + }); + + it('rejects a OneBot adapter that compatibility parsing would discard', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ networks: { httpServers: [{ name: 'broken', port: 0 }] } }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + )).toThrow(/onebot_12345\.json.*port/i); + }); + + it('rejects enabling TLS when the effective pair is incomplete', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'runtime.json': { + encoding: 'utf8', + data: JSON.stringify({ webuiTls: { enabled: true } }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/cert\.pem.*key\.pem.*incomplete/i); + }); + + it('rejects a UI config that claims a background image which is absent from the effective overlay', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'ui.json': { + encoding: 'utf8', + data: JSON.stringify({ + appearance: { + background: { + type: 'image', + hasImage: true, + imageMime: 'image/png', + imageVersion: 1, + }, + }, + }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/ui\.json.*background.*missing/i); + }); + + it('does not expose malformed current UI contents while validating a restored background', () => { + const secret = 'ui-secret-fragment'; + let thrown: unknown; + + try { + prepareRestorePlan( + backupWith({ + 'ui-assets/background': { + encoding: 'base64', + data: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).toString('base64'), + }, + }), + { + restoreCredentials: false, + readCurrent: (name) => name === 'ui.json' ? Buffer.from(secret) : null, + }, + ); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + name: 'RestorePreflightError', + message: 'ui.json: effective UI config is invalid JSON', + })); + expect((thrown as Error).message).not.toContain(secret); + }); + + it('rejects a OneBot global/per-account overlay that is invalid only after merge', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'onebot.json': { + encoding: 'utf8', + data: JSON.stringify({ + httpServers: [{ name: 'dup', port: 3100 }], + }), + }, + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'overlay', + wsClients: [{ name: 'dup', url: 'ws://127.0.0.1:9000' }], + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null, listCurrentOneBotNames: () => [] }, + )).toThrow(/onebot_12345\.json.*duplicated/i); + }); + + it('validates current per-account overlays affected by a restored global OneBot config', () => { + const currentPerUin = Buffer.from(JSON.stringify({ + mode: 'overlay', + wsClients: [{ name: 'dup', url: 'ws://127.0.0.1:9000' }], + })); + expect(() => prepareRestorePlan( + backupWith({ + 'onebot.json': { + encoding: 'utf8', + data: JSON.stringify({ httpServers: [{ name: 'dup', port: 3100 }] }), + }, + }), + { + restoreCredentials: true, + readCurrent: (name) => name === 'onebot_54321.json' ? currentPerUin : null, + listCurrentOneBotNames: () => ['onebot_54321.json'], + }, + )).toThrow(/onebot_54321\.json.*duplicated/i); + }); + + it('canonicalizes a per-account overlay against the effective global OneBot config', () => { + const currentGlobal = Buffer.from(JSON.stringify({ + messageFormat: 'string', + reportSelfMessage: true, + statusCommand: { trigger: '#global' }, + notifications: { channelIds: ['ops'] }, + })); + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'overlay', + httpClients: [{ name: 'remote', url: 'https://example.test/onebot' }], + }), + }, + }), + { + restoreCredentials: true, + readCurrent: (name) => name === 'onebot.json' ? currentGlobal : null, + }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.mode).toBe('overlay'); + expect(canonical.networks.httpClients[0]).toEqual(expect.objectContaining({ + messageFormat: 'string', + reportSelfMessage: true, + })); + expect(canonical.statusCommand.trigger).toBe('#global'); + expect(canonical.notifications.channelIds).toEqual(['ops']); + }); + + it('accepts lossless scalar spellings already supported by the runtime owner', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'runtime.json': { + encoding: 'utf8', + data: JSON.stringify({ webuiPort: '5099', hookAutoLoad: 1, webuiTls: { enabled: 0 } }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.webuiPort).toBe(5099); + expect(canonical.hookAutoLoad).toBe(true); + expect(canonical.webuiTls.enabled).toBe(false); + }); + + it('accepts owner-supported whitespace trimming without accepting changed values', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'snowluma.json': { + encoding: 'utf8', + data: JSON.stringify({ + rkey: { fallbackServers: [' https://a.example/r '] }, + musicSignUrl: ' https://sign.example/card ', + }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + ); + + expect(JSON.parse(prepared.restore[0].data.toString('utf8'))).toEqual({ + rkey: { fallbackServers: ['https://a.example/r'] }, + musicSignUrl: 'https://sign.example/card', + }); + }); + + it('does not read an unrelated current global OneBot file for a snapshot restore', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ mode: 'snapshot' }), + }, + }), + { + restoreCredentials: true, + readCurrent: (name) => name === 'onebot.json' ? Buffer.from('{broken') : null, + }, + ); + + expect(JSON.parse(prepared.restore[0].data.toString('utf8')).mode).toBe('snapshot'); + }); + + it('canonicalizes owner-supported OneBot notification id trimming and deduplication', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'snapshot', + notifications: { channelIds: [' ops ', 'ops'] }, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.notifications.channelIds).toEqual(['ops']); + }); + + it('accepts disabled OneBot clients whose legacy config omitted the unused URL', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'snapshot', + networks: { + httpClients: [{ name: 'http-off', enabled: false }], + wsClients: [{ name: 'ws-off', enabled: false }], + }, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.networks.httpClients[0].url).toBe(''); + expect(canonical.networks.wsClients[0].url).toBe(''); + }); + + it('measures a OneBot status trigger after owner-supported whitespace trimming', () => { + const trigger = 'a'.repeat(32); + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'snapshot', + statusCommand: { trigger: ` ${trigger} ` }, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.statusCommand.trigger).toBe(trigger); + }); + + it('preserves the missing musicSignUrl migration sentinel in an older global config', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'snowluma.json': { + encoding: 'utf8', + data: JSON.stringify({ rkey: { fallbackServers: [] } }), + }, + 'onebot.json': { + encoding: 'utf8', + data: JSON.stringify({ musicSignUrl: 'https://legacy.example/sign' }), + }, + }), + { + restoreCredentials: true, + readCurrent: () => null, + listCurrentOneBotNames: () => [], + }, + ); + + const byName = Object.fromEntries(prepared.restore.map((file) => [ + file.name, + JSON.parse(file.data.toString('utf8')), + ])); + expect(byName['snowluma.json']).not.toHaveProperty('musicSignUrl'); + expect(byName['onebot.json'].musicSignUrl).toBe('https://legacy.example/sign'); + }); + + it('preserves legacy per-account defaults that apply to inherited global adapters', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot.json': { + encoding: 'utf8', + data: JSON.stringify({ httpServers: [{ name: 'global-http', port: 3100 }] }), + }, + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ messageFormat: 'string', reportSelfMessage: true }), + }, + }), + { + restoreCredentials: true, + readCurrent: () => null, + listCurrentOneBotNames: () => [], + }, + ); + + const perUin = prepared.restore.find((file) => file.name === 'onebot_12345.json')!; + expect(JSON.parse(perUin.data.toString('utf8')).networks.httpServers[0]).toEqual(expect.objectContaining({ + name: 'global-http', + messageFormat: 'string', + reportSelfMessage: true, + })); + }); + + it('rejects per-account filenames that startup would immediately delete', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'onebot_1.json': { encoding: 'utf8', data: JSON.stringify({ mode: 'snapshot' }) }, + }), + { restoreCredentials: true, readCurrent: () => null }, + )).toThrow(/unknown file/i); + }); + + it('rejects syntactically invalid WebUI and OneBot bind hosts', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: JSON.stringify({ webuiHost: 'bad host' }) }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/runtime\.json.*webuiHost/i); + + expect(() => prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'snapshot', + networks: { httpServers: [{ name: 'bad', host: 'bad host', port: 3100 }] }, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + )).toThrow(/onebot_12345\.json.*host/i); + }); + + it('keeps valid IPv6 bind hosts while applying syntax checks', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: JSON.stringify({ webuiHost: '::' }) }, + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'snapshot', + networks: { httpServers: [{ name: 'v6', host: '::1', port: 3100 }] }, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + ); + + expect(prepared.restore.map((file) => file.name).sort()).toEqual(['onebot_12345.json', 'runtime.json']); + }); + + it('rejects malformed IPv6 zone syntax that Node cannot bind', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: JSON.stringify({ webuiHost: '::1%bad%extra' }) }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/runtime\.json.*webuiHost/i); + }); + + it('ignores untouched invalid PEM files while effective TLS is disabled', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: '{}' }, + }), + { + restoreCredentials: false, + readCurrent: (name) => name === 'cert.pem' || name === 'key.pem' ? Buffer.from('invalid PEM') : null, + }, + ); + + expect(prepared.restore.map((file) => file.name)).toEqual(['runtime.json']); + }); + + it('does not inspect invalid per-UIN files that startup cleanup owns', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot.json': { encoding: 'utf8', data: '{}' }, + }), + { + restoreCredentials: true, + readCurrent: (name) => { + if (name === 'onebot_1.json') throw new Error('invalid UIN file should not be read'); + return null; + }, + listCurrentOneBotNames: () => ['onebot_1.json'], + }, + ); + + expect(prepared.restore.map((file) => file.name)).toEqual(['onebot.json']); + }); +}); diff --git a/packages/core/tests/webui-restore-http.test.ts b/packages/core/tests/webui-restore-http.test.ts new file mode 100644 index 00000000..16097822 --- /dev/null +++ b/packages/core/tests/webui-restore-http.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, it } from 'vitest'; +import { RestorePreflightError } from '../src/webui/backup'; +import { describeRestoreFailure } from '../src/webui/server'; +import { RestoreTransactionError } from '../src/webui/restore'; + +function failure( + phase: RestoreTransactionError['phase'], + options: Partial<{ + cause: unknown; + rollbackSucceeded: boolean; + snapshotDir: string; + committed: boolean; + failedFiles: string[]; + }> = {}, +): RestoreTransactionError { + return new RestoreTransactionError({ + phase, + transactionId: `tx-${phase}`, + message: `restore ${phase} failed`, + cause: options.cause ?? new Error(`${phase} root cause`), + rollbackSucceeded: options.rollbackSucceeded, + snapshotDir: options.snapshotDir, + committed: options.committed, + failedFiles: options.failedFiles, + }); +} + +describe('describeRestoreFailure', () => { + it('returns a client error with the semantic preflight detail', () => { + const error = failure('preflight', { + cause: new RestorePreflightError('runtime.json', '$.webuiPort must be 1-65535'), + failedFiles: ['runtime.json'], + }); + + expect(describeRestoreFailure(error)).toEqual({ + status: 400, + body: { + success: false, + message: '备份校验失败:runtime.json: $.webuiPort must be 1-65535', + transactionId: 'tx-preflight', + phase: 'preflight', + committed: false, + failedFiles: ['runtime.json'], + }, + }); + }); + + it('says the live config was rolled back after a commit failure', () => { + const error = failure('commit', { + rollbackSucceeded: true, + failedFiles: ['notifications.json'], + }); + + expect(describeRestoreFailure(error)).toEqual({ + status: 500, + body: { + success: false, + message: '恢复失败,当前配置已自动回滚。事务 ID:tx-commit。请检查服务器日志。', + transactionId: 'tx-commit', + phase: 'commit', + committed: false, + rollbackSucceeded: true, + failedFiles: ['notifications.json'], + }, + }); + }); + + it('keeps recovery coordinates visible when rollback is incomplete', () => { + const error = failure('rollback', { + rollbackSucceeded: false, + committed: true, + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-rollback', + failedFiles: ['runtime.json'], + }); + + const response = describeRestoreFailure(error); + expect(response.status).toBe(500); + expect(response.body).toEqual(expect.objectContaining({ + success: false, + transactionId: 'tx-rollback', + phase: 'rollback', + committed: true, + rollbackSucceeded: false, + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-rollback', + failedFiles: ['runtime.json'], + })); + expect(response.body.message).toContain('自动回滚不完整'); + expect(response.body.message).toContain('请勿重启或继续修改配置'); + expect(response.body.message).toContain('/srv/snowluma/config/.restore-transaction-tx-rollback'); + }); + + it('distinguishes a committed restore from a failed restore when only cleanup fails', () => { + const error = failure('cleanup', { + committed: true, + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-cleanup', + }); + + const response = describeRestoreFailure(error); + expect(response.status).toBe(500); + expect(response.body).toEqual(expect.objectContaining({ + success: false, + transactionId: 'tx-cleanup', + phase: 'cleanup', + committed: true, + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-cleanup', + })); + expect(response.body.message).toContain('配置已恢复'); + expect(response.body.message).toContain('重启后配置仍会生效'); + expect(response.body.message).toContain('/srv/snowluma/config/.restore-transaction-tx-cleanup'); + }); + + it('surfaces retained transaction files when pre-commit cleanup fails', () => { + const error = failure('cleanup', { + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-cleanup', + failedFiles: ['notifications.json'], + }); + + const response = describeRestoreFailure(error); + expect(response.body.message).toContain('当前配置未改动'); + expect(response.body.message).toContain('临时事务目录清理失败'); + expect(response.body.message).toContain('/srv/snowluma/config/.restore-transaction-tx-cleanup'); + }); + + it('surfaces retained transaction files after rollback cleanup fails', () => { + const error = failure('cleanup', { + rollbackSucceeded: true, + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-cleanup', + failedFiles: ['notifications.json'], + }); + + const response = describeRestoreFailure(error); + expect(response.body.message).toContain('当前配置已自动回滚'); + expect(response.body.message).toContain('临时事务目录清理失败'); + expect(response.body.message).toContain('/srv/snowluma/config/.restore-transaction-tx-cleanup'); + }); +}); diff --git a/packages/core/tests/webui-restore.test.ts b/packages/core/tests/webui-restore.test.ts new file mode 100644 index 00000000..b7659bfd --- /dev/null +++ b/packages/core/tests/webui-restore.test.ts @@ -0,0 +1,366 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { + RestoreTransactionError, + restoreBackup, + type RestoreOperation, +} from '../src/webui/restore'; + +const TS = '2026-06-18T00:00:00.000Z'; + +function backupWith(files: Record) { + return { version: 1, app: 'snowluma', files }; +} + +function runtime(port: number): { encoding: 'utf8'; data: string } { + return { encoding: 'utf8', data: JSON.stringify({ webuiPort: port }) }; +} + +function notifications(seconds: number): { encoding: 'utf8'; data: string } { + return { + encoding: 'utf8', + data: JSON.stringify({ version: 1, debounceSeconds: seconds, channels: [] }), + }; +} + +function validAuth() { + return { + passwordHash: 'ab'.repeat(64), + passwordSalt: 'cd'.repeat(16), + mustChangePassword: false, + generatedAt: TS, + updatedAt: TS, + }; +} + +describe('restoreBackup transaction', () => { + let root: string; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-restore-')); + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + const livePath = (name: string) => path.join(root, name); + const writeLive = (name: string, data: string, mode = 0o644) => { + fs.mkdirSync(path.dirname(livePath(name)), { recursive: true }); + fs.writeFileSync(livePath(name), data, { mode }); + fs.chmodSync(livePath(name), mode); + }; + const readLive = (name: string) => fs.readFileSync(livePath(name), 'utf8'); + const transactionDirs = () => fs.readdirSync(root).filter((name) => name.startsWith('.restore-transaction-')); + + function run( + files: Record, + beforeOperation?: (operation: RestoreOperation) => void, + ) { + return restoreBackup(backupWith(files), { + configDir: root, + restoreCredentials: true, + transactionId: 'test-transaction', + beforeOperation, + }); + } + + it('commits every prepared file, enforces credential mode, and removes the temporary snapshot', () => { + writeLive('runtime.json', '{"old":true}'); + writeLive('webui.json', JSON.stringify(validAuth()), 0o644); + + const result = run({ + 'runtime.json': runtime(5100), + 'webui.json': { encoding: 'utf8', data: JSON.stringify(validAuth()) }, + }); + + expect(JSON.parse(readLive('runtime.json')).webuiPort).toBe(5100); + expect(JSON.parse(readLive('webui.json')).passwordHash).toBe(validAuth().passwordHash); + expect(fs.statSync(livePath('webui.json')).mode & 0o777).toBe(0o600); + expect(result).toEqual(expect.objectContaining({ + transactionId: 'test-transaction', + restored: ['runtime.json', 'webui.json'], + skipped: [], + restartRequiredToApply: true, + })); + expect(transactionDirs()).toEqual([]); + }); + + it('does not request a restart or create a transaction when nothing is selected', () => { + const result = run({}); + + expect(result).toEqual(expect.objectContaining({ + restored: [], + skipped: [], + migrated: [], + restartRequiredToApply: false, + })); + expect(transactionDirs()).toEqual([]); + }); + + it.each([ + ['snapshot', 'copy-current'], + ['stage', 'write-staged'], + ['stage', 'chmod-staged'], + ] as const)('leaves every live file untouched when %s fails', (phase, operation) => { + const oldRuntime = '{"old":"runtime"}'; + const oldNotifications = '{"old":"notifications"}'; + writeLive('runtime.json', oldRuntime); + writeLive('notifications.json', oldNotifications); + + expect(() => run({ + 'runtime.json': runtime(5101), + 'notifications.json': notifications(45), + }, (point) => { + if (point.phase === phase && point.operation === operation && point.file === 'notifications.json') { + throw new Error(`injected ${phase} failure`); + } + })).toThrow(RestoreTransactionError); + + expect(readLive('runtime.json')).toBe(oldRuntime); + expect(readLive('notifications.json')).toBe(oldNotifications); + expect(transactionDirs()).toEqual([]); + }); + + it('rolls every file back when a later commit rename fails', () => { + const oldRuntime = '{"old":"runtime"}'; + const oldNotifications = '{"old":"notifications"}'; + writeLive('runtime.json', oldRuntime); + writeLive('notifications.json', oldNotifications); + + let thrown: unknown; + try { + run({ + 'runtime.json': runtime(5102), + 'notifications.json': notifications(60), + }, (point) => { + if (point.phase === 'commit' && point.operation === 'rename-staged' && point.file === 'notifications.json') { + throw new Error('injected commit failure'); + } + }); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + name: 'RestoreTransactionError', + phase: 'commit', + rollbackSucceeded: true, + committed: false, + })); + expect(readLive('runtime.json')).toBe(oldRuntime); + expect(readLive('notifications.json')).toBe(oldNotifications); + expect(transactionDirs()).toEqual([]); + }); + + it('removes files that did not exist before when rolling a partial commit back', () => { + const oldRuntime = '{"old":"runtime"}'; + const oldUi = '{}'; + writeLive('runtime.json', oldRuntime); + writeLive('ui.json', oldUi); + + expect(() => run({ + 'runtime.json': runtime(5103), + 'notifications.json': notifications(75), + 'ui.json': { encoding: 'utf8', data: '{}' }, + }, (point) => { + if (point.phase === 'commit' && point.operation === 'rename-staged' && point.file === 'ui.json') { + throw new Error('injected final commit failure'); + } + })).toThrow(RestoreTransactionError); + + expect(readLive('runtime.json')).toBe(oldRuntime); + expect(fs.existsSync(livePath('notifications.json'))).toBe(false); + expect(readLive('ui.json')).toBe(oldUi); + expect(transactionDirs()).toEqual([]); + }); + + it('retains the snapshot and reports its path only when rollback itself fails', () => { + writeLive('runtime.json', '{"old":"runtime"}'); + writeLive('notifications.json', '{"old":"notifications"}'); + + let thrown: unknown; + try { + run({ + 'runtime.json': runtime(5104), + 'notifications.json': notifications(90), + }, (point) => { + if (point.phase === 'commit' && point.operation === 'rename-staged' && point.file === 'notifications.json') { + throw new Error('injected commit failure'); + } + if (point.phase === 'rollback' && point.operation === 'restore-current' && point.file === 'runtime.json') { + throw new Error('injected rollback failure'); + } + }); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + name: 'RestoreTransactionError', + phase: 'rollback', + rollbackSucceeded: false, + snapshotDir: expect.stringContaining('.restore-transaction-test-transaction'), + })); + const snapshotDir = (thrown as RestoreTransactionError).snapshotDir!; + expect(fs.existsSync(snapshotDir)).toBe(true); + expect(fs.statSync(snapshotDir).mode & 0o777).toBe(0o700); + expect(fs.existsSync(path.join(snapshotDir, 'snapshot', 'runtime.json'))).toBe(true); + const causes = ((thrown as RestoreTransactionError).cause as AggregateError).errors; + expect(causes.map((error: unknown) => error instanceof Error ? error.message : String(error))).toEqual([ + 'injected commit failure', + 'injected rollback failure', + ]); + }); + + it('performs no filesystem transaction when semantic preflight fails', () => { + const oldRuntime = '{"old":"runtime"}'; + writeLive('runtime.json', oldRuntime); + const operations: RestoreOperation[] = []; + + let thrown: unknown; + try { + run({ + 'runtime.json': { encoding: 'utf8', data: JSON.stringify({ webuiPort: 70_000 }) }, + }, (operation) => operations.push(operation)); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + name: 'RestoreTransactionError', + phase: 'preflight', + transactionId: 'test-transaction', + failedFiles: ['runtime.json'], + })); + expect((thrown as RestoreTransactionError).cause).toEqual(expect.objectContaining({ + name: 'RestorePreflightError', + file: 'runtime.json', + })); + expect(operations).toEqual([]); + expect(readLive('runtime.json')).toBe(oldRuntime); + expect(transactionDirs()).toEqual([]); + }); + + it('fails preflight when a required current OneBot file cannot be read', () => { + fs.symlinkSync('onebot.json', livePath('onebot.json')); + + let thrown: unknown; + try { + run({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'overlay', + httpClients: [{ name: 'remote', url: 'https://example.test/onebot' }], + }), + }, + }); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + name: 'RestoreTransactionError', + phase: 'preflight', + failedFiles: ['onebot.json'], + })); + expect((thrown as RestoreTransactionError).cause).toEqual(expect.objectContaining({ + name: 'RestorePreflightError', + file: 'onebot.json', + })); + expect(transactionDirs()).toEqual([]); + }); + + it('reports a committed restore distinctly when final cleanup fails', () => { + writeLive('runtime.json', '{"old":"runtime"}'); + + let thrown: unknown; + try { + run({ 'runtime.json': runtime(5105) }, (point) => { + if (point.phase === 'cleanup') throw new Error('injected cleanup failure'); + }); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + name: 'RestoreTransactionError', + phase: 'cleanup', + committed: true, + snapshotDir: expect.stringContaining('.restore-transaction-test-transaction'), + })); + expect(JSON.parse(readLive('runtime.json')).webuiPort).toBe(5105); + expect(fs.existsSync((thrown as RestoreTransactionError).snapshotDir!)).toBe(true); + }); + + it('never removes an existing transaction directory when id allocation collides', () => { + writeLive('runtime.json', '{"old":"runtime"}'); + const existing = path.join(root, '.restore-transaction-test-transaction'); + fs.mkdirSync(path.join(existing, 'snapshot'), { recursive: true }); + const marker = path.join(existing, 'snapshot', 'manual-recovery-marker'); + fs.writeFileSync(marker, 'keep me'); + + expect(() => run({ 'runtime.json': runtime(5106) })).toThrow(RestoreTransactionError); + + expect(fs.readFileSync(marker, 'utf8')).toBe('keep me'); + expect(readLive('runtime.json')).toBe('{"old":"runtime"}'); + }); + + it('keeps the original stage failure file and both causes when cleanup also fails', () => { + writeLive('runtime.json', '{"old":"runtime"}'); + writeLive('notifications.json', '{"old":"notifications"}'); + + let thrown: unknown; + try { + run({ + 'runtime.json': runtime(5107), + 'notifications.json': notifications(30), + }, (point) => { + if (point.phase === 'stage' && point.operation === 'write-staged' && point.file === 'notifications.json') { + throw new Error('stage-root-cause'); + } + if (point.phase === 'cleanup') throw new Error('cleanup-root-cause'); + }); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + phase: 'cleanup', + committed: false, + failedFiles: ['notifications.json'], + })); + const causes = ((thrown as RestoreTransactionError).cause as AggregateError).errors; + expect(causes.map((error: unknown) => (error as Error).message)).toEqual(['stage-root-cause', 'cleanup-root-cause']); + }); + + it('keeps the failed commit file and both causes when post-rollback cleanup fails', () => { + writeLive('runtime.json', '{"old":"runtime"}'); + writeLive('notifications.json', '{"old":"notifications"}'); + + let thrown: unknown; + try { + run({ + 'runtime.json': runtime(5108), + 'notifications.json': notifications(30), + }, (point) => { + if (point.phase === 'commit' && point.file === 'notifications.json') throw new Error('commit-root-cause'); + if (point.phase === 'cleanup') throw new Error('cleanup-root-cause'); + }); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + phase: 'cleanup', + rollbackSucceeded: true, + committed: false, + failedFiles: ['notifications.json'], + })); + const causes = ((thrown as RestoreTransactionError).cause as AggregateError).errors; + expect(causes.map((error: unknown) => (error as Error).message)).toEqual(['commit-root-cause', 'cleanup-root-cause']); + }); +}); diff --git a/packages/mcp/package.json b/packages/mcp/package.json index db118668..e1c8d7be 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/mcp", - "version": "1.12.2", + "version": "1.12.3", "description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.", "repository": { "type": "git", diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index 5d55e7c8..bf0e73e1 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -5689,7 +5689,7 @@ { "name": "get_status", "aliases": [], - "returns": "运行状态。`online`/`good` 均表示账号是否在线。", + "returns": "运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。", "returnsSchema": { "type": "object", "properties": { @@ -5699,7 +5699,7 @@ }, "good": { "type": "boolean", - "description": "状态是否正常(与 online 一致)" + "description": "接收链路健康状态;仅在确认停滞时为 false" } }, "required": [ diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index daa649f0..55f5cd05 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -5692,7 +5692,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_status", "aliases": [], - "returns": "运行状态。`online`/`good` 均表示账号是否在线。", + "returns": "运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。", "returnsSchema": { "type": "object", "properties": { @@ -5702,7 +5702,7 @@ export const ACTIONS: CatalogAction[] = [ }, "good": { "type": "boolean", - "description": "状态是否正常(与 online 一致)" + "description": "接收链路健康状态;仅在确认停滞时为 false" } }, "required": [ diff --git a/packages/onebot/package.json b/packages/onebot/package.json index 59995cd1..f653116c 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/onebot", - "version": "1.12.2", + "version": "1.12.3", "private": true, "type": "module", "description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis..method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/'` collapses to `import { … } from '@snowluma/onebot/'`.", diff --git a/packages/onebot/src/actions/info.ts b/packages/onebot/src/actions/info.ts index 2fa50e2d..e4724e83 100644 --- a/packages/onebot/src/actions/info.ts +++ b/packages/onebot/src/actions/info.ts @@ -27,19 +27,19 @@ export const actions = [ defineAction({ name: 'get_status', readOnly: true, - returns: '运行状态。`online`/`good` 均表示账号是否在线。', + returns: '运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。', returnsSchema: { type: 'object', properties: { online: { type: 'boolean', description: '是否在线' }, - good: { type: 'boolean', description: '状态是否正常(与 online 一致)' }, + good: { type: 'boolean', description: '接收链路健康状态;仅在确认停滞时为 false' }, }, required: ['online', 'good'], }, params: {}, run: (_p, ctx) => { const online = ctx.isOnline(); - return okResponse({ online, good: online }); + return okResponse({ online, good: online && ctx.bridge.receiveHealthy }); }, }), @@ -96,4 +96,3 @@ export const actions = [ }, }), ]; - diff --git a/packages/onebot/src/config.ts b/packages/onebot/src/config.ts index 45acb727..7375e1e9 100644 --- a/packages/onebot/src/config.ts +++ b/packages/onebot/src/config.ts @@ -2,6 +2,7 @@ import { createLogger } from '@snowluma/common/logger'; import { isRealUin } from '@snowluma/common/uin'; import { randomBytes } from 'crypto'; import fs from 'fs'; +import { isIP } from 'node:net'; import path from 'path'; import type { HttpClientNetwork, @@ -127,6 +128,237 @@ export function saveOneBotConfig( saveJson(perUinPath, toJsonObject(config, options.mode ?? 'snapshot')); } +export interface PreparedOneBotConfigRestore { + value: JsonObject; + migratedFields: string[]; +} + +/** + * Parse and canonicalize an on-disk OneBot config without touching the + * filesystem. Restore uses this owner-provided seam so legacy layouts are + * migrated deliberately while malformed values cannot disappear through the + * normal load path's permissive compatibility parser. + */ +export function prepareOneBotConfigForRestore( + value: unknown, + scope: 'global' | 'per-uin', + inheritedGlobal?: unknown, +): PreparedOneBotConfigRestore { + if (!isObject(value)) invalid('restore source must be an object'); + validateOneBotRestoreSource(value); + + let global: JsonObject | null = null; + if (inheritedGlobal !== undefined && inheritedGlobal !== null) { + if (!isObject(inheritedGlobal)) invalid('inherited global restore source must be an object'); + validateOneBotRestoreSource(inheritedGlobal); + global = inheritedGlobal; + } + + // onebot.json is an inheritance source. Materializing its adapter defaults + // in isolation changes how existing per-UIN legacy overlays are interpreted. + // Strictly validate it, but preserve its source structure. + if (scope === 'global') { + return { value, migratedFields: [] }; + } + + const sources = value.mode !== PER_UIN_SNAPSHOT_MARKER && global + ? [global, value] + : [value]; + const config = fromJson(sources, false); + const mode = scope === 'per-uin' && value.mode === PER_UIN_SNAPSHOT_MARKER + ? 'snapshot' + : 'overlay'; + const canonical = toJsonObject(config, mode); + + // These legacy global defaults also apply to adapters declared by a + // per-account overlay. Keep them until every overlay has naturally been + // materialized, otherwise canonicalizing onebot.json changes inheritance. + // Keep the one known cross-file legacy field until startup's existing + // migrateGlobalSettings copy-up moves it into snowluma.json. + if (Object.prototype.hasOwnProperty.call(value, 'musicSignUrl')) { + canonical.musicSignUrl = value.musicSignUrl; + } + + return { + value: canonical, + migratedFields: JSON.stringify(value) === JSON.stringify(canonical) ? [] : ['$'], + }; +} + +const RESTORE_TOP_LEVEL_KEYS = new Set([ + 'mode', 'networks', 'statusCommand', 'notifications', 'musicSignUrl', + 'httpServers', 'httpClients', 'httpPostEndpoints', 'wsServers', 'wsClients', + 'messageFormat', 'reportSelfMessage', +]); + +const RESTORE_NETWORK_KEYS = new Set(['httpServers', 'httpClients', 'wsServers', 'wsClients']); +const RESTORE_BASE_ADAPTER_KEYS = ['name', 'enabled', 'accessToken', 'messageFormat', 'reportSelfMessage'] as const; + +function validateOneBotRestoreSource(value: JsonObject): void { + rejectUnknownKeys(value, RESTORE_TOP_LEVEL_KEYS, '$'); + if (value.mode !== undefined && value.mode !== 'snapshot' && value.mode !== 'overlay') { + invalid('$.mode must be snapshot or overlay'); + } + if (value.messageFormat !== undefined && parseMessageFormat(value.messageFormat) === undefined) { + invalid('$.messageFormat must be array or string'); + } + if (value.reportSelfMessage !== undefined && typeof value.reportSelfMessage !== 'boolean') { + invalid('$.reportSelfMessage must be a boolean'); + } + if (value.musicSignUrl !== undefined) { + if (typeof value.musicSignUrl !== 'string') invalid('$.musicSignUrl must be a string'); + const url = value.musicSignUrl.trim(); + if (url && !isHttpUrlForRestore(url)) invalid('$.musicSignUrl must be empty or an http(s) URL'); + } + + const networks = value.networks; + if (networks !== undefined) { + if (!isObject(networks)) invalid('$.networks must be an object'); + rejectUnknownKeys(networks, RESTORE_NETWORK_KEYS, '$.networks'); + } + + const counts: Record = { + httpServers: 0, + httpClients: 0, + wsServers: 0, + wsClients: 0, + }; + const visit = (owner: JsonObject, key: keyof OneBotNetworks, pathPrefix: string): void => { + if (owner[key] === undefined) return; + counts[key] += validateRestoreAdapterArray(owner[key], key, `${pathPrefix}.${key}`); + }; + if (isObject(networks)) { + for (const key of RESTORE_NETWORK_KEYS) visit(networks, key as keyof OneBotNetworks, '$.networks'); + } + for (const key of RESTORE_NETWORK_KEYS) visit(value, key as keyof OneBotNetworks, '$'); + if (value.httpPostEndpoints !== undefined) { + counts.httpClients += validateRestoreAdapterArray(value.httpPostEndpoints, 'httpClients', '$.httpPostEndpoints'); + } + + validateRestoreStatusCommand(value.statusCommand); + validateRestoreNotifications(value.notifications); + + const parsed = fromJson([value], false); + for (const key of RESTORE_NETWORK_KEYS) { + const kind = key as keyof OneBotNetworks; + if (parsed.networks[kind].length !== counts[kind]) { + invalid(`$.${kind} contains a duplicate or unusable adapter`); + } + } +} + +function validateRestoreAdapterArray(value: unknown, kind: keyof OneBotNetworks, at: string): number { + if (!Array.isArray(value)) invalid(`${at} must be an array`); + const specific = kind === 'httpServers' || kind === 'wsServers' + ? ['host', 'port', 'path'] + : kind === 'httpClients' + ? ['url', 'timeoutMs'] + : ['url', 'role', 'reconnectIntervalMs']; + if (kind === 'wsServers') specific.push('role'); + const allowed = new Set([...RESTORE_BASE_ADAPTER_KEYS, ...specific]); + + value.forEach((raw, index) => { + const pathAt = `${at}[${String(index)}]`; + if (!isObject(raw)) invalid(`${pathAt} must be an object`); + rejectUnknownKeys(raw, allowed, pathAt); + if (raw.name !== undefined && typeof raw.name !== 'string') invalid(`${pathAt}.name must be a string`); + if (raw.enabled !== undefined && typeof raw.enabled !== 'boolean') invalid(`${pathAt}.enabled must be a boolean`); + if (raw.accessToken !== undefined && typeof raw.accessToken !== 'string') invalid(`${pathAt}.accessToken must be a string`); + if (raw.messageFormat !== undefined && parseMessageFormat(raw.messageFormat) === undefined) { + invalid(`${pathAt}.messageFormat must be array or string`); + } + if (raw.reportSelfMessage !== undefined && typeof raw.reportSelfMessage !== 'boolean') { + invalid(`${pathAt}.reportSelfMessage must be a boolean`); + } + + if (kind === 'httpServers' || kind === 'wsServers') { + const port = parseRestoreInteger(raw.port); + if (port === null || port <= 0 || port > 65535) invalid(`${pathAt}.port must be an integer between 1 and 65535`); + if (raw.host !== undefined && typeof raw.host !== 'string') invalid(`${pathAt}.host must be a string`); + if (raw.path !== undefined && typeof raw.path !== 'string') invalid(`${pathAt}.path must be a string`); + } else { + if (raw.url !== undefined && typeof raw.url !== 'string') invalid(`${pathAt}.url must be a string`); + if (raw.url === undefined && raw.enabled !== false) invalid(`${pathAt}.url is required while the adapter is enabled`); + } + if (kind === 'httpClients' && raw.timeoutMs !== undefined) { + const timeout = parseRestoreInteger(raw.timeoutMs); + if (timeout === null || timeout <= 0 || timeout > NODE_TIMER_MAX_MS) { + invalid(`${pathAt}.timeoutMs must be an integer between 1 and ${NODE_TIMER_MAX_MS}`); + } + } + if (kind === 'wsServers' || kind === 'wsClients') { + const role = raw.role; + if (role !== undefined && !['api', 'event', 'universal'].includes(String(role).toLowerCase())) { + invalid(`${pathAt}.role must be Api, Event, or Universal`); + } + } + if (kind === 'wsClients' && raw.reconnectIntervalMs !== undefined) { + const interval = parseRestoreInteger(raw.reconnectIntervalMs); + if (interval === null || interval < 1000 || interval > NODE_TIMER_MAX_MS) { + invalid(`${pathAt}.reconnectIntervalMs must be an integer between 1000 and ${NODE_TIMER_MAX_MS}`); + } + } + }); + return value.length; +} + +function validateRestoreStatusCommand(value: unknown): void { + if (value === undefined) return; + if (!isObject(value)) invalid('$.statusCommand must be an object'); + rejectUnknownKeys(value, new Set(['enabled', 'swallow', 'cooldownSeconds', 'trigger']), '$.statusCommand'); + if (value.enabled !== undefined && typeof value.enabled !== 'boolean') invalid('$.statusCommand.enabled must be a boolean'); + if (value.swallow !== undefined && typeof value.swallow !== 'boolean') invalid('$.statusCommand.swallow must be a boolean'); + if (value.cooldownSeconds !== undefined) { + const cooldown = parseRestoreInteger(value.cooldownSeconds); + if (cooldown === null || cooldown < 0 || cooldown > STATUS_COMMAND_COOLDOWN_MAX) { + invalid(`$.statusCommand.cooldownSeconds must be an integer between 0 and ${STATUS_COMMAND_COOLDOWN_MAX}`); + } + } + if (value.trigger !== undefined) { + const trigger = typeof value.trigger === 'string' ? value.trigger.trim() : ''; + if ( + typeof value.trigger !== 'string' || !trigger || /[\r\n]/.test(value.trigger) || + trigger.length > STATUS_COMMAND_TRIGGER_MAX_LENGTH + ) { + invalid(`$.statusCommand.trigger must be non-empty, single-line, and <= ${STATUS_COMMAND_TRIGGER_MAX_LENGTH} characters`); + } + } +} + +function validateRestoreNotifications(value: unknown): void { + if (value === undefined) return; + if (!isObject(value)) invalid('$.notifications must be an object'); + rejectUnknownKeys(value, new Set(['channelIds']), '$.notifications'); + if (value.channelIds === undefined) return; + if (!Array.isArray(value.channelIds)) invalid('$.notifications.channelIds must be an array'); + value.channelIds.forEach((id, index) => { + if (typeof id !== 'string') invalid(`$.notifications.channelIds[${String(index)}] must be a string`); + const normalized = id.trim(); + if (!normalized || normalized.length > 64 || !/^[\w.-]+$/.test(normalized)) { + invalid(`$.notifications.channelIds[${String(index)}] is invalid`); + } + }); +} + +function rejectUnknownKeys(value: JsonObject, allowed: ReadonlySet, at: string): void { + const unknown = Object.keys(value).find((key) => !allowed.has(key)); + if (unknown) invalid(`${at}.${unknown} is not supported`); +} + +function parseRestoreInteger(value: unknown): number | null { + const number = typeof value === 'string' && value.trim() ? Number(value) : value; + return typeof number === 'number' && Number.isSafeInteger(number) ? number : null; +} + +function isHttpUrlForRestore(value: string): boolean { + try { + const parsed = new URL(value); + return (parsed.protocol === 'http:' || parsed.protocol === 'https:') && parsed.host.length > 0; + } catch { + return false; + } +} + /** Validate the normalized, public OneBot configuration shape before it is * persisted or compiled into a live network plan. Adapter names form one * process-wide namespace per account, not four independent namespaces. */ @@ -251,6 +483,7 @@ function validateServer(item: JsonObject, at: string): void { if (typeof item.host !== 'string') invalid(`${at}.host must be a string`); if (!item.host.trim()) invalid(`${at}.host must be a non-empty string when provided`); if (item.host !== item.host.trim()) invalid(`${at}.host must not have surrounding whitespace`); + if (!isValidBindHost(item.host)) invalid(`${at}.host must be a valid TCP bind host`); } if (item.path !== undefined) { if (typeof item.path !== 'string') invalid(`${at}.path must be a string`); @@ -714,3 +947,13 @@ function saveJson(filePath: string, json: JsonObject): void { function isObject(value: unknown): value is JsonObject { return typeof value === 'object' && value !== null && !Array.isArray(value); } + +function isValidBindHost(value: string): boolean { + if (!value || value.length > 253 || /[\s/?#@]/u.test(value)) return false; + if (value.includes(':')) return isIP(value) === 6; + if (/^[\d.]+$/.test(value)) { + return isIP(value) === 4; + } + const normalized = value.endsWith('.') ? value.slice(0, -1) : value; + return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(? { + it('keeps online true while reporting a stalled receive path as not good', async () => { + const ctx = { + isOnline: () => true, + bridge: { receiveHealthy: false }, + } as unknown as ApiActionContext; + const response = await new ApiHandler(ctx).handle('get_status', {}); + + expect(response).toMatchObject({ + status: 'ok', + retcode: 0, + data: { online: true, good: false }, + }); + }); +}); diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 472abfea..c096269c 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proto-defs", - "version": "1.12.2", + "version": "1.12.3", "private": true, "type": "module", "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).", diff --git a/packages/protocol/package.json b/packages/protocol/package.json index b6c15aa6..907483d2 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/protocol", - "version": "1.12.2", + "version": "1.12.3", "private": true, "type": "module", "description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/'` collapses to `import { … } from '@snowluma/protocol/'`.", diff --git a/packages/protocol/src/msg-push/decoders/group-member-change.ts b/packages/protocol/src/msg-push/decoders/group-member-change.ts index 12d11391..99add6b1 100644 --- a/packages/protocol/src/msg-push/decoders/group-member-change.ts +++ b/packages/protocol/src/msg-push/decoders/group-member-change.ts @@ -1,7 +1,7 @@ import { protobuf_decode } from '@snowluma/proton'; import type { GroupMemberJoin, GroupMemberLeave } from '../../events'; import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify'; -import { decodeOperatorUid, resolveUidToUin } from '../helpers'; +import { decodeNestedOperatorUid, decodeRawOperatorUid, resolveUidToUin } from '../helpers'; import type { MsgPushDecoder } from '../registry'; export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => { @@ -9,7 +9,10 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => { if (!change) return []; const groupId = change.groupUin ?? 0; const userUid = change.memberUid ?? ''; - const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)); + const operatorUid = decodeRawOperatorUid( + change.operatorBytes ?? new Uint8Array(0), + 'group member increase', + ); const ev: GroupMemberJoin = { kind: 'group_member_join', time: ctx.head.timestamp, @@ -49,7 +52,12 @@ export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => { const dt = change.decreaseType ?? 0; const groupId = change.groupUin ?? 0; const userUid = change.memberUid ?? ''; - const operatorUid = decodeOperatorUid(change.operatorBytes ?? new Uint8Array(0)); + const operatorBytes = change.operatorBytes ?? new Uint8Array(0); + // QQ sends the operator as a raw UTF-8 UID for normal member changes. + // Only the bot-self-kicked variant (decreaseType=3) wraps it in OperatorInfo. + const operatorUid = dt === 3 + ? decodeNestedOperatorUid(operatorBytes, 'group member decrease type=3') + : decodeRawOperatorUid(operatorBytes, `group member decrease type=${dt}`); const ev: GroupMemberLeave = { kind: 'group_member_leave', time: ctx.head.timestamp, diff --git a/packages/protocol/src/msg-push/helpers.ts b/packages/protocol/src/msg-push/helpers.ts index f14df2d4..2491b061 100644 --- a/packages/protocol/src/msg-push/helpers.ts +++ b/packages/protocol/src/msg-push/helpers.ts @@ -1,4 +1,5 @@ import { protobuf_decode } from '@snowluma/proton'; +import { hexPreview } from '@snowluma/common/hex'; import { inflateSync } from 'zlib'; import type { IdentityService } from '../identity-service'; import type { OperatorInfo } from '@snowluma/proto-defs/notify'; @@ -85,11 +86,57 @@ export function resolveUidToUin(identity: IdentityService, groupId: number, uid: return fallback; } -export function decodeOperatorUid(bytes: Uint8Array): string { +const OPERATOR_BYTES_PREVIEW_LENGTH = 32; + +function describeOperatorBytes(bytes: Uint8Array): string { + return `bytes=${bytes.length} preview=${hexPreview(bytes, OPERATOR_BYTES_PREVIEW_LENGTH)}`; +} + +function hasControlCharacter(value: string): boolean { + for (const char of value) { + const codePoint = char.codePointAt(0); + if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f)) return true; + } + return false; +} + +function assertOperatorUid(uid: string, context: string, bytes: Uint8Array): string { + if (hasControlCharacter(uid)) { + throw new Error(`${context} operator UID contains control characters (${describeOperatorBytes(bytes)})`); + } + return uid; +} + +export function decodeRawOperatorUid(bytes: Uint8Array, context: string): string { if (!bytes || bytes.length === 0) return ''; - const info = protobuf_decode(bytes); - if (info?.operatorField?.uid) return info.operatorField.uid; - return Buffer.from(bytes).toString('utf8'); + let uid: string; + try { + uid = new TextDecoder('utf-8', { fatal: true }).decode(bytes); + } catch (error) { + throw new Error( + `${context} operator UID is not valid UTF-8 (${describeOperatorBytes(bytes)})`, + { cause: error }, + ); + } + return assertOperatorUid(uid, context, bytes); +} + +export function decodeNestedOperatorUid(bytes: Uint8Array, context: string): string { + if (!bytes || bytes.length === 0) return ''; + let info: OperatorInfo | null; + try { + info = protobuf_decode(bytes); + } catch (error) { + throw new Error( + `${context} operator info decode failed (${describeOperatorBytes(bytes)})`, + { cause: error }, + ); + } + const uid = info?.operatorField?.uid; + if (!uid) { + throw new Error(`${context} operator info is missing UID (${describeOperatorBytes(bytes)})`); + } + return assertOperatorUid(uid, context, bytes); } export function buildTemplateMap(params: Array<{ name?: string; value?: string }>): Map { diff --git a/packages/proton/package.json b/packages/proton/package.json index 81e5bfa6..004eae08 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proton", - "version": "1.12.2", + "version": "1.12.3", "private": true, "type": "module", "description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index ba19a485..141f11a4 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/runtime", - "version": "1.12.2", + "version": "1.12.3", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 76ba0748..0e5acca4 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.12.2", + "version": "1.12.3", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index 2b2ee6a9..aebe1a99 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.12.2", + "version": "1.12.3", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index 02008ae1..bb9c9f39 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/websocket", - "version": "1.12.2", + "version": "1.12.3", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 473d9115..522a76f0 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -2,7 +2,7 @@ "license": "SEE LICENSE IN LICENSE", "name": "webui", "private": true, - "version": "1.12.2", + "version": "1.12.3", "type": "module", "scripts": { "dev": "vite", diff --git a/packages/webui/src/components/settings/system-panel.tsx b/packages/webui/src/components/settings/system-panel.tsx index 87366ea3..2c226796 100644 --- a/packages/webui/src/components/settings/system-panel.tsx +++ b/packages/webui/src/components/settings/system-panel.tsx @@ -43,7 +43,7 @@ export function SystemPanel() { const [restoreCreds, setRestoreCreds] = useState(false); const fileRef = useRef(null); - const load = async () => { + const load = async (): Promise => { try { const res = await api.systemSettings.get(); setData(res); @@ -51,8 +51,10 @@ export function SystemPanel() { setHost(res.settings.webuiHost); setTrustProxy(res.settings.trustProxy); setTlsEnabled(res.settings.tlsEnabled); + return true; } catch { setMsg({ kind: 'err', text: '加载系统设置失败' }); + return false; } finally { setLoading(false); } @@ -136,11 +138,19 @@ export function SystemPanel() { let parsed: Record; try { parsed = JSON.parse(text); } catch { flash('err', '文件不是有效的 JSON'); return; } const res = await api.systemSettings.importBackup(parsed, restoreCreds); - const parts = [`已恢复 ${res.restored.length} 项`]; - if (res.skipped.length) parts.push(`跳过 ${res.skipped.length} 项(凭据未恢复)`); - flash('ok', `${parts.join(',')},重启后生效`); + const parts = res.restored.length ? [`已恢复 ${res.restored.length} 项`] : ['没有可恢复的配置']; + if (res.skipped.length) parts.push(`跳过 ${res.skipped.length} 项(敏感配置,含 OneBot 配置)`); + if (res.migrated.length) parts.push(`兼容转换 ${res.migrated.length} 项`); + const summary = `${parts.join(',')}${res.restartRequiredToApply ? ',重启后生效' : ''}`; + const refreshed = await load(); + flash( + refreshed ? 'ok' : 'err', + refreshed ? summary : `${summary};但界面状态刷新失败,请手动刷新页面`, + ); } catch (e) { - flash('err', e instanceof Error ? e.message : '恢复失败'); + const message = e instanceof Error ? e.message : '恢复失败'; + const refreshed = await load(); + flash('err', refreshed ? message : `${message};界面状态刷新失败,请手动刷新页面`); } finally { setSaving(false); if (fileRef.current) fileRef.current.value = ''; @@ -263,16 +273,16 @@ export function SystemPanel() { 配置备份 / 恢复 - 导出/导入全部配置(OneBot、外观、通知、系统设置、证书)。不含消息数据库。 + 备份外观、通知、系统设置和证书等配置;敏感开关还会包含 OneBot 配置。不含消息数据库。
- - + +
{exportCreds && ( -

⚠ 备份文件将包含登录口令哈希与 TLS 私钥,请妥善保管。

+

⚠ 将额外包含 WebUI 登录状态、TLS 私钥,以及带访问令牌的 OneBot 配置,请妥善保管。

)}
-

恢复前会自动把当前配置快照到 config/.restore-backup-*;恢复后需重启生效。

+

恢复前会校验本次要恢复的配置;写入过程中出错会自动回滚,成功后临时快照会删除。恢复后需重启生效。

diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 666a47b4..0bff6327 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -164,7 +164,7 @@ export interface ApiClient { deleteCert(): Promise; /** Download the config backup bundle (credentials gated). */ exportBackup(includeCredentials: boolean): Promise; - /** Validate + restore a bundle (snapshots current config first). */ + /** Validate + restore a bundle as one process-level transaction. */ importBackup(backup: BackupBundle, restoreCredentials: boolean): Promise; }; diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index 83bbb0a3..abf27b58 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -253,9 +253,11 @@ export type DebugStreamMessage = // server validates; the client never inspects its internals. export type BackupBundle = Record; export interface BackupImportResult { + success: true; + transactionId: string; restored: string[]; skipped: string[]; - snapshotDir: string; + migrated: Array<{ name: string; fields: string[] }>; restartRequiredToApply: boolean; }