Compare commits

...

26 Commits

Author SHA1 Message Date
snowluma-bot[bot]
8a8f892e20 chore(native): replace native artifacts (native-de06ed1)
Build: https://github.com/SnowLuma/SnowLumaNative/releases/tag/native-de06ed1
2026-10-18 10:55:30 +00:00
晚晴
39d1f40583 docs: point action reference at the published docs site (#540)
docs/onebot-actions.md is referenced twice but does not exist in the repository, so both "动作参考" links in the README resolve to 404s. The OneBot action reference is published on the docs site, kept in sync from collectActionDocs() via the sync-docs-catalog workflow, so link there instead. Also add a deploy row pointing at the Docker/Windows guide, which the README had no entry for.

Co-authored-by: zhngzhu <215231231+zhngzhu@users.noreply.github.com>
2026-10-18 18:54:56 +08:00
手瓜一十雪
0cdb389831 [merge] docs: remove reply and media explanations 2026-10-18 14:24:33 +08:00
手瓜一十雪
e60bc3bad2 ci: allow manual release validation 2026-10-18 14:01:03 +08:00
手瓜一十雪
c15b2d857d chore: prepare v2.0.0 release 2026-10-18 13:58:08 +08:00
手瓜一十雪
1001f55a06 fix: drain account shutdown before reopening persistence 2026-10-18 13:52:13 +08:00
手瓜一十雪
0f358b2ac2 fix(webui): stop idle polling and release background timers 2026-10-18 13:49:48 +08:00
手瓜一十雪
652b9c4eda fix: serialize process polling and keep database shutdown terminal 2026-10-18 13:40:00 +08:00
手瓜一十雪
95a2d0d257 fix(protocol): isolate catalog lookups and event subscriptions 2026-10-18 13:31:10 +08:00
手瓜一十雪
fb39af6c28 fix: unify stream cleanup and async request ownership 2026-10-18 13:20:22 +08:00
手瓜一十雪
9b165a8971 refactor: await native operations across the bridge lifecycle 2026-10-18 13:19:21 +08:00
手瓜一十雪
1faa6c58fa fix: unify stream cleanup and configuration response handling 2026-10-18 13:18:25 +08:00
手瓜一十雪
38a7c3da63 fix: standardize version parsing and simplify string escaping 2026-10-18 13:00:39 +08:00
手瓜一十雪
4e2b6b1200 refactor: use native async discovery and simplify shared state 2026-10-18 12:57:18 +08:00
手瓜一十雪
5032cbb8c0 feat(core): add staged self-updates and unify application version 2026-10-18 12:50:11 +08:00
手瓜一十雪
c54aeffc77 refactor: clarify async state and subscription ownership 2026-10-18 12:42:54 +08:00
H3CoF6
f6ca9d5f65 feat(bridge): detect local QQ accounts with shared process snapshots (#525)
Read QQ account databases and attribute identities to their owning processes. Share snapshots across REST, watcher updates and login reconciliation, discard stale results, and report detection failures.
2026-10-18 12:10:37 +08:00
晚晴
8e24995fc3 feat(core): add process facts to ordered account notifications (#539)
* feat(core): carry hook process status in notifications

`offline` alone cannot tell an external supervisor whether the QQ session dropped (log back in) or the process is gone (restart the client). Resolve the hook process behind a UIN at notify time and expose `status`, `pid` and `error` as template variables; a failing lookup degrades to empty values so delivery is never blocked.

The default webhook/email templates gain a process-status line; existing channels keep their stored template untouched.

* fix(core): preserve notification lifecycle ordering and simplify state

---------

Co-authored-by: zhngzhu <215231231+zhngzhu@users.noreply.github.com>
Co-authored-by: 手瓜一十雪 <nanaeonn@outlook.com>
2026-10-18 11:13:58 +08:00
手瓜一十雪
b6d86a586d fix(protocol): switch highway nodes on connection failure 2026-10-18 10:37:07 +08:00
MliKiowa
b90d34c9d8 Enhance bug report template for TRACE logs (#532)
Updated the bug report template to emphasize the need for original messages and complete Trace content.
2026-10-16 10:44:09 +08:00
DrSmoothl
5150d83403 fix(webui): preserve reverse proxy authentication
Prevent login loops when the WebUI is protected by HTTP authentication
at a reverse proxy. Apply the fix to settings, uploads, and live streams
while retaining compatibility with existing WebUI clients.

Fixes #523
2026-10-14 08:13:50 +08:00
DrSmoothl
d6dd748beb docs(webui): clarify account detection reliability
Explain that account detection is not guaranteed to succeed and its results are for reference.
2026-10-13 16:42:28 +08:00
手瓜一十雪
3c4dbe31a8 docs(runtime): remove bundled ffmpeg addon README 2026-10-13 15:32:37 +08:00
手瓜一十雪
4c83cc826e fix(runtime): update ffmpeg addon for SILK duration support
Refresh the four bundled platform binaries from NapNeko/ffmpegAddon commit 9ac944793ffdc2a1c5c55f16e24cb32185feb4ec, successful build 38025527136. Record artifact provenance and binary checksums.

Add native regression coverage for standard SILK, QQ NTSILK, extensionless inputs, and truncated packets.
2026-10-13 15:31:18 +08:00
DrSmoothl
f85b28d23c feat(onebot): add group share links
Retrieve group invitation links with compatible request defaults and explicit error reporting. Add a typed SDK helper and discoverable action documentation.

Fixes #521
2026-10-13 10:34:41 +08:00
MliKiowa
c7428363cb feat: add async SQLite on Node 24 and improve messaging diagnostics (#520)
Move database work off the main thread on Node.js 24 and improve message handling and runtime diagnostics.

Preserve migration, restart, and concurrency coverage with the async SQLite driver.
2026-10-13 10:12:47 +08:00
373 changed files with 20609 additions and 9675 deletions

View File

@@ -123,7 +123,7 @@ body:
attributes:
label: TRACE 日志 / 错误堆栈
description: |
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现。
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现,务必保留原始报文和完整Trace内容。
开启 TRACE 的两种方式(任选其一):
- **WebUI(推荐)**:进入「日志」页 →「服务端日志级别」切到 `TRACE` → 显示过滤切到「开发」预设(确保 TRACE 行可见,否则导出不含 trace)→ 复现问题 → 点「导出当前视图」得到 `snowluma-logs-*.log`,拖到本输入框上传。

View File

@@ -4,6 +4,7 @@ name: CI
on:
pull_request:
workflow_dispatch:
permissions:
contents: read
@@ -21,7 +22,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6
@@ -48,7 +49,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6
@@ -69,7 +70,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6
@@ -90,7 +91,7 @@ jobs:
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- uses: actions/setup-node@v6

View File

@@ -72,7 +72,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -115,7 +115,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -136,19 +136,12 @@ jobs:
SNOWLUMA_TARGET: ${{ matrix.target }}
run: pnpm run build:all
# Bundle production node_modules into dist/ before packaging — mirrors
# release.yml. Without this the `-lite` tarball has no runtime deps and the
# Docker image (which bakes the lite tarball) can't start.
- name: Bundle runtime dependencies
working-directory: dist
run: npm install --omit=dev
- name: Verify release layout
run: pnpm check:release-layout
# Naming convention:
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 24+
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh

View File

@@ -34,7 +34,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js

View File

@@ -18,7 +18,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -64,7 +64,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js
@@ -85,16 +85,12 @@ jobs:
SNOWLUMA_TARGET: ${{ matrix.target }}
run: pnpm run build:all
- name: Bundle runtime dependencies
working-directory: dist
run: npm install --omit=dev
- name: Verify release layout
run: pnpm check:release-layout
# Naming convention:
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 24+
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
@@ -161,7 +157,7 @@ jobs:
## 选择下载
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 22.13+;23 系需 23.4+) |
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 24+) |
| --- | --- | --- |
| Windows x64 | \`SnowLuma-${tag}-win-x64.zip\` | \`SnowLuma-${tag}-win-x64-lite.zip\` |
| Linux x64 | \`SnowLuma-${tag}-linux-x64.tar.gz\` | \`SnowLuma-${tag}-linux-x64-lite.tar.gz\` |

View File

@@ -31,7 +31,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js

View File

@@ -32,7 +32,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js

View File

@@ -31,7 +31,7 @@ jobs:
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
version: 11.25.0
run_install: false
- name: Setup Node.js

View File

@@ -1 +1 @@
22.13.0
24.21.0

View File

@@ -16,10 +16,11 @@ This is a pnpm workspace. Package ownership matters more than directory names:
| Location | Responsibility |
| --- | --- |
| `packages/core` | Application entry, per-account Bridge orchestration, WebUI backend, notifications, release assembly |
| `packages/bridge` | QQ process discovery, Hook sessions, native transport lifecycle |
| `packages/bridge` | QQ process discovery, local account/login detection, Hook sessions, native transport lifecycle |
| `packages/protocol` | Packet decoding, typed QQ events, identity resolution, protocol requests and media transfers |
| `packages/onebot` | Action validation and dispatch, event conversion, message storage, HTTP/WebSocket adapters |
| `packages/common` | Shared logging, configuration and utilities without business dependencies |
| `packages/sqlite` | Asynchronous SQLite facade, native loader, prebuild selection and Vite release assets |
| `packages/proto-defs` | Typed protocol schemas |
| `packages/proton` | Compile-time protobuf codecs and build integration |
| `packages/websocket` | WebSocket implementation and native binding integration |
@@ -32,11 +33,17 @@ This is a pnpm workspace. Package ownership matters more than directory names:
`packages/bridge` owns process connectivity; the account-level Bridge lives in `packages/core/src/bridge`. Start at [the application entry](packages/core/src/index.ts) to follow their composition.
[The entry point](packages/core/src/index.ts) applies pending updates before starting runtime services. [The updater](packages/core/src/update) owns staging and replacement; [Core's build configuration](packages/core/vite.config.ts) emits the release manifest from its build outputs and runtime assets. Keep Core in one bundle and native libraries lazy-loaded so startup can recover an interrupted update before opening native files.
Application versions come from the root `package.json` through `@snowluma/common/version`. Use `pnpm bump <version>` to update workspace manifests, or `pnpm bump` to sync them after editing the root version.
Use `@snowluma/common/semver` for application version validation and comparison. Versions must be canonical SemVer; strip GitHub's `v` tag prefix only at the API boundary.
Read the relevant owner before changing a path:
| Change | Start here |
| --- | --- |
| Connection or account lifecycle | [Hook manager](packages/bridge/src/hook-manager.ts), [Bridge manager](packages/core/src/bridge/manager.ts), [OneBot instance](packages/onebot/src/instance.ts) |
| Which account a QQ process is signed in as | [Account detection](packages/bridge/src/qq-account/detect.ts), [login.db reader](packages/bridge/src/qq-account/login-db.ts), [QQ data paths](packages/bridge/src/qq-account/paths.ts) |
| Incoming QQ events or identity | [Packet pipeline](packages/protocol/src/packet-pipeline.ts), [message decoders](packages/protocol/src/msg-push/index.ts), [identity service](packages/protocol/src/identity-service.ts) |
| OneBot actions or message segments | [Action definitions](packages/onebot/src/actions/index.ts), [validation helpers](packages/onebot/src/action-kit.ts), [event conversion](packages/onebot/src/event-converter/index.ts) |
| WebUI | [Interaction conventions](packages/webui/README.md), `packages/webui/src`, `packages/core/src/webui` |

19
CHANGELOG.md Normal file
View File

@@ -0,0 +1,19 @@
# 更新记录
## 2.0.0
### 升级
- 最低运行环境升至 Node.js 24。完整版内置 Node.js;Lite、SDK 和 MCP 用户需先升级运行环境。
- 原生接口全面异步化,应用与原生产物需成套更新;请使用对应平台的完整发行包。
### 更新
- 新增本地 QQ 账号识别、进程状态诊断和有序账号通知。
- WebUI 支持暂存更新、重启安装,并保留配置、日志与消息数据。
- 新增群分享链接、空间说说详情与评论分页接口,同步 SDK 类型和 MCP 动作目录。
- 改进合并转发引用预览、群相册评论、SILK 时长和 Highway 节点切换。
- 整理原生调用、SQLite、账号关闭和重连顺序,修复请求取消、订阅和定时器释放。
- 减少 WebUI 空闲轮询,修复反向代理认证与版本比较。
[查看自 v1.14.22 起的完整差异](https://github.com/SnowLuma/SnowLuma/compare/v1.14.22...dev)

View File

@@ -35,8 +35,15 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
| 路径 | 作用 |
| --- | --- |
| `packages/core` | 核心运行时:协议、桥接、OneBot 适配、WebUI 服务端 |
| `packages/core` | 应用入口、账号级 Bridge 编排、WebUI 服务端和发行构建 |
| `packages/bridge` | QQ 进程发现、Hook 会话和原生传输生命周期 |
| `packages/protocol` | QQ 数据包解码、身份解析、协议请求和媒体传输 |
| `packages/onebot` | OneBot 动作、事件转换、消息存储和传输适配 |
| `packages/common` | 日志、配置和共享工具 |
| `packages/proto-defs`、`packages/proton` | 协议结构定义、编译期 protobuf 编解码和构建集成 |
| `packages/sdk` | 面向第三方开发者的 SDK,会发布到 npm |
| `packages/mcp` | MCP 服务端和生成的动作目录 |
| `packages/ui` | 发布到 npm 的共享 UI 组件 |
| `packages/runtime` | 运行时辅助包 |
| `packages/websocket` | WebSocket 实现 |
| `packages/webui` | 基于 Vite + React 的前端控制台 |
@@ -51,12 +58,12 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
### 系统要求
- **Node.js 22.13+(23 系需 23.4+)**(项目使用默认启用的 `node:sqlite`)
- **pnpm 10.28.0**(项目通过 `packageManager` 与 CI 统一版本)
- **Node.js 24+**
- **pnpm 11.25.0**(项目通过 `packageManager` 与 CI 统一版本)
- macOS / Linux / Windows 均可。如果要构建原生产物,需要对应平台的工具链。
如果系统提供 Corepack,可执行 `corepack enable pnpm`;没有 Corepack 时可执行
`npm install -g pnpm@10.28.0`。进入仓库后,`node --version` 与
`npm install -g pnpm@11.25.0`。进入仓库后,`node --version` 与
`pnpm --version` 应满足上述版本要求,否则安装会直接失败。
### 拉代码、装依赖、跑起来
@@ -197,7 +204,7 @@ Prettier,并按需开启保存时格式化。
- 单测放在被测代码同包的 `tests/` 或同目录的 `*.test.ts`,按既有风格走。
- 测试要描述行为,不要测实现细节。`it('should call internal foo')` 这种是反例。
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/core/src/onebot/` 下的 `fake-bridge` 类测试。
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/onebot/tests/` 中的 Bridge 测试替身。
### 文档

View File

@@ -12,7 +12,7 @@
<p align="center">
<a href="#快速开始">快速开始</a> ·
<a href="./docs/onebot-actions.md">动作参考</a> ·
<a href="https://snowluma.github.io/zh/docs/api">动作参考</a> ·
<a href="https://github.com/SnowLuma/SnowLuma/issues">问题反馈</a>
</p>
@@ -43,7 +43,7 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生
## 快速开始
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载对应平台的完整发行包并解压。Lite 版需 Node.js 22.13+(23 系需 23.4+)。
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载对应平台的完整发行包并解压。Lite 版需 Node.js 24+。
2. Windows 运行 `launcher.bat`;Linux 执行:
```bash
@@ -53,11 +53,15 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生
3. 打开 [`http://localhost:5099`](http://localhost:5099),使用启动日志中的初始密码登录 WebUI,按引导接入 QQ 进程并配置 OneBot 连接。
在「设置 → 关于 → 软件更新」下载新版本,再点「重启更新」。文件优先暂存于系统临时目录,不可用时使用安装目录的 `tmp/update`,下次启动时替换并清理,配置、日志与消息数据保留。更新沿用当前 Node.js;容器部署请更新镜像。
版本号遵循 [SemVer](https://semver.org/),在线更新仅安装正式版;构建元数据不影响版本排序。
## 接入与文档
| 入口 | 文档 |
| --- | --- |
| WebSocket / HTTP | [OneBot 动作参考](docs/onebot-actions.md) |
| WebSocket / HTTP | [OneBot 动作参考](https://snowluma.github.io/zh/docs/api) |
| 部署(Docker / Windows) | [部署指南](https://snowluma.github.io/zh/docs/guide/deploy) |
| TypeScript SDK | [`packages/sdk/README.md`](packages/sdk/README.md) |
| MCP | [`packages/mcp/README.md`](packages/mcp/README.md) |
@@ -65,7 +69,7 @@ JSON 消息段接受标准的 `data.data` 字符串,也兼容 `data.data` 非
## 开发
需要 Node.js 22.13+(23 系需 23.4+)与 pnpm 10.28.0,日常开发基于 `dev` 分支:
需要 Node.js 24+ 与 pnpm 11.25.0,日常开发基于 `dev` 分支:
```bash
git clone https://github.com/SnowLuma/SnowLuma.git
@@ -78,10 +82,6 @@ pnpm test
贡献流程见 [`CONTRIBUTING.md`](CONTRIBUTING.md);模块边界与项目词汇见 [`CONTEXT.md`](CONTEXT.md);开发方向见 [`RoadMap.md`](RoadMap.md)。
## 引用消息预览
OneBot 发送 `reply` 段时,会将本地消息缓存中的原文附入 QQ 引用预览,保留文字、换行与引用关系。图片、语音等非文字段以类型提示显示,不重新上传媒体;原消息中的嵌套引用不递归展开。只有消息元数据而没有缓存正文时,不生成虚构的预览内容。
## 使用边界与许可
> [!IMPORTANT]

View File

@@ -6,10 +6,7 @@ import { defineConfig, globalIgnores } from 'eslint/config';
import globals from 'globals';
import tseslint from 'typescript-eslint';
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(
/^\/(.:\/)/,
'$1',
);
const tsconfigRootDir = import.meta.dirname;
export const sourceIgnores = globalIgnores([
'**/dist/**',

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.14.22",
"version": "2.0.0",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -48,28 +48,9 @@
"typescript": "catalog:",
"typescript-eslint": "^8.58.2"
},
"pnpm": {
"peerDependencyRules": {
"allowedVersions": {
"eslint-plugin-react-hooks>eslint": "10"
}
},
"overrides": {
"esbuild@<0.28.1": "^0.28.1",
"@babel/core@<7.29.6": "^7.29.6",
"qs@<=6.15.3": "^6.16.0",
"fast-uri@<3.1.6": "^3.1.6",
"@hono/node-server@<1.19.15": "^1.19.15",
"hono": "~4.12.34",
"postcss@<=8.5.22": "^8.5.23",
"ip-address@<=10.3.0": "^10.3.1",
"body-parser@<2.3.0": "^2.3.0",
"brace-expansion@<5.0.7": "^5.0.7"
}
},
"packageManager": "pnpm@10.28.0",
"packageManager": "pnpm@11.25.0",
"engines": {
"node": "^22.13.0 || >=23.4.0",
"pnpm": "10.28.0"
"node": ">=24",
"pnpm": "11.25.0"
}
}

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.14.22",
"version": "2.0.0",
"private": true,
"type": "module",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
@@ -40,9 +40,9 @@
"types": "./src/qq-hook-client.ts",
"default": "./src/qq-hook-client.ts"
},
"./qq-port-probe": {
"types": "./src/qq-port-probe.ts",
"default": "./src/qq-port-probe.ts"
"./qq-account": {
"types": "./src/qq-account/index.ts",
"default": "./src/qq-account/index.ts"
},
"./types": {
"types": "./src/types.ts",
@@ -54,12 +54,16 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/common": "workspace:*"
"@snowluma/common": "workspace:*",
"@snowluma/sqlite": "workspace:*"
},
"devDependencies": {
"@types/node": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
},
"engines": {
"node": ">=24"
}
}

View File

@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, runWithTraceRequest, type Logger } from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { PacketSender } from '@snowluma/common/packet-sender';
@@ -7,18 +8,19 @@ import { HookSession, type HookSessionDeps } from './hook-session';
import {
injectHookProcess,
listHookProcesses,
resolveHookNativePath,
unloadHookProcess,
type HookProcessBaseInfo,
} from './injector';
import { PipeWatcher } from './pipe-watcher';
import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
import { createProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
import { QqHookClient } from './qq-hook-client';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import type { HookProcessInfo } from './types';
import { detectAccountLoginsForPids, type AccountLoginState } from './qq-account';
import type { HookProcessAccount, HookProcessInfo } from './types';
const AUTO_LOAD_MAX_ATTEMPTS = 3;
const DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS = 5000;
type AutoLoadAttempt = {
attempts: number;
inFlight: boolean;
@@ -53,7 +55,15 @@ export type HookManagerDeps = {
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
watcherIntervalMs?: number;
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
listProcesses?: () => HookProcessBaseInfo[];
listProcesses?: () => Promise<HookProcessBaseInfo[]>;
/** Local account detection used to label each process with the account QQ is
* signed in as. Receives the pids to label so each one is resolved against
* the HOME it actually runs under (a container can give every QQ instance
* its own). Defaults to reading QQ's own account data. */
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
/** How often the watcher re-probes the account label of each process, in
* milliseconds. Defaults to `DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS`. */
accountReprobeIntervalMs?: number;
/** When true, every newly-discovered QQ process is auto-injected (fires
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
* Failed loads are logged and leave the session in the 'error' state.
@@ -94,13 +104,9 @@ export class HookManager {
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly pipeWatcher: PipeWatcher;
private readonly ownsPipeWatcher: boolean;
/** Watcher/API process enumeration — isolated + timeout-bounded by default
* so a blocked native /proc walk can't freeze the loop (issue #158).
* Resolves to `null` (UNKNOWN) on timeout/failure. */
private readonly enumerate: () => Promise<HookProcessBaseInfo[] | null>;
/** The owned enumerator (worker lifecycle), or null when a custom lister was
* injected (tests) — nothing to tear down in that case. */
private readonly enumerator: ProcessEnumerator | null;
private readonly enumerator: ProcessEnumerator;
private readonly detectAccounts: (pids: readonly number[]) => Promise<AccountLoginState[]>;
private readonly accountReprobeIntervalMs: number;
private readonly autoLoadOnDiscovery: boolean;
private readonly onSessionsChangedRaw?: () => void;
private readonly log: Logger;
@@ -108,6 +114,11 @@ export class HookManager {
private readonly autoLoadAttempts = new Map<number, AutoLoadAttempt>();
private readonly startPromise: Promise<void>;
private accounts = new Map<number, HookProcessAccount>();
private accountProbe: Promise<void> | null = null;
private nextAccountProbeAt = 0;
private lastAccountProbeFailure = '';
private disposed = false;
constructor(deps: HookManagerDeps) {
@@ -118,48 +129,25 @@ export class HookManager {
this.injector = deps.injector ?? {
inject: injectHookProcess,
unload: (pid, handle) => {
if (!handle) {
return;
}
unloadHookProcess(pid, handle);
},
unload: unloadHookProcess,
};
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
this.detectAccounts = deps.detectAccounts ?? detectAccountLoginsForPids;
this.accountReprobeIntervalMs =
deps.accountReprobeIntervalMs ?? DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS;
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
// A custom lister (tests) is used directly — no worker, no isolation, just
// an async wrap that maps a throw to the UNKNOWN sentinel. The default path
// wraps the native enumerator in a worker with a timeout.
if (deps.listProcesses) {
const lister = deps.listProcesses;
this.enumerator = null;
this.enumerate = async () => {
try {
return await lister();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
return null;
}
};
} else {
this.enumerator = createNativeProcessEnumerator({
addonPath: resolveHookNativePath('node'),
fallbackSync: listHookProcesses,
processName: defaultProcessName(),
log: this.log,
});
this.enumerate = () => this.enumerator!.enumerate();
}
this.enumerator = createProcessEnumerator({
listProcesses: deps.listProcesses ?? listHookProcesses,
log: this.log,
});
if (deps.pipeWatcher) {
this.pipeWatcher = deps.pipeWatcher;
this.ownsPipeWatcher = false;
} else {
this.pipeWatcher = new PipeWatcher({
listProcesses: this.enumerate,
listProcesses: this.enumerator.enumerate,
listLivePipes: (processes) =>
QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
intervalMs: deps.watcherIntervalMs,
@@ -176,23 +164,21 @@ export class HookManager {
async listProcesses(): Promise<HookProcessInfo[]> {
await this.startPromise;
const processes = await this.enumerate();
if (processes === null) {
// Enumeration timed out / failed — report the last-known sessions rather
// than an empty list (which the WebUI would render as "no QQ").
return [...this.sessions.values()].map((s) => s.toInfo()).sort((a, b) => a.pid - b.pid);
}
const result: HookProcessInfo[] = [];
for (const proc of processes) {
const session = this.ensureSession(proc.pid);
session.attachProcessInfo(proc);
result.push(session.toInfo());
}
return result.sort((a, b) => a.pid - b.pid);
const processes = await this.enumerator.enumerate();
// A failed enumeration preserves the last known process set.
const sessions =
processes === null
? [...this.sessions.values()]
: processes.map((proc) => {
const session = this.ensureSession(proc.pid);
session.attachProcessInfo(proc);
return session;
});
await this.refreshAccounts();
return sessions
.filter((session) => this.sessions.get(session.pid) === session)
.map((session) => this.processInfo(session))
.sort((a, b) => a.pid - b.pid);
}
async loadProcess(pid: number): Promise<HookProcessInfo> {
@@ -200,11 +186,10 @@ export class HookManager {
await this.startPromise;
this.autoLoadAttempts.delete(pid);
const session = this.ensureSession(pid);
const info = await session.load();
// Pull the next tick forward so a freshly-injected pipe gets noticed
// within the next event-loop turn instead of after the full interval.
await session.load();
this.pipeWatcher.wake();
return info;
await this.refreshAccounts();
return this.processInfo(session);
}
async unloadProcess(pid: number): Promise<HookProcessInfo> {
@@ -212,19 +197,18 @@ export class HookManager {
await this.startPromise;
this.autoLoadAttempts.delete(pid);
const session = this.ensureSession(pid);
return session.unload();
await session.unload();
await this.refreshAccounts();
return this.processInfo(session);
}
async refreshProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
return session.refresh();
}
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
this.assertValidPid(pid);
return probeQqLoginInfo(pid);
await session.refresh();
await this.refreshAccounts();
return this.processInfo(session);
}
dispose(): void {
@@ -239,8 +223,9 @@ export class HookManager {
}
this.sessions.clear();
this.accounts.clear();
this.autoLoadAttempts.clear();
this.enumerator?.dispose();
this.enumerator.dispose();
if (this.ownsPipeWatcher) {
this.pipeWatcher.dispose();
@@ -249,6 +234,80 @@ export class HookManager {
// ─────────────── wiring ───────────────
private processInfo(session: HookSession): HookProcessInfo {
return { ...session.toInfo(), account: this.accounts.get(session.pid) ?? null };
}
/** REST, watcher ticks and login reconciliation share the same account snapshot. */
private async refreshAccounts(): Promise<void> {
if (this.disposed) {
return;
}
if (this.accountProbe) {
await this.accountProbe;
// Process discovery invalidates the snapshot while a read is in flight.
if (this.nextAccountProbeAt === 0) {
await this.refreshAccounts();
}
return;
}
if (Date.now() < this.nextAccountProbeAt || this.sessions.size === 0) {
return;
}
this.nextAccountProbeAt = Date.now() + this.accountReprobeIntervalMs;
this.accountProbe = runWithTraceRequest(() => this.readAccounts()).finally(() => {
this.accountProbe = null;
});
await this.accountProbe;
}
private async readAccounts(): Promise<void> {
const sessions = new Map(this.sessions);
const accounts = new Map<number, HookProcessAccount>();
try {
for (const state of await this.detectAccounts([...sessions.keys()])) {
if (
state.pid !== null &&
sessions.has(state.pid) &&
this.sessions.get(state.pid) === sessions.get(state.pid)
) {
accounts.set(state.pid, { uin: state.uin, nickname: state.nickname });
}
}
this.lastAccountProbeFailure = '';
} catch (error) {
const message = errorMessage(error);
if (this.lastAccountProbeFailure !== message) {
this.lastAccountProbeFailure = message;
this.log.warn('account detection failed: %s', message);
}
}
if (this.disposed) {
return;
}
const changed =
accounts.size !== this.accounts.size ||
[...accounts].some(([pid, account]) => {
const previous = this.accounts.get(pid);
return previous?.uin !== account.uin || previous.nickname !== account.nickname;
});
this.accounts = accounts;
if (changed) {
this.notifySessionsChanged();
}
}
private bindWatcher(): void {
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
if (this.disposed) {
@@ -338,6 +397,8 @@ export class HookManager {
return;
}
void this.refreshAccounts();
for (const session of this.sessions.values()) {
const autoLoad = this.autoLoadAttempts.get(session.pid);
@@ -480,10 +541,10 @@ export class HookManager {
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=unexpected_failure error=%j elapsedMs=%d',
session.pid,
attempt,
errMsg(err),
errorMessage(err),
Date.now() - startedAt,
);
this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errMsg(err));
this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errorMessage(err));
}
});
}
@@ -500,6 +561,10 @@ export class HookManager {
makeClient: this.makeClient,
pipeWatcher: this.pipeWatcher,
onPacket: this.onPacket,
detectLoginUin: async () => {
await this.refreshAccounts();
return this.accounts.get(pid)?.uin ?? null;
},
log: this.log,
});
session.attachProcessInfo({ name: defaultProcessName() });
@@ -523,9 +588,12 @@ export class HookManager {
});
session.on('disposed', () => {
this.sessions.delete(pid);
this.accounts.delete(pid);
this.nextAccountProbeAt = 0;
});
this.sessions.set(pid, session);
this.nextAccountProbeAt = 0;
return session;
}
@@ -544,7 +612,7 @@ export class HookManager {
try {
this.onSessionsChangedRaw();
} catch (err) {
this.log.warn('onSessionsChanged threw: %s', errMsg(err));
this.log.warn('onSessionsChanged threw: %s', errorMessage(err));
}
}
@@ -559,10 +627,6 @@ function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
function isTransientLibcMappingError(error: string): boolean {
return /^target process does not map \S*\/libc\.so\.6 while resolving mmap$/.test(error);
}
@@ -612,5 +676,4 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
}
export type { HookProcessBaseInfo } from './injector';
export type { QqPortLoginInfo } from './qq-port-probe';
export type { HookProcessInfo, HookProcessStatus } from './types';
export type { HookProcessAccount, HookProcessInfo, HookProcessStatus } from './types';

View File

@@ -4,7 +4,6 @@ import {
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
QqHookClient,
type QqHookSendReply,
} from './qq-hook-client';
export type OutboundHealthListener = (healthy: boolean) => void;
@@ -33,16 +32,16 @@ export class HookPacketClient implements PacketSender {
}
try {
const reply = (await this.client.send(serviceCmd, body, {
const reply = await this.client.send(serviceCmd, body, {
wantReply: true,
replyTimeoutMs: timeoutMs,
})) as QqHookSendReply;
});
this.setOutboundHealthy(true);
return {
success: reply.error === 0,
gotResponse: true,
errorCode: reply.error,
errorMessage: reply.message || '',
errorMessage: reply.message,
responseData: reply.body,
};
} catch (error) {

View File

@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { readFileSync } from 'fs';
import os from 'os';
import path from 'path';
@@ -57,10 +58,6 @@ function isProcessGoneError(error: unknown): boolean {
return code === 'ENOENT' || code === 'ESRCH';
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function ownRuntimeDir(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, ownUid: number): string {
const explicit = configuredDirectory(
env.SNOWLUMA_HOOK_RUNTIME_DIR,

View File

@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import {
createLogger,
runWithoutRequestContext,
@@ -9,9 +10,9 @@ import type { PacketSink } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
import { EventEmitter } from 'events';
import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult } from './injector';
import type { HookInjectResult, ManualMapHandle } from './injector';
import { detectUinForPid } from './qq-account';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import { statusFor } from './hook-status';
import type { HookProcessInfo, HookProcessStatus } from './types';
@@ -32,14 +33,14 @@ const RECEIVE_STALE_CONFIRM_MS = 15_000;
export type HookSessionDeps = {
injector: {
inject: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
unload: (pid: number, handle: HookInjectResult['handle']) => void;
inject: (pid: number) => Promise<HookInjectResult>;
unload: (pid: number, handle: ManualMapHandle) => Promise<void>;
};
makeClient: (pid: number) => QqHookClient;
/** Active, pipe-independent login probe (reads QQ's ptlogin/deeplink ports).
* Drives the login-reconcile safety net; injectable for tests. Defaults to
* `probeQqLoginInfo`. */
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
/** Account QQ's local data reports as signed in on `pid`, or null. Drives the
* login-reconcile safety net; injectable for tests. Defaults to
* `detectUinForPid`. */
detectLoginUin?: (pid: number) => Promise<string | null>;
/** Sync fast-path check used by load() to skip re-injection when a
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
* fresh poll — used after unload to dodge the up-to-1500ms cache
@@ -80,7 +81,7 @@ export class HookSession extends EventEmitter {
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly probeLogin: (pid: number) => Promise<QqPortLoginInfo | null>;
private readonly detectLoginUin: (pid: number) => Promise<string | null>;
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
private readonly onPacket: PacketSink | null;
private readonly log: Logger;
@@ -101,9 +102,9 @@ export class HookSession extends EventEmitter {
private bound = false;
private opChain: Promise<unknown> = Promise.resolve();
private disposed = false;
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
private probing = false;
private lastProbeFailure = '';
private loginReconcileTimer: ReturnType<typeof setInterval> | null = null;
private detecting = false;
private lastDetectFailure = '';
private acceptedLoginHintUin = '';
private loginHintAttemptUin = '';
private loginHintAttempts = 0;
@@ -121,7 +122,7 @@ export class HookSession extends EventEmitter {
this.pid = pid;
this.injector = deps.injector;
this.makeClient = deps.makeClient;
this.probeLogin = deps.probeLogin ?? probeQqLoginInfo;
this.detectLoginUin = deps.detectLoginUin ?? detectUinForPid;
this.pipeWatcher = deps.pipeWatcher;
this.onPacket = deps.onPacket ?? null;
this.log = deps.log ?? createLogger('HookSession');
@@ -170,6 +171,8 @@ export class HookSession extends EventEmitter {
status: this._status,
error: this._error,
method: this._method,
// Filled in by HookManager from the client's local account data.
account: null,
};
}
@@ -203,7 +206,9 @@ export class HookSession extends EventEmitter {
}
await this.reconcilePipeUp();
}).catch((err) => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
}).catch((err) =>
this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errorMessage(err)),
);
}
onPipeDown(): void {
@@ -217,7 +222,9 @@ export class HookSession extends EventEmitter {
}
this.reconcilePipeDown();
}).catch((err) => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
}).catch((err) =>
this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errorMessage(err)),
);
}
/** Called by the manager when the watcher reports the QQ.exe process is
@@ -265,7 +272,7 @@ export class HookSession extends EventEmitter {
this.log.trace(() => [
'hook_session_process_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid,
errMsg(error),
errorMessage(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
@@ -273,7 +280,7 @@ export class HookSession extends EventEmitter {
}
});
}).catch((err) =>
this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)),
this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errorMessage(err)),
);
}
@@ -345,7 +352,7 @@ export class HookSession extends EventEmitter {
this.pid,
operation,
`${operation}_threw`,
errMsg(error),
errorMessage(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
@@ -355,20 +362,12 @@ export class HookSession extends EventEmitter {
}
private serialize<T>(op: () => Promise<T>): Promise<T> {
const previous = this.opChain;
let release!: () => void;
const completion = new Promise<void>((resolve) => {
release = resolve;
});
this.opChain = previous.then(() => completion);
return (async () => {
try {
await previous.catch(() => undefined);
return await op();
} finally {
release();
}
})();
const result = this.opChain.then(op);
this.opChain = result.then(
() => undefined,
() => undefined,
);
return result;
}
// ─────────────── internal transitions ───────────────
@@ -409,7 +408,7 @@ export class HookSession extends EventEmitter {
this.applyStatus();
} catch (error) {
this._error = errMsg(error);
this._error = errorMessage(error);
this.setStatus('error', this._error);
this.log.error('load failed: PID=%d err=%s', this.pid, this._error);
// The module can already be listening even when this call returns
@@ -441,7 +440,7 @@ export class HookSession extends EventEmitter {
const handle = this.injectResult?.handle;
if (this.injected && handle) {
this.injector.unload(this.pid, handle);
await this.injector.unload(this.pid, handle);
this.log.info('SnowLuma unloaded from PID=%d', this.pid);
}
@@ -465,7 +464,7 @@ export class HookSession extends EventEmitter {
this.setStatus('available', '');
}
} catch (error) {
this._error = errMsg(error);
this._error = errorMessage(error);
this.setStatus('error', this._error);
this.log.error('unload failed: PID=%d err=%s', this.pid, this._error);
}
@@ -487,7 +486,7 @@ export class HookSession extends EventEmitter {
this.reconcilePipeDown();
}
} catch (error) {
this._error = errMsg(error);
this._error = errorMessage(error);
this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
}
@@ -579,7 +578,7 @@ export class HookSession extends EventEmitter {
this.log.trace(() => [
'hook_session_disconnect_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid,
errMsg(error),
errorMessage(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
@@ -636,7 +635,7 @@ export class HookSession extends EventEmitter {
this.applyStatus();
// The native hook only PUSHES a loginState frame on the login edge;
// if QQ logged in before/around connect (Docker auto-login) that edge
// is missed and we'd wait forever. Actively re-probe until logged in.
// is missed and we'd wait forever. Keep re-detecting until logged in.
runWithoutRequestContext(() => this.startLoginReconcile());
}
@@ -648,7 +647,7 @@ export class HookSession extends EventEmitter {
Date.now() - startedAt,
]);
} catch (error) {
this._error = errMsg(error);
this._error = errorMessage(error);
// Drop the client so the next attempt builds a fresh socket pair.
// A failed connect was never logged in → 'connecting' (or 'available').
this.tearDownClient();
@@ -668,7 +667,7 @@ export class HookSession extends EventEmitter {
client.on('packet', (packet) => this.handlePacket(packet));
client.on('loginState', (state) => this.handleLoginState(state));
client.on('error', (error) => {
const msg = errMsg(error);
const msg = errorMessage(error);
this._error = msg;
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
});
@@ -694,7 +693,7 @@ export class HookSession extends EventEmitter {
this.reconcilePipeDown();
}).catch((err) =>
this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)),
this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errorMessage(err)),
);
});
}
@@ -786,7 +785,7 @@ export class HookSession extends EventEmitter {
this.log.trace(() => [
'hook_session_login_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid,
errMsg(error),
errorMessage(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
@@ -796,39 +795,41 @@ export class HookSession extends EventEmitter {
}
// ─────────────── login reconcile (Docker auto-login safety net) ───────────
// The local endpoint can identify an auto-restored account before the
// runtime is ready. Forward identity for reconciliation, but never synthesize
// online state from the probe.
// QQ can restore an account on its own before the runtime is ready, and its
// local account data names that account. Forward the identity for
// reconciliation, but never synthesize online state from the detection.
private startLoginReconcile(): void {
if (this.loginProbeTimer || this.disposed) {
if (this.loginReconcileTimer || this.disposed) {
return;
}
this.log.info('awaiting login: PID=%d', this.pid);
void this.probeLoginOnce(); // immediate — catch already-logged-in fast
this.loginProbeTimer = setInterval(
() => void this.probeLoginOnce(),
void this.detectLoginOnce(); // immediate — catch already-logged-in fast
this.loginReconcileTimer = setInterval(
() => void this.detectLoginOnce(),
LOGIN_RECONCILE_INTERVAL_MS,
);
this.loginProbeTimer.unref?.();
this.loginReconcileTimer.unref();
}
private stopLoginReconcile(): void {
if (this.loginProbeTimer) {
clearInterval(this.loginProbeTimer);
this.loginProbeTimer = null;
if (this.loginReconcileTimer) {
clearInterval(this.loginReconcileTimer);
this.loginReconcileTimer = null;
}
}
private async probeLoginOnce(): Promise<void> {
// A port-scan probe can outlast the interval; skip overlapping ticks so a
// slow probe never stacks concurrent subprocess-spawning scans.
if (this.probing) {
private async detectLoginOnce(): Promise<void> {
// Detecting the account reads the filesystem; skip overlapping ticks so a
// slow read never stacks on top of the interval.
if (this.detecting) {
return;
}
if (this.disposed || !this.connected || this.loggedIn) {
const client = this.client;
if (this.disposed || !client || !this.connected || this.loggedIn) {
this.stopLoginReconcile();
return;
}
@@ -837,46 +838,44 @@ export class HookSession extends EventEmitter {
return;
}
this.probing = true;
this.detecting = true;
try {
let info: QqPortLoginInfo | null;
let uin: string | null;
try {
info = await this.probeLogin(this.pid);
uin = await this.detectLoginUin(this.pid);
} catch (error) {
const message = errMsg(error);
const note = `${this.pid}:${message}`;
const message = errorMessage(error);
if (this.lastProbeFailure !== note) {
this.lastProbeFailure = note;
this.log.warn('login probe failed: PID=%d err=%s', this.pid, message);
if (this.lastDetectFailure !== message) {
this.lastDetectFailure = message;
this.log.warn(
'login identity detection failed: PID=%d err=%s',
this.pid,
message,
);
}
return; // best-effort; the interval retries
}
// The await yielded — re-check we still want this before mutating state.
if (this.disposed || !this.connected || this.loggedIn) {
this.stopLoginReconcile();
// A reconnect owns a new client; an older read cannot supply its identity.
if (this.client !== client || this.disposed || !this.connected || this.loggedIn) {
return;
}
if (info?.identityKnown && isRealUin(info.uin)) {
const client = this.client;
this.lastDetectFailure = '';
if (!client) {
return;
}
if (this.acceptedLoginHintUin === info.uin) {
if (uin !== null && isRealUin(uin)) {
if (this.acceptedLoginHintUin === uin) {
this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
return;
}
if (this.loginHintAttemptUin !== info.uin) {
this.loginHintAttemptUin = info.uin;
if (this.loginHintAttemptUin !== uin) {
this.loginHintAttemptUin = uin;
this.loginHintAttempts = 0;
this.nextLoginHintAt = 0;
this.nextLoginIdentityObservationAt = 0;
@@ -893,11 +892,11 @@ export class HookSession extends EventEmitter {
this.log.info(
'login identity discovered: PID=%d UIN=%s; awaiting readiness',
this.pid,
info.uin,
uin,
);
try {
await client.reconcileLoginIdentity(info.uin);
await client.reconcileLoginIdentity(uin);
if (
this.client !== client ||
@@ -908,7 +907,7 @@ export class HookSession extends EventEmitter {
return;
}
this.acceptedLoginHintUin = info.uin;
this.acceptedLoginHintUin = uin;
this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} catch (error) {
@@ -920,9 +919,9 @@ export class HookSession extends EventEmitter {
this.log.warn(
'login identity reconciliation failed: PID=%d UIN=%s attempts=%d err=%s',
this.pid,
info.uin,
uin,
attempt,
errMsg(error),
errorMessage(error),
);
this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
@@ -932,15 +931,15 @@ export class HookSession extends EventEmitter {
this.log.trace(
'login identity hint failed: PID=%d UIN=%s attempt=%d err=%s',
this.pid,
info.uin,
uin,
attempt,
errMsg(error),
errorMessage(error),
);
}
}
}
} finally {
this.probing = false;
this.detecting = false;
}
}
@@ -950,7 +949,7 @@ export class HookSession extends EventEmitter {
this.loginHintAttempts = 0;
this.nextLoginHintAt = 0;
this.nextLoginIdentityObservationAt = 0;
this.lastProbeFailure = '';
this.lastDetectFailure = '';
}
private handlePacket(packet: QqHookPacket): void {
@@ -1075,9 +1074,9 @@ export class HookSession extends EventEmitter {
silentForMs,
);
}, RECEIVE_STALE_CONFIRM_MS);
this.receiveWatchTimer.unref?.();
this.receiveWatchTimer.unref();
}, RECEIVE_STALE_AFTER_MS);
this.receiveWatchTimer.unref?.();
this.receiveWatchTimer.unref();
}
private shouldWatchReceive(): boolean {
@@ -1132,7 +1131,3 @@ export class HookSession extends EventEmitter {
this._receiveHealthy = true;
}
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}

View File

@@ -2,8 +2,14 @@ export {
HookManager,
type BridgeManagerSink,
type HookManagerDeps,
type HookProcessAccount,
type HookProcessBaseInfo,
type HookProcessInfo,
type HookProcessStatus,
type QqPortLoginInfo,
} from './hook-manager';
export { type AccountLoginState, type LocalAccount } from './qq-account';
export {
getRuntimeIntegrity,
hasLowProcessIntegrity,
type RuntimeIntegrity,
} from './runtime-integrity';

View File

@@ -1,11 +1,8 @@
import { existsSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { errorMessage } from '@snowluma/common/errors';
import { resolveRuntimeNativePath } from '@snowluma/common/native-path';
import { listSnowlumaPipePidsSync } from './qq-hook-client';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface ManualMapHandle {
base: bigint;
entry: bigint;
@@ -14,9 +11,11 @@ export interface ManualMapHandle {
}
interface NativeHookAddon {
getAllMainProcess(): number[];
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
getRuntimeIntegrityAsync(): Promise<unknown>;
getAllMainProcessAsync(): Promise<number[]>;
getFileHoldersAsync(path: string): Promise<{ pid: number; name: string }[]>;
loadModuleManualAsync(pid: number, dylibPath: string): Promise<ManualMapHandle>;
unloadModuleManualAsync(pid: number, handle: ManualMapHandle): Promise<void>;
}
export interface HookProcessBaseInfo {
@@ -27,7 +26,7 @@ export interface HookProcessBaseInfo {
export interface HookInjectResult {
method: 'loadModuleManual';
handle?: ManualMapHandle;
handle: ManualMapHandle;
}
let nativeAddon: NativeHookAddon | null = null;
@@ -41,14 +40,6 @@ function loadNativeAddon(addonPath: string): NativeHookAddon {
type HookBinaryExt = 'node' | 'dll' | 'so';
function platformBinaryName(ext: HookBinaryExt): string {
if (process.platform === 'win32' && process.arch === 'x64') {
return `snowluma-win32-x64.${ext}`;
}
return `snowluma-${process.platform}-${process.arch}.${ext}`;
}
function platformInjectableExt(): 'dll' | 'so' {
return process.platform === 'win32' ? 'dll' : 'so';
}
@@ -57,33 +48,8 @@ function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
}
function nativeSearchDirs(): string[] {
// Several layouts must be supported:
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
// → walk up to <root>/packages and append runtime/native
// Same offset works for `packages/bridge/dist/index.mjs` after build.
// 3. cwd-based fallback when neither __dirname-relative path resolves.
return [
path.resolve(__dirname, 'native'),
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
path.resolve(process.cwd(), 'dist', 'native'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
];
}
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
const fileName = platformBinaryName(ext);
for (const dir of nativeSearchDirs()) {
const fullPath = path.join(dir, fileName);
if (existsSync(fullPath)) {
return fullPath;
}
}
return null;
return resolveRuntimeNativePath(`snowluma-${process.platform}-${process.arch}.${ext}`);
}
export function getNativeHookAddon(): NativeHookAddon | null {
@@ -103,7 +69,7 @@ export function getNativeHookAddon(): NativeHookAddon | null {
nativeLoadError = null;
return nativeAddon;
} catch (error) {
nativeLoadError = error instanceof Error ? error.message : String(error);
nativeLoadError = errorMessage(error);
return null;
}
}
@@ -112,7 +78,7 @@ export function getNativeHookLoadError(): string | null {
return nativeLoadError;
}
export function listHookProcesses(): HookProcessBaseInfo[] {
export async function listHookProcesses(): Promise<HookProcessBaseInfo[]> {
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
// means QQ ran with our dylib already mapped, so the dylib's listener
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
@@ -128,10 +94,16 @@ export function listHookProcesses(): HookProcessBaseInfo[] {
const addon = getNativeHookAddon();
if (!addon) {
return [];
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
return [...new Set(addon.getAllMainProcess())]
if (typeof addon.getAllMainProcessAsync !== 'function') {
throw new Error(
'Hook native addon lacks getAllMainProcessAsync; update the native artifacts',
);
}
return [...new Set(await addon.getAllMainProcessAsync())]
.filter((pid) => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
@@ -151,15 +123,15 @@ export async function injectHookProcess(pid: number): Promise<HookInjectResult>
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
}
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) };
return { method: 'loadModuleManual', handle: await addon.loadModuleManualAsync(pid, dllPath) };
}
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
export async function unloadHookProcess(pid: number, handle: ManualMapHandle): Promise<void> {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
addon.unloadModuleManual(pid, handle);
await addon.unloadModuleManualAsync(pid, handle);
}

View File

@@ -1,55 +1,36 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { EventEmitter } from 'events';
import { EventEmitter } from 'node:events';
import { setImmediate as nextTurn } from 'node:timers/promises';
import type { HookProcessBaseInfo } from './injector';
const DEFAULT_INTERVAL_MS = 1500;
const MIN_INTERVAL_MS = 250;
export type PipeWatcherDeps = {
/** Native: list QQ.exe processes currently running. May be async and may
* return `null` (UNKNOWN) when enumeration timed out / failed — in which
* case this tick keeps the prior process+pipe state instead of treating the
* missing data as "everything disappeared" (issue #158). */
listProcesses: () => HookProcessBaseInfo[] | null | Promise<HookProcessBaseInfo[] | null>;
/** Native: PIDs that currently have a live SnowLuma named pipe. The current
* process snapshot lets Linux inspect each target user's runtime directory. */
/** Failed enumeration returns null and preserves the last known snapshot. */
listProcesses: () => Promise<HookProcessBaseInfo[] | null>;
/** Linux uses this snapshot to locate each target user's runtime directory. */
listLivePipes: (processes: readonly HookProcessBaseInfo[]) => Promise<Set<number>>;
/** Polling interval in ms. Defaults to 1500, floored to 250. */
intervalMs?: number;
log?: Logger;
};
/**
* PipeWatcher — the only module that polls the OS for QQ.exe processes
* and live SnowLuma named pipes. Subscribers consume diffs as events.
*
* Lifecycle: start() runs one tick synchronously, then schedules a poll
* every `intervalMs`. tickNow() drains a single tick on demand. wake()
* pulls the next scheduled tick forward to the next event-loop turn.
*
* Emitted events:
* 'process-discovered' (info: HookProcessBaseInfo) — a QQ.exe appeared
* 'process-gone' (pid: number) — a QQ.exe disappeared
* 'pipe-up' (pid: number) — named pipe came up
* 'pipe-down' (pid: number) — named pipe dropped
* 'tick' () — fired after every poll
*
* Within a single tick the order is: process-discovered, pipe-up,
* pipe-down, process-gone, tick. That ordering lets HookManager create
* a session before it gets a pipe event and run disconnect logic before
* dispose logic when QQ.exe is killed with a live pipe.
*/
type PipeEvent =
| ['process-discovered', HookProcessBaseInfo]
| ['pipe-up' | 'pipe-down' | 'process-gone', number];
/** Publishes process and pipe snapshots, then emits their ordered differences. */
export class PipeWatcher extends EventEmitter {
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
private readonly intervalMs: number;
private readonly log: Logger;
private livePipes = new Set<number>();
private knownPids = new Set<number>();
private timer: NodeJS.Timeout | null = null;
private ticking = false;
private pendingWake = false;
private tickTask: Promise<void> | null = null;
private pendingTick = false;
private startPromise: Promise<void> | null = null;
private stopped = false;
@@ -61,51 +42,63 @@ export class PipeWatcher extends EventEmitter {
this.log = deps.log ?? createLogger('PipeWatcher');
}
/** Was this PID's pipe live as of the last completed tick? */
isPipeLive(pid: number): boolean {
return this.livePipes.has(pid);
}
/** Was this PID alive as of the last completed tick? */
isProcessAlive(pid: number): boolean {
return this.knownPids.has(pid);
}
/**
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
* and begin the polling loop. Idempotent.
*/
/** Read the initial snapshot and start polling. Repeated calls share startup. */
start(): Promise<void> {
if (this.startPromise) {
return this.startPromise;
}
this.startPromise = (async () => {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
})();
return this.startPromise;
return (this.startPromise ??= this.tickNow().finally(() => {
this.scheduleNext(this.intervalMs);
}));
}
/** Pull the next scheduled tick forward to the next event-loop turn. */
/** Coalesce wake requests into one scan after the current read. */
wake(): void {
if (this.stopped) {
return;
}
this.scheduleNext(0);
if (this.tickTask) {
this.pendingTick = true;
} else {
this.scheduleNext(0);
}
}
/** Force a single tick now. Resolves after diff events have been emitted. */
/** Wait for a fresh snapshot, including a scan queued behind an active read. */
tickNow(): Promise<void> {
return this.tickOnce();
if (this.stopped) {
return Promise.resolve();
}
if (this.tickTask) {
this.pendingTick = true;
return this.tickTask;
}
this.tickTask = (async () => {
do {
this.pendingTick = false;
await this.readSnapshot();
if (this.pendingTick && !this.stopped) {
await nextTurn();
}
} while (this.pendingTick && !this.stopped);
})().finally(() => {
this.tickTask = null;
});
return this.tickTask;
}
stop(): void {
this.stopped = true;
this.pendingTick = false;
if (this.timer) {
clearTimeout(this.timer);
@@ -125,139 +118,100 @@ export class PipeWatcher extends EventEmitter {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(
() => {
this.timer = null;
void this.tickAndReschedule();
},
Math.max(0, delayMs),
);
this.timer = setTimeout(() => {
this.timer = null;
void this.tickAndReschedule();
}, delayMs);
}
private async tickAndReschedule(): Promise<void> {
try {
await this.tickOnce();
await this.tickNow();
} catch (error) {
this.log.warn('poll failed: %s', errorMessage(error));
} finally {
this.scheduleNext(this.intervalMs);
}
}
/**
* Read processes + live pipes, emit diff events. If another tick is
* already running, mark a follow-up tick so we don't lose a wake().
*/
private async tickOnce(): Promise<void> {
if (this.ticking) {
this.pendingWake = true;
private async readSnapshot(): Promise<void> {
let processes: HookProcessBaseInfo[] | null;
try {
processes = await this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errorMessage(error));
processes = null;
}
if (this.stopped) {
return;
}
this.ticking = true;
if (processes === null) {
// Missing data must not disconnect healthy sessions. Reconnect retries
// still run against the last known snapshot (issue #158).
this.emit('tick');
return;
}
let livePipes: Set<number>;
try {
let processes: HookProcessBaseInfo[] | null;
livePipes = await this.listLivePipes(processes);
} catch (error) {
this.log.warn('listLivePipes failed: %s', errorMessage(error));
livePipes = this.livePipes;
}
try {
processes = await this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = null;
if (this.stopped) {
return;
}
const knownPids = new Set(processes.map(({ pid }) => pid));
const currentPipes = new Set([...livePipes].filter((pid) => knownPids.has(pid)));
const events: PipeEvent[] = [];
for (const process of processes) {
if (!this.knownPids.has(process.pid)) {
events.push(['process-discovered', process]);
}
}
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
// Treating missing data as "everything disappeared" would fire
// process-gone for every live PID and dispose healthy sessions — the
// freeze-then-teardown footgun behind issue #158. Still emit 'tick' so
// the manager's per-tick reconnect retries keep running off last-known
// live pipes.
if (processes === null) {
this.emit('tick');
for (const pid of currentPipes) {
if (!this.livePipes.has(pid)) {
events.push(['pipe-up', pid]);
}
}
// Disconnect pipes before disposing their departed processes.
for (const pid of this.livePipes) {
if (!currentPipes.has(pid)) {
events.push(['pipe-down', pid]);
}
}
for (const pid of this.knownPids) {
if (!knownPids.has(pid)) {
events.push(['process-gone', pid]);
}
}
this.knownPids = knownPids;
this.livePipes = currentPipes;
for (const [event, payload] of events) {
if (this.stopped) {
return;
}
let livePipes: Set<number> | null;
this.emit(event, payload);
}
try {
livePipes = await this.listLivePipes(processes);
} catch (error) {
this.log.warn('listLivePipes failed: %s', errMsg(error));
livePipes = null;
}
const newKnownPids = new Set<number>();
for (const proc of processes) {
newKnownPids.add(proc.pid);
}
// 1. Newly discovered processes.
for (const proc of processes) {
if (!this.knownPids.has(proc.pid)) {
this.emit('process-discovered', proc);
}
}
// 2. Pipes that came up. Ignore pipes for processes we don't know
// about (would race against an out-of-order tick).
const newLivePipes = new Set<number>();
if (livePipes === null) {
// Keep the last known pipe state for processes that still exist, while
// allowing confirmed process exits to complete their normal teardown.
for (const pid of this.livePipes) {
if (newKnownPids.has(pid)) {
newLivePipes.add(pid);
}
}
} else {
for (const pid of livePipes) {
if (!newKnownPids.has(pid)) {
continue;
}
newLivePipes.add(pid);
if (!this.livePipes.has(pid)) {
this.emit('pipe-up', pid);
}
}
}
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
// subscribers can run disconnect logic before dispose logic.
for (const pid of this.livePipes) {
if (!newLivePipes.has(pid)) {
this.emit('pipe-down', pid);
}
}
// 4. Processes that disappeared.
for (const pid of this.knownPids) {
if (!newKnownPids.has(pid)) {
this.emit('process-gone', pid);
}
}
this.knownPids = newKnownPids;
this.livePipes = newLivePipes;
if (!this.stopped) {
this.emit('tick');
} finally {
this.ticking = false;
if (this.pendingWake) {
this.pendingWake = false;
// Defer to break sync recursion if a listener calls wake().
setImmediate(() => {
void this.tickOnce();
});
}
}
}
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}

View File

@@ -1,291 +1,77 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { Worker } from 'worker_threads';
import type { HookProcessBaseInfo } from './injector';
/**
* Isolated, timeout-bounded wrapper around the native `getAllMainProcess()`
* enumeration.
*
* Why this exists (issue #158): the watcher polls QQ processes every ~1.5s by
* calling the synchronous native enumerator, which walks `/proc` and reads each
* candidate's `cmdline`/`maps`. Those reads go through the target's mm and
* BLOCK while a process is mid-`exec()` — exactly what happens when QQ runs a
* silent hot-update and the process table churns. A blocked synchronous native
* call freezes the whole Node event loop: OneBot stops responding, the watcher
* stops ticking, reconnect logic never runs. The process stays "alive" so the
* supervisor never restarts it — the bot just goes silent.
*
* The only way to put a real timeout on a synchronous native call is to run it
* off the main thread. We run it in a worker; the main thread races the result
* against a deadline. On timeout the main loop keeps going (it returns the
* UNKNOWN sentinel `null`, which the watcher treats as "no fresh data, keep
* prior state" — crucially NOT "all processes gone"). The blocked worker is
* abandoned (a fresh one is spawned next time); it exits on its own once the
* native call finally returns.
*
* Graceful degradation: if the native addon can't be loaded in a worker (e.g.
* it isn't context-aware) or there's no addon at all (macOS reads sockets, not
* `/proc`), we fall back to calling `fallbackSync` on the main thread — i.e.
* exactly today's behaviour, no worse.
*/
export interface ProcessEnumerator {
/** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed
* out / failed and the caller should keep its prior state. */
/** null means unknown: keep the previous process set. */
enumerate(): Promise<HookProcessBaseInfo[] | null>;
dispose(): void;
}
export interface NativeEnumeratorDeps {
/** Resolved path to the hook `.node` addon, or null when there is none
* (macOS / missing) — in which case we never spawn a worker. */
addonPath: string | null;
/** Synchronous lister used when worker isolation is unavailable. Returns
* today's value (and may itself block — that's the no-worse-than-before
* fallback). */
fallbackSync: () => HookProcessBaseInfo[];
/** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */
processName: string;
/** Per-enumeration deadline. Default 4000ms — comfortably above a healthy
* enumeration (single-digit ms) but well under a human "is it dead?". */
interface ProcessEnumeratorDeps {
listProcesses: () => Promise<HookProcessBaseInfo[]>;
timeoutMs?: number;
/** Cap on abandoned (blocked) workers before we stop spawning more and just
* return UNKNOWN until they drain. Bounds thread growth across a long
* hot-update window. Default 4. */
maxOrphans?: number;
log?: Logger;
}
const DEFAULT_TIMEOUT_MS = 4000;
const DEFAULT_MAX_ORPHANS = 4;
// Worker body (CommonJS — eval workers default to CJS so `require` is available;
// `process.dlopen` is a global and needs no module system). Loads the addon
// handed in via workerData, then answers each 'enumerate' with the raw pid list
// from the blocking native call. All the cheap post-processing stays on main.
const WORKER_SOURCE = `
const { parentPort, workerData } = require('node:worker_threads');
let addon = null;
try {
const mod = { exports: {} };
process.dlopen(mod, workerData.addonPath);
addon = mod.exports;
} catch (e) {
parentPort.postMessage({ type: 'fatal', error: String((e && e.message) || e) });
}
if (addon) {
parentPort.on('message', (msg) => {
if (!msg || msg.type !== 'enumerate') return;
try {
const pids = addon.getAllMainProcess();
parentPort.postMessage({ type: 'result', id: msg.id, pids: Array.from(pids) });
} catch (e) {
parentPort.postMessage({ type: 'error', id: msg.id, error: String((e && e.message) || e) });
}
});
parentPort.postMessage({ type: 'ready' });
}
`;
function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] {
return [...new Set(pids)]
.filter((pid) => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map((pid) => ({ pid, name: processName, path: '' }));
}
export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator {
export function createProcessEnumerator(deps: ProcessEnumeratorDeps): ProcessEnumerator {
const log = deps.log ?? createLogger('ProcessEnumerator');
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
// fallback there is a cheap socket read, not a /proc walk.
if (!deps.addonPath) {
return {
async enumerate() {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate fallback failed: %s', errMsg(err));
return null;
}
},
dispose() {
/* nothing to tear down */
},
};
}
const addonPath = deps.addonPath;
let worker: Worker | null = null;
/** Set once we learn the addon can't load in a worker — permanent fallback. */
let isolationBroken = false;
let orphans = 0;
let seq = 0;
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
const timeoutMs = deps.timeoutMs ?? 4000;
let disposed = false;
const spawnWorker = (): void => {
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
worker = w;
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
if (msg.type === 'ready') {
return;
}
if (msg.type === 'fatal') {
// The addon won't load off-thread — give up on isolation for good and
// fall back to the synchronous path from here on. Resolve any in-flight
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
log.warn(
'process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration',
msg.error ?? '',
);
isolationBroken = true;
for (const { resolve } of pending.values()) {
resolve(null);
}
pending.clear();
teardownWorker();
return;
}
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
const entry = pending.get(msg.id);
if (!entry) {
return;
}
pending.delete(msg.id);
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
}
});
w.on('error', (err) => {
log.warn('enumeration worker error: %s', errMsg(err));
if (worker === w) {
teardownWorker();
}
});
};
const teardownWorker = (): void => {
const w = worker;
worker = null;
if (!w) {
return;
}
// terminate() can't preempt a thread blocked in the native call; it takes
// effect once the call returns. Track it as an orphan until it actually
// exits so we can bound how many we let pile up.
orphans += 1;
w.once('exit', () => {
orphans = Math.max(0, orphans - 1);
});
void w.terminate().catch(() => {
/* already gone */
});
};
const syncFallback = (): HookProcessBaseInfo[] | null => {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate sync fallback failed: %s', errMsg(err));
return null;
}
};
let pending: {
promise: Promise<HookProcessBaseInfo[] | null>;
settle: (result: HookProcessBaseInfo[] | null) => void;
} | null = null;
return {
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
if (disposed || isolationBroken) {
return syncFallback();
enumerate() {
if (disposed) {
return Promise.resolve(null);
}
if (!worker) {
if (orphans >= maxOrphans) {
// Too many blocked workers already piling up (a sustained hang) —
// don't spawn more; report UNKNOWN and let them drain.
return null;
}
spawnWorker();
if (pending) {
return pending.promise;
}
const w = worker;
if (!w) {
return syncFallback();
}
const id = ++seq;
const resultPromise = new Promise<number[] | null>((resolve) => {
pending.set(id, { resolve });
let resolve!: (result: HookProcessBaseInfo[] | null) => void;
const promise = new Promise<HookProcessBaseInfo[] | null>((done) => {
resolve = done;
});
try {
w.postMessage({ type: 'enumerate', id });
} catch (err) {
pending.delete(id);
log.warn('failed to post enumerate request: %s', errMsg(err));
teardownWorker();
return syncFallback();
}
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), timeoutMs);
});
const outcome = await Promise.race([resultPromise, timeout]);
if (timer) {
const settle = (result: HookProcessBaseInfo[] | null) => {
clearTimeout(timer);
}
resolve(result);
};
if (outcome === 'timeout') {
pending.delete(id);
const timer = setTimeout(() => {
log.warn(
'process enumeration timed out after %dms (worker abandoned) — keeping prior process set',
'process enumeration timed out after %dms; keeping prior process set',
timeoutMs,
);
teardownWorker();
return null;
}
settle(null);
}, timeoutMs);
pending = { promise, settle };
if (outcome === null) {
// Native call threw inside the worker — treat as a transient failure,
// keep prior state rather than nuking every session.
return null;
}
return mapPids(outcome, deps.processName);
// A timeout ends the wait, not the native call. Keep its slot until it
// finishes so subsequent polls cannot accumulate blocked native work.
void Promise.resolve()
.then(() => (disposed ? null : deps.listProcesses()))
.then(
(processes) => {
pending = null;
settle(disposed ? null : processes);
},
(error) => {
pending = null;
log.warn('process enumeration failed: %s', errorMessage(error));
settle(null);
},
);
return promise;
},
dispose() {
disposed = true;
for (const { resolve } of pending.values()) {
resolve(null);
}
pending.clear();
const w = worker;
worker = null;
if (w) {
void w.terminate().catch(() => {
/* ignore */
});
}
pending?.settle(null);
},
};
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}

View File

@@ -0,0 +1,107 @@
import fs from 'node:fs/promises';
import { getNativeHookAddon } from '../injector';
export interface DatabaseHolder {
pid: number;
name: string;
}
export async function getDatabaseHolders(dbPath: string): Promise<DatabaseHolder[]> {
if (process.platform === 'win32') {
return getWindowsHolders(dbPath);
}
return process.platform === 'linux' ? getLinuxHolders(dbPath) : [];
}
async function getWindowsHolders(dbPath: string): Promise<DatabaseHolder[]> {
const addon = getNativeHookAddon();
if (!addon?.getFileHoldersAsync) {
throw new Error('Windows account detection requires a hook addon with getFileHoldersAsync');
}
const holders = await addon.getFileHoldersAsync(dbPath);
if (
!Array.isArray(holders) ||
holders.some(
(holder) =>
!holder ||
!Number.isInteger(holder.pid) ||
holder.pid <= 0 ||
typeof holder.name !== 'string',
)
) {
throw new Error('Invalid database holders returned by the hook addon');
}
return holders;
}
export function isQqProcessName(name: string): boolean {
return (
name
.trim()
.toLowerCase()
.replace(/\.exe$/, '') === 'qq'
);
}
/** Match POSIX locks by device and inode; the table does not contain file paths. */
async function getLinuxHolders(dbPath: string): Promise<DatabaseHolder[]> {
const stat = await fs.stat(dbPath).catch((error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT') {
return null;
}
throw error;
});
if (!stat) {
return [];
}
const key = deviceInodeKey(stat.dev, stat.ino);
const table = await fs.readFile('/proc/locks', 'utf8');
const holders: DatabaseHolder[] = [];
const seen = new Set<number>();
for (const line of table.split('\n')) {
// `<id>: <type> <advisory|mandatory> <read|write> <pid> <dev>:<inode> <start> <end>`
const fields = line.trim().split(/\s+/);
if (fields.length < 8 || fields[5] !== key) {
continue;
}
const pid = Number(fields[4]);
if (!Number.isInteger(pid) || pid <= 0 || seen.has(pid)) {
continue;
}
seen.add(pid);
holders.push({ pid, name: await readProcessName(pid) });
}
return holders;
}
function deviceInodeKey(device: number, inode: number): string {
const major = (device >> 8) & 0xfff;
const minor = (device & 0xff) | ((device >> 12) & 0xfff00);
return `${major.toString(16).padStart(2, '0')}:${minor.toString(16).padStart(2, '0')}:${inode}`;
}
async function readProcessName(pid: number): Promise<string> {
try {
return (await fs.readFile(`/proc/${pid}/comm`, 'utf8')).trim();
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return '';
}
throw error;
}
}

View File

@@ -0,0 +1,62 @@
import { createLogger } from '@snowluma/common/logger';
import { isQqProcessName, getDatabaseHolders } from './database-holders';
import { readLocalAccounts, type LocalAccount } from './login-db';
import { loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths';
const log = createLogger('QqAccount');
const reportedFailures = new Map<string, string>();
export interface AccountLoginState extends LocalAccount {
pid: number | null;
}
export async function detectAccountLogins(
roots: readonly string[] = qqDataRoots(),
): Promise<AccountLoginState[]> {
const states: AccountLoginState[] = [];
for (const root of roots) {
const report = await readLocalAccounts(root);
for (const dbPath of loginDbPaths(root)) {
const failure = report.failures.find((item) => item.path === dbPath);
if (!failure) {
reportedFailures.delete(dbPath);
continue;
}
const detail =
failure.error instanceof Error
? failure.error.message
: String(failure.error ?? '');
const reason = detail ? failure.reason + ': ' + detail : failure.reason;
if (reportedFailures.get(dbPath) !== reason) {
reportedFailures.set(dbPath, reason);
log.warn('login.db unreadable: path=%s reason=%s', dbPath, reason);
}
}
for (const account of report.accounts) {
const holder = (await getDatabaseHolders(ntMsgDbPath(root, account))).find(
(candidate) => isQqProcessName(candidate.name),
);
states.push({ ...account, pid: holder?.pid ?? null });
}
}
return states;
}
export async function detectAccountLoginsForPids(
pids: readonly number[],
): Promise<AccountLoginState[]> {
const roots = [...new Set(pids.flatMap((pid) => qqDataRootsForPid(pid)))];
return detectAccountLogins(roots);
}
export async function detectUinForPid(pid: number): Promise<string | null> {
const accounts = await detectAccountLoginsForPids([pid]);
return accounts.find((account) => account.pid === pid)?.uin ?? null;
}

View File

@@ -0,0 +1,22 @@
export { isQqProcessName, getDatabaseHolders, type DatabaseHolder } from './database-holders';
export {
detectAccountLogins,
detectAccountLoginsForPids,
detectUinForPid,
type AccountLoginState,
} from './detect';
export {
readLocalAccounts,
type LocalAccount,
type LocalAccountReport,
type LoginDbFailure,
} from './login-db';
export { accountDirName, loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths';
export {
decryptDatabase,
detectAlgorithm,
type DecryptedDatabase,
type KdfHmacAlgorithm,
type PageHmacAlgorithm,
type SqlcipherAlgorithm,
} from './sqlcipher';

View File

@@ -0,0 +1,199 @@
import { isRealUin } from '@snowluma/common/uin';
import { SqliteDatabase } from '@snowluma/sqlite';
import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { loginDbPaths } from './paths';
import { decryptDatabase, detectAlgorithm } from './sqlcipher';
const LOGIN_DB_PASSPHRASE = 'BD156D6710D54D8782F4';
const COLUMN_UIN = '1000';
const COLUMN_UID = '1001';
const COLUMN_NICKNAME = '1007';
export interface LocalAccount {
uin: string;
uid: string;
nickname: string;
}
export type LoginDbFailure = 'read-failed' | 'undecryptable' | 'query-failed';
type LoginDbResult = { accounts: LocalAccount[] } | { failure: LoginDbFailure; error?: unknown };
export interface LocalAccountReport {
accounts: LocalAccount[];
failures: Array<{ path: string; reason: LoginDbFailure; error?: unknown }>;
}
// Share concurrent reads and invalidate when either the database or its WAL changes.
const accountCache = new Map<string, { stamp: string; result: Promise<LoginDbResult> }>();
export async function readLocalAccounts(root: string): Promise<LocalAccountReport> {
const merged = new Map<string, LocalAccount>();
const failures: LocalAccountReport['failures'] = [];
for (const dbPath of loginDbPaths(root)) {
const result = await readLoginDb(dbPath);
if ('failure' in result) {
failures.push({ path: dbPath, reason: result.failure, error: result.error });
continue;
}
for (const account of result.accounts) {
if (!merged.has(account.uin)) {
merged.set(account.uin, account);
}
}
}
return { accounts: [...merged.values()], failures };
}
async function readLoginDb(dbPath: string): Promise<LoginDbResult> {
let stamp: string;
try {
const files = await Promise.all([statIfPresent(dbPath), statIfPresent(dbPath + '-wal')]);
stamp = files.map((info) => (info ? info.mtimeMs + ':' + info.size : '-')).join('|');
} catch (error) {
accountCache.delete(dbPath);
return { failure: 'read-failed', error };
}
const cached = accountCache.get(dbPath);
if (cached?.stamp === stamp) {
return cached.result;
}
const entry = { stamp, result: decryptAndQuery(dbPath) };
accountCache.set(dbPath, entry);
const result = await entry.result;
if ('failure' in result && accountCache.get(dbPath) === entry) {
accountCache.delete(dbPath);
}
return result;
}
async function decryptAndQuery(dbPath: string): Promise<LoginDbResult> {
let image: Buffer;
let wal: Buffer | null;
try {
const contents = await readIfPresent(dbPath);
if (!contents) {
return { accounts: [] };
}
image = contents;
wal = await readIfPresent(dbPath + '-wal');
} catch (error) {
return { failure: 'read-failed', error };
}
const algorithm = detectAlgorithm(image, LOGIN_DB_PASSPHRASE);
if (!algorithm) {
return { failure: 'undecryptable' };
}
const decrypted = decryptDatabase(image, wal, LOGIN_DB_PASSPHRASE, algorithm);
if (!decrypted) {
return { failure: 'undecryptable' };
}
try {
return { accounts: await queryLoginTable(decrypted.image) };
} catch (error) {
return { failure: 'query-failed', error };
}
}
// SQLite opens a private temporary image; QQ's database and sidecars stay read-only.
async function queryLoginTable(image: Buffer): Promise<LocalAccount[]> {
const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-qq-login-'));
const dbPath = path.join(directory, 'login.db');
try {
await writeFile(dbPath, image, { mode: 0o600 });
const db = new SqliteDatabase(dbPath, { readOnly: true });
try {
const rows = await db
.prepare(
`SELECT [${COLUMN_UIN}], [${COLUMN_UID}], [${COLUMN_NICKNAME}] FROM login_table`,
)
.all();
const accounts: LocalAccount[] = [];
for (const row of rows) {
const account = {
uin: asText(row[COLUMN_UIN]),
uid: asText(row[COLUMN_UID]),
nickname: asText(row[COLUMN_NICKNAME]),
};
if (isRealUin(account.uin) && account.uid.length > 0) {
accounts.push(account);
}
}
return accounts;
} finally {
await db.close();
}
} finally {
await rm(directory, { recursive: true, force: true });
}
}
async function readIfPresent(file: string): Promise<Buffer | null> {
try {
return await readFile(file);
} catch (error) {
if (isNotFound(error)) {
return null;
}
throw error;
}
}
function isNotFound(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
}
async function statIfPresent(file: string) {
try {
return await stat(file);
} catch (error) {
if (isNotFound(error)) {
return null;
}
throw error;
}
}
/** SQLite values arrive as numbers, strings or blobs depending on the column. */
function asText(value: unknown): string {
if (typeof value === 'string') {
return value;
}
if (typeof value === 'number' || typeof value === 'bigint') {
return String(value);
}
if (value instanceof Uint8Array) {
return Buffer.from(value).toString('utf8');
}
return '';
}

View File

@@ -0,0 +1,161 @@
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import path from 'node:path';
const LOGIN_DB_SEGMENTS = ['nt_db', 'login.db'] as const;
export function qqDataRoots(): string[] {
if (process.platform === 'win32') {
return windowsDataRoots();
}
if (process.platform === 'linux') {
return linuxDataRoots({ ...process.env, HOME: process.env.HOME || homedir() });
}
return [];
}
/** Each Linux client owns its HOME; an unavailable process has no known root. */
export function qqDataRootsForPid(pid: number): string[] {
if (process.platform === 'win32') {
return windowsDataRoots();
}
if (process.platform !== 'linux') {
return [];
}
const environment = readProcessEnvironment(pid);
return environment ? linuxDataRoots(environment) : [];
}
function linuxDataRoots(environment: { HOME?: string; XDG_CONFIG_HOME?: string }): string[] {
const base =
environment.XDG_CONFIG_HOME ||
(environment.HOME ? path.join(environment.HOME, '.config') : null);
return base ? [path.join(base, 'QQ')] : [];
}
function readProcessEnvironment(pid: number): { HOME?: string; XDG_CONFIG_HOME?: string } | null {
let raw: string;
try {
raw = readFileSync(`/proc/${pid}/environ`, 'utf8');
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
return null;
}
throw error;
}
const environment: { HOME?: string; XDG_CONFIG_HOME?: string } = {};
for (const entry of raw.split('\0')) {
const separator = entry.indexOf('=');
if (separator <= 0) {
continue;
}
const name = entry.slice(0, separator);
if (name === 'HOME' || name === 'XDG_CONFIG_HOME') {
environment[name] = entry.slice(separator + 1);
}
}
return environment;
}
/** Both Linux layouts occur in QQ installations; the primary takes precedence. */
export function loginDbPaths(root: string): string[] {
if (process.platform === 'win32') {
return [path.join(root, 'nt_qq', 'global', ...LOGIN_DB_SEGMENTS)];
}
return [
path.join(root, 'global', ...LOGIN_DB_SEGMENTS),
path.join(root, 'nt_qq', 'global', ...LOGIN_DB_SEGMENTS),
];
}
export function ntMsgDbPath(root: string, account: { uin: string; uid: string }): string {
if (process.platform === 'win32') {
return path.join(root, account.uin, 'nt_qq', 'nt_db', 'nt_msg.db');
}
return path.join(root, accountDirName(account.uid), 'nt_db', 'nt_msg.db');
}
export function accountDirName(uid: string): string {
const digest = createHash('md5').update(uid, 'utf8').digest('hex');
return `nt_qq_${createHash('md5').update(`${digest}nt_kernel`, 'utf8').digest('hex')}`;
}
function windowsDataRoots(): string[] {
const configured = tencentFilesRootFromUserDataInfo();
return [configured ?? path.join(homedir(), 'Documents', 'Tencent Files')];
}
export function tencentFilesRootFromUserDataInfo(home = homedir()): string | null {
const ini = path.join(
path.dirname(home),
'Public',
'Documents',
'Tencent',
'QQ',
'UserDataInfo.ini',
);
let text: string;
try {
text = readFileSync(ini, 'utf8');
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
return null;
}
throw error;
}
let inDataSet = false;
for (const raw of text.split(/\r?\n/)) {
const line = raw.trim();
if (line.startsWith('[') && line.endsWith(']')) {
inDataSet = line.toLowerCase() === '[userdataset]';
continue;
}
if (!inDataSet) {
continue;
}
const separator = line.indexOf('=');
if (
separator === -1 ||
line.slice(0, separator).trim().toLowerCase() !== 'userdatasavepath'
) {
continue;
}
const value = line.slice(separator + 1).trim();
if (value.length === 0) {
return null;
}
// The ini always holds Windows paths, so resolve them with the win32
// flavor wherever this runs.
return path.win32.basename(value).toLowerCase() === 'tencent files'
? value
: path.win32.join(value, 'Tencent Files');
}
return null;
}

View File

@@ -0,0 +1,461 @@
/**
* SQLCipher v4 page decryption for QQ NT's local databases.
*
* QQ NT stores every database under `nt_db/` as a SQLCipher v4 stream behind a
* 1024-byte client header:
*
* [ 1024-byte client header ][ page 1 ][ page 2 ] ...
* ^ KDF salt = first 16 bytes of page 1
*
* Each page ends with `IV (16 bytes) || page HMAC`, rounded up to the AES block
* size; the page size is 4096 on every database QQ writes. Page 1's ciphertext
* starts after its 16-byte salt, which replaces the plaintext "SQLite format 3"
* magic — so the decrypted body of page 1 starts at page offset 16 and can never
* contain that magic. A candidate key is therefore confirmed by recomputing the
* page HMAC over the *ciphertext*, which is independent of the AES pass.
*
* The page-HMAC and KDF-HMAC algorithms are not fixed across client builds, so
* they are probed per database (12 combinations) instead of assumed.
*/
import { createDecipheriv, createHmac, pbkdf2Sync } from 'node:crypto';
/** QQ NT prepends this many bytes before the SQLCipher stream. */
export const DATABASE_HEADER_SIZE = 1024;
const PAGE_SIZE = 4096;
const SALT_SIZE = 16;
const IV_SIZE = 16;
const KEY_SIZE = 32;
/** SQLCipher v4 derives the AES key with this many PBKDF2 iterations. */
const KDF_ITERATIONS = 4000;
/** The per-page HMAC key uses a fast derivation over the page salt. */
const HMAC_KEY_ITERATIONS = 2;
/** SQLCipher's HMAC salt is the page salt XOR this mask. */
const HMAC_SALT_MASK = 0x3a;
const WAL_HEADER_SIZE = 32;
const WAL_FRAME_HEADER_SIZE = 24;
const SQLITE_MAGIC = Buffer.from('SQLite format 3\0', 'latin1');
export type PageHmacAlgorithm = 'none' | 'sha1' | 'sha256' | 'sha512';
export type KdfHmacAlgorithm = 'sha1' | 'sha256' | 'sha512';
/** One SQLCipher algorithm pair, as probed against a database's page 1. */
export interface SqlcipherAlgorithm {
pageHmac: PageHmacAlgorithm;
kdfHmac: KdfHmacAlgorithm;
}
/** Every pair to probe, in order: `cipher_use_hmac = OFF` first, then each digest. */
const PAGE_HMAC_ALGORITHMS: readonly PageHmacAlgorithm[] = ['none', 'sha1', 'sha256', 'sha512'];
const KDF_HMAC_ALGORITHMS: readonly KdfHmacAlgorithm[] = ['sha1', 'sha256', 'sha512'];
const PAGE_HMAC_DIGEST_BYTES: Record<PageHmacAlgorithm, number> = {
none: 0,
sha1: 20,
sha256: 32,
sha512: 64,
};
/** A database image decrypted from disk, with its `-wal` frames folded in. */
export interface DecryptedDatabase {
/** A self-contained plaintext SQLite image (rollback-journal mode). */
image: Buffer;
/** Frames folded in from the `-wal` sidecar, 0 when there was nothing to merge. */
walFrames: number;
}
/**
* Probe the algorithm pair of an encrypted database.
*
* Returns null when the page-1 HMAC matches no combination under `passphrase`,
* which means either the passphrase or the file layout is not what we expect.
*/
export function detectAlgorithm(image: Buffer, passphrase: string): SqlcipherAlgorithm | null {
const pageOne = readPageOne(image);
if (!pageOne) {
return null;
}
const salt = pageOne.subarray(0, SALT_SIZE);
for (const pageHmac of PAGE_HMAC_ALGORITHMS) {
for (const kdfHmac of KDF_HMAC_ALGORITHMS) {
const algorithm: SqlcipherAlgorithm = { pageHmac, kdfHmac };
const key = deriveKey(passphrase, salt, kdfHmac);
if (verifyPageOne(pageOne, key, algorithm)) {
return algorithm;
}
}
}
return null;
}
/**
* Decrypt a whole database and fold in the `-wal` sidecar when there is one.
*
* QQ keeps a long-lived WAL, so everything committed since the last checkpoint
* — including an account that just signed in — lives only in the sidecar.
* Returns null when the image cannot be decrypted.
*/
export function decryptDatabase(
image: Buffer,
wal: Buffer | null,
passphrase: string,
algorithm: SqlcipherAlgorithm,
): DecryptedDatabase | null {
const pageOne = readPageOne(image);
if (!pageOne) {
return null;
}
const key = deriveKey(passphrase, pageOne.subarray(0, SALT_SIZE), algorithm.kdfHmac);
const base = decryptPages(image, key, algorithm);
if (!base) {
return null;
}
const merged = applyWal(base, wal, key, algorithm);
normalizeImage(merged.image);
return merged;
}
/** Page 1 as stored, or null when the file is too short to hold a header + page 1. */
function readPageOne(image: Buffer): Buffer | null {
if (image.length < DATABASE_HEADER_SIZE + PAGE_SIZE) {
return null;
}
return image.subarray(DATABASE_HEADER_SIZE, DATABASE_HEADER_SIZE + PAGE_SIZE);
}
/** Per-page reserve = IV + page HMAC digest, rounded up to the AES block size. */
function reserveBytes(algorithm: SqlcipherAlgorithm): number {
const digestBytes = PAGE_HMAC_DIGEST_BYTES[algorithm.pageHmac];
return Math.ceil((IV_SIZE + digestBytes) / 16) * 16;
}
function deriveKey(passphrase: string, salt: Buffer, kdfHmac: KdfHmacAlgorithm): Buffer {
return pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, KEY_SIZE, kdfHmac);
}
/**
* Confirm a candidate key against page 1.
*
* With the page HMAC enabled the check runs over the stored ciphertext, exactly
* like SQLCipher's own verification. With HMAC off there is nothing to verify on
* the ciphertext, so page 1 is decrypted and the SQLite header fields that live
* past the salt-occupied first 16 bytes are checked instead.
*/
function verifyPageOne(pageOne: Buffer, key: Buffer, algorithm: SqlcipherAlgorithm): boolean {
const reserve = reserveBytes(algorithm);
const digestBytes = PAGE_HMAC_DIGEST_BYTES[algorithm.pageHmac];
if (digestBytes === 0) {
const body = decryptPageBody(pageOne, key, SALT_SIZE, reserve);
return body !== null && hasSqliteHeaderFields(body);
}
const hmacSalt = Buffer.alloc(SALT_SIZE);
for (let index = 0; index < SALT_SIZE; index++) {
hmacSalt[index] = pageOne[index] ^ HMAC_SALT_MASK;
}
const hmacKey = pbkdf2Sync(key, hmacSalt, HMAC_KEY_ITERATIONS, KEY_SIZE, algorithm.kdfHmac);
const bodyEnd = PAGE_SIZE - reserve;
const pageNumber = Buffer.alloc(4);
pageNumber.writeUInt32LE(1);
const input = Buffer.concat([
pageOne.subarray(SALT_SIZE, bodyEnd),
pageOne.subarray(bodyEnd, bodyEnd + IV_SIZE),
pageNumber,
]);
const computed = createHmac(algorithm.pageHmac, hmacKey).update(input).digest();
const stored = pageOne.subarray(bodyEnd + IV_SIZE, bodyEnd + IV_SIZE + digestBytes);
return equalsBytes(computed, stored);
}
/** The decrypted page-1 body starts at file offset 16 (the salt replaces 0..16). */
function hasSqliteHeaderFields(body: Buffer): boolean {
if (body.length < 8) {
return false;
}
const pageSize = body.readUInt16BE(0);
const pageSizeOk = pageSize === 1 || (pageSize >= 512 && (pageSize & (pageSize - 1)) === 0);
return pageSizeOk && body[5] === 64 && body[6] === 32 && body[7] === 32;
}
function equalsBytes(left: Buffer, right: Buffer): boolean {
if (left.length !== right.length) {
return false;
}
let diff = 0;
for (let index = 0; index < left.length; index++) {
diff |= left[index]! ^ right[index]!;
}
return diff === 0;
}
/**
* Decrypt every page of the main file, in place on a fresh buffer.
*
* `skip` drops the salt prefix of page 1; the reserve region of each page is
* left zeroed, which is how SQLCipher lays the plaintext out.
*/
function decryptPages(image: Buffer, key: Buffer, algorithm: SqlcipherAlgorithm): Buffer | null {
const stream = image.subarray(DATABASE_HEADER_SIZE);
const pageCount = Math.floor(stream.length / PAGE_SIZE);
if (pageCount === 0) {
return null;
}
const reserve = reserveBytes(algorithm);
const plain = Buffer.alloc(pageCount * PAGE_SIZE);
for (let index = 0; index < pageCount; index++) {
const pageNumber = index + 1;
const page = stream.subarray(index * PAGE_SIZE, (index + 1) * PAGE_SIZE);
const body = decryptPageBody(page, key, pageNumber === 1 ? SALT_SIZE : 0, reserve);
if (body === null) {
return null;
}
writePlaintextPage(plain, index * PAGE_SIZE, pageNumber, body);
}
return plain;
}
/** Decrypt one page body, or null when the page cannot hold an IV + digest. */
function decryptPageBody(page: Buffer, key: Buffer, skip: number, reserve: number): Buffer | null {
const cipherLength = PAGE_SIZE - skip - reserve;
if (cipherLength <= 0) {
return null;
}
const ciphertext = page.subarray(skip, skip + cipherLength);
const iv = page.subarray(skip + cipherLength, skip + cipherLength + IV_SIZE);
const decipher = createDecipheriv('aes-256-cbc', key, iv);
decipher.setAutoPadding(false);
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
}
/**
* Write one decrypted page into the plaintext image.
*
* Page 1 is special in both the main file and the WAL: its first 16 on-disk
* bytes hold the KDF salt in place of SQLite's magic, so the magic and the
* page-size field have to be restored. Every other page's body starts at offset
* 0 of the page.
*/
function writePlaintextPage(image: Buffer, offset: number, pageNumber: number, body: Buffer): void {
if (pageNumber !== 1) {
body.copy(image, offset, 0, Math.min(body.length, PAGE_SIZE));
return;
}
SQLITE_MAGIC.copy(image, offset);
body.copy(image, offset + SALT_SIZE, 0, Math.min(body.length, PAGE_SIZE - SALT_SIZE));
image.writeUInt16BE(PAGE_SIZE, offset + 16);
}
/**
* Fold the `-wal` sidecar into a decrypted image and return the frame count.
*
* A WAL is not wrapped in SQLCipher's envelope the way the main file is: its
* 32-byte header and every 24-byte frame header stay plaintext, and each frame
* carries one encrypted page (page 1 keeping its salt prefix). SQLite's frame
* checksums are computed over the frames *as stored*, i.e. over the ciphertext,
* which is why the intact prefix is established before any decryption.
*
* Only frames up to the last commit are applied, and the database size recorded
* by that commit decides how many pages the merged image has — a torn tail from
* a running QQ therefore contributes nothing.
*/
function applyWal(
base: Buffer,
wal: Buffer | null,
key: Buffer,
algorithm: SqlcipherAlgorithm,
): DecryptedDatabase {
const log = wal === null ? null : parseWal(wal);
if (!log || log.frames.length === 0) {
return { image: base, walFrames: 0 };
}
let lastCommit = -1;
for (let index = 0; index < log.frames.length; index++) {
if (log.frames[index]!.commitSize !== 0) {
lastCommit = index;
}
}
if (lastCommit < 0) {
return { image: base, walFrames: 0 };
}
const pageCount = log.frames[lastCommit]!.commitSize;
const basePageCount = base.length / PAGE_SIZE;
// A commit can only grow the database by the pages its own log carries, so
// anything past that bound is a corrupt frame header rather than a size.
if (pageCount < 1 || pageCount > basePageCount + log.frames.length) {
return { image: base, walFrames: 0 };
}
const merged = Buffer.alloc(pageCount * PAGE_SIZE);
base.copy(merged, 0, 0, Math.min(base.length, merged.length));
const reserve = reserveBytes(algorithm);
for (let index = 0; index <= lastCommit; index++) {
const frame = log.frames[index]!;
if (frame.pageNumber === 0 || frame.pageNumber > pageCount) {
continue;
}
const page = wal!.subarray(frame.offset, frame.offset + PAGE_SIZE);
const body = decryptPageBody(page, key, frame.pageNumber === 1 ? SALT_SIZE : 0, reserve);
if (body === null) {
return { image: base, walFrames: 0 };
}
writePlaintextPage(merged, (frame.pageNumber - 1) * PAGE_SIZE, frame.pageNumber, body);
}
return { image: merged, walFrames: lastCommit + 1 };
}
interface WalFrame {
pageNumber: number;
/** Database size in pages recorded by a commit frame, 0 for a non-commit frame. */
commitSize: number;
/** Offset of the frame's page inside the `-wal` buffer. */
offset: number;
}
interface WalLog {
frames: WalFrame[];
littleEndian: boolean;
}
/**
* Validate a `-wal` buffer and collect its intact frames.
*
* Validation stops at the first frame whose checksum does not continue the
* chain, mirroring SQLite's own recovery: everything after that frame is either
* half-written or belongs to an aborted transaction.
*/
function parseWal(wal: Buffer): WalLog | null {
if (wal.length < WAL_HEADER_SIZE + WAL_FRAME_HEADER_SIZE + PAGE_SIZE) {
return null;
}
const magic = wal.readUInt32BE(0);
const littleEndian = magic === 0x377f0682 ? true : magic === 0x377f0683 ? false : null;
if (littleEndian === null || wal.readUInt32BE(8) !== PAGE_SIZE) {
return null;
}
// The header checksum covers its first 24 bytes; magic and page size are
// excluded from the checksummed range by that length.
const header = walChecksum([0, 0], [wal.subarray(0, WAL_HEADER_SIZE - 8)], littleEndian);
if (header[0] !== wal.readUInt32BE(24) || header[1] !== wal.readUInt32BE(28)) {
return null;
}
const frameSize = WAL_FRAME_HEADER_SIZE + PAGE_SIZE;
const frames: WalFrame[] = [];
let running = header;
for (let offset = WAL_HEADER_SIZE; offset + frameSize <= wal.length; offset += frameSize) {
const frameHeader = wal.subarray(offset, offset + WAL_FRAME_HEADER_SIZE);
const page = wal.subarray(offset + WAL_FRAME_HEADER_SIZE, offset + frameSize);
running = walChecksum(running, [frameHeader.subarray(0, 8), page], littleEndian);
if (
running[0] !== frameHeader.readUInt32BE(16) ||
running[1] !== frameHeader.readUInt32BE(20)
) {
break;
}
frames.push({
pageNumber: frameHeader.readUInt32BE(0),
commitSize: frameHeader.readUInt32BE(4),
offset: offset + WAL_FRAME_HEADER_SIZE,
});
}
return { frames, littleEndian };
}
/**
* SQLite's rolling WAL checksum: two 32-bit accumulators advanced over 8-byte
* word pairs. The byte order is fixed by the WAL magic (`0x377f0682` =
* little-endian words, `0x377f0683` = big-endian) and is unrelated to the
* host's byte order.
*
* Every chunk fed in here is a multiple of 8 bytes: the header contributes 24
* bytes, a frame its first 8 header bytes plus a whole page.
*/
function walChecksum(
seed: [number, number],
chunks: readonly Buffer[],
littleEndian: boolean,
): [number, number] {
let first = seed[0];
let second = seed[1];
for (const chunk of chunks) {
for (let offset = 0; offset + 8 <= chunk.length; offset += 8) {
const high = littleEndian ? chunk.readUInt32LE(offset) : chunk.readUInt32BE(offset);
const low = littleEndian
? chunk.readUInt32LE(offset + 4)
: chunk.readUInt32BE(offset + 4);
first = (first + high + second) >>> 0;
second = (second + low + first) >>> 0;
}
}
return [first, second];
}
/**
* Make the assembled image self-consistent before it is handed to SQLite.
*
* The merge can add or remove pages relative to the base image, and the header
* fields that describe the database are only trusted while page 1's change
* counter and version-valid-for agree. The write/read version bytes are reset
* to the legacy journal so the image can be opened read-only without needing a
* `-wal`/`-shm` pair next to it.
*/
function normalizeImage(image: Buffer): void {
const pageCount = image.length / PAGE_SIZE;
const changeCounter = image.readUInt32BE(24);
image[18] = 1;
image[19] = 1;
image.writeUInt32BE(pageCount, 28);
image.writeUInt32BE(changeCounter, 92);
}

View File

@@ -560,7 +560,7 @@ export class QqHookClient extends EventEmitter {
private controlWriteChain: Promise<unknown> = Promise.resolve();
private closed = false;
private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n };
private loginWaiters: Deferred<QqHookLoginState>[] = [];
private readonly loginWaiters = new Set<Deferred<QqHookLoginState>>();
constructor(
pid: number,
@@ -612,13 +612,22 @@ export class QqHookClient extends EventEmitter {
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
await this.connect();
if (this.closed) {
throw new Error('qq_hook client is closed');
}
if (this.loginState.loggedIn) {
return this.getLoginState();
}
const deferred = createDeferred<QqHookLoginState>();
this.loginWaiters.push(deferred);
return withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
this.loginWaiters.add(deferred);
try {
return await withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
} finally {
this.loginWaiters.delete(deferred);
}
}
static controlPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string {
@@ -735,6 +744,21 @@ export class QqHookClient extends EventEmitter {
return { control, recv: recvInfo };
}
send(
cmd: string,
body: Buffer | Uint8Array | string | null | undefined,
options?: QqHookSendOptions & { wantReply?: true },
): Promise<QqHookSendReply>;
send(
cmd: string,
body: Buffer | Uint8Array | string | null | undefined,
options: QqHookSendOptions & { wantReply: false },
): Promise<{ requestId: number }>;
send(
cmd: string,
body: Buffer | Uint8Array | string | null | undefined,
options?: QqHookSendOptions,
): Promise<QqHookSendReply | { requestId: number }>;
async send(
cmd: string,
body: Buffer | Uint8Array | string | null | undefined,
@@ -849,9 +873,7 @@ export class QqHookClient extends EventEmitter {
body: Buffer | Uint8Array | string | null | undefined,
options: Omit<QqHookSendOptions, 'wantReply'> = {},
): Promise<{ requestId: number }> {
return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{
requestId: number;
}>;
return this.send(cmd, body, { ...options, wantReply: false });
}
async sendAndWait(
@@ -859,7 +881,7 @@ export class QqHookClient extends EventEmitter {
body: Buffer | Uint8Array | string | null | undefined,
options: Omit<QqHookSendOptions, 'wantReply'> = {},
): Promise<QqHookSendReply> {
return this.send(cmd, body, { ...options, wantReply: true }) as Promise<QqHookSendReply>;
return this.send(cmd, body, { ...options, wantReply: true });
}
async sendMany(
@@ -971,12 +993,11 @@ export class QqHookClient extends EventEmitter {
}
private rejectLoginWaiters(error: Error): void {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) {
for (const waiter of this.loginWaiters) {
waiter.reject(error);
}
this.loginWaiters.clear();
}
private rejectControlPending(error: Error): void {
@@ -1266,12 +1287,11 @@ export class QqHookClient extends EventEmitter {
this.emit('loginState', next);
if (next.loggedIn) {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) {
for (const waiter of this.loginWaiters) {
waiter.resolve({ ...next });
}
this.loginWaiters.clear();
}
});
}

View File

@@ -1,294 +0,0 @@
import { createLogger } from '@snowluma/common/logger';
import { exec } from 'child_process';
import http from 'http';
import https from 'https';
import { promisify } from 'util';
const execAsync = promisify(exec);
const log = createLogger('LoginProbe');
const probeNotes = new Map<number, string>();
function noteProbe(pid: number, result: string, ports: number, processes: number | null): void {
const processText = processes === null ? '' : ` processes=${processes}`;
const message = `login probe: PID=${pid} result=${result} ports=${ports}${processText}`;
if (probeNotes.get(pid) === message) {
return;
}
probeNotes.set(pid, message);
log.info(message);
}
const CONNECTION_TIMEOUT_MS = 500;
const COMMAND_TIMEOUT_MS = 1500;
const OVERALL_PROBE_TIMEOUT_MS = 5000;
const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as const };
// QQ's Ptlogin quick-login ports plus its main process mean a single
// logged-in client surfaces roughly this many processes. When no usable
// probe port is found, a count BELOW this implies the target PID is still at
// the login screen; AT/ABOVE it the environment is ambiguous (multiple or
// unrelated `qq` processes), so we fall through to deep-link probing rather
// than guess "logged out".
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
export interface QqPortLoginInfo {
port: number;
uin: string;
uid?: string;
nickName?: string;
/** The local QQ endpoint exposed an account identity. This does not prove
* the native protocol session is ready to send or receive packets. */
identityKnown: boolean;
}
/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the
* probe reads are modelled; QQ sends more but they're irrelevant here. */
interface PtloginUin {
uin?: string | number;
account?: string | number;
nickname?: string;
}
/**
* One `pt_get_uins` call. Returns the parsed account array (possibly empty —
* an EMPTY array is a real answer: "0 accounts", NOT an error) or `null` when
* the port could not be reached / the body was not a usable pt_get_uins
* response (connect refused, timeout, unparseable). Callers MUST distinguish
* the two: `[]` feeds the logged-in/out decision, `null` means "network
* problem, no answer" and should fall through to the deep-link fallback.
*/
async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin[] | null> {
return new Promise((resolve) => {
const protocol = useHttps ? 'https' : 'http';
const url = `${protocol}://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
const headers = {
Host: 'localhost.ptlogin2.qq.com',
Referer: 'https://xui.ptlogin2.qq.com/',
Cookie: 'pt_local_token=0',
};
const handleResponse = (res: http.IncomingMessage) => {
let text = '';
res.on('data', (chunk) => {
text += chunk.toString();
});
res.on('end', () => {
try {
const inner = text.split('[')[1].split(']')[0];
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
resolve(data);
} catch {
resolve(null);
}
});
};
const req = useHttps
? https.get(
url,
{ headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false },
handleResponse,
)
: http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse);
req.on('error', () => resolve(null));
req.on('timeout', () => {
req.destroy();
resolve(null);
});
});
}
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
const useHttps = port % 2 !== 0;
const res1 = await fetchPtlogin(port, useHttps);
const res2 = await fetchPtlogin(port, useHttps);
if (res1 === null && res2 === null) {
return 'fallback';
}
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
if (target.length === 1) {
const account = target[0];
return {
port,
uin: String(account.uin || account.account || ''),
nickName: account.nickname || '',
identityKnown: true,
};
}
return 'fallback';
}
async function getQqProcessCount(): Promise<number> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync(
'tasklist /fi "imagename eq QQ.exe" /nh',
EXEC_OPTIONS,
);
return stdout
.toLowerCase()
.split('\n')
.filter((line) => line.includes('qq.exe')).length;
} else {
const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS);
return parseInt(stdout.trim(), 10) || 0;
}
} catch {
// On failure report the ambiguous threshold so we never falsely
// conclude "logged out".
return LOGGED_OUT_PROCESS_COUNT_MAX;
}
}
async function getProcessPorts(pid: number): Promise<number[] | null> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
const parts = line.trim().split(/\s+/);
if (parts.length < 5) {
continue;
}
const owningPid = parts[parts.length - 1];
if (owningPid !== String(pid)) {
continue;
}
const localAddr = parts[1];
const portMatch = localAddr.match(/:(\d+)$/);
if (!portMatch) {
continue;
}
ports.add(Number(portMatch[1]));
}
return Array.from(ports);
} else {
const { stdout } = await execAsync('ss -tlnp', EXEC_OPTIONS);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) {
continue;
}
const match = line.match(/:(\d+)\s/);
if (match) {
ports.add(Number(match[1]));
}
}
return Array.from(ports);
}
} catch {
return null;
}
}
async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo | null> {
const ports = await getProcessPorts(pid);
if (ports === null) {
noteProbe(pid, 'unavailable', 0, null);
return null;
}
if (ports.length === 0) {
const totalPids = await getQqProcessCount();
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
noteProbe(pid, 'no-ports', 0, totalPids);
return { port: 0, uin: '', identityKnown: false };
}
noteProbe(pid, 'inconclusive', 0, totalPids);
return null;
}
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
const matchedOddPorts = ports.filter((p) => ODD_PT_PORTS.includes(p));
const matchedEvenPorts = ports.filter((p) => EVEN_PT_PORTS.includes(p));
let ptPortsToTry: number[] = [];
if (matchedOddPorts.length > 0) {
ptPortsToTry = matchedOddPorts;
} else if (matchedEvenPorts.length > 0) {
ptPortsToTry = matchedEvenPorts;
}
if (ptPortsToTry.length > 0) {
for (const port of ptPortsToTry) {
const ptResult = await tryPtloginMethod(port);
if (ptResult !== 'fallback') {
return ptResult;
}
}
} else {
const totalPids = await getQqProcessCount();
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
noteProbe(pid, 'no-ports', ports.length, totalPids);
return {
port: ports[0] || 0,
uin: '',
identityKnown: false,
};
}
noteProbe(pid, 'inconclusive', ports.length, totalPids);
return null;
}
// Background discovery must remain passive. Interactive application
// endpoints are deliberately excluded from automatic probing.
noteProbe(pid, 'no-match', ptPortsToTry.length, null);
return null;
}
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
let timer: ReturnType<typeof setTimeout> | undefined;
let timedOut = false;
const timeout = new Promise<null>((resolve) => {
timer = setTimeout(() => {
timedOut = true;
resolve(null);
}, OVERALL_PROBE_TIMEOUT_MS);
});
try {
const result = await Promise.race([probeQqLoginInfoInternal(pid), timeout]);
if (timedOut) {
log.warn('login check timed out: PID=%d', pid);
}
return result;
} finally {
if (timer) {
clearTimeout(timer);
}
}
}

View File

@@ -0,0 +1,121 @@
import { getNativeHookAddon, getNativeHookLoadError } from './injector';
export interface IntegrityReadError {
status: 'error';
operation: string;
code: number;
}
export interface NativeRuntimeIntegrity {
pid: number;
executablePath: string | null;
process: { status: 'ok'; rid: number } | IntegrityReadError;
file:
| {
status: 'ok';
label: { rid: number; inherited: boolean; policy: number } | null;
}
| IntegrityReadError;
}
export type RuntimeIntegrity =
| { status: 'unsupported' }
| { status: 'unavailable'; error: string }
| ({ status: 'available' } & NativeRuntimeIntegrity);
/** File labels can change after startup; only the actual token decides the warning. */
export function hasLowProcessIntegrity(integrity: RuntimeIntegrity): boolean {
return (
integrity.status === 'available' &&
integrity.process.status === 'ok' &&
integrity.process.rid < 8192
);
}
function record(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function uint32(value: unknown): value is number {
return (
typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 0xffff_ffff
);
}
function readError(value: Record<string, unknown>): boolean {
return value.status === 'error' && typeof value.operation === 'string' && uint32(value.code);
}
function isNativeRuntimeIntegrity(value: unknown): value is NativeRuntimeIntegrity {
if (
!record(value) ||
value.pid !== process.pid ||
!(typeof value.executablePath === 'string' || value.executablePath === null) ||
!record(value.process) ||
!record(value.file)
) {
return false;
}
if (!(
readError(value.process) ||
(value.process.status === 'ok' && uint32(value.process.rid))
)) {
return false;
}
const file = value.file;
return (
readError(file) ||
(file.status === 'ok' &&
(file.label === null ||
(record(file.label) &&
uint32(file.label.rid) &&
typeof file.label.inherited === 'boolean' &&
uint32(file.label.policy))))
);
}
let cached: Promise<RuntimeIntegrity> | undefined;
/** One startup snapshot, shared by the startup log and the WebUI warning. */
export function getRuntimeIntegrity(): Promise<RuntimeIntegrity> {
return (cached ??= readRuntimeIntegrity());
}
async function readRuntimeIntegrity(): Promise<RuntimeIntegrity> {
if (process.platform !== 'win32') {
return { status: 'unsupported' };
}
try {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? '原生组件不可用');
}
if (typeof addon.getRuntimeIntegrityAsync !== 'function') {
throw new Error('当前原生组件不支持完整性诊断,请更新原生组件');
}
const result = await addon.getRuntimeIntegrityAsync();
if (!isNativeRuntimeIntegrity(result)) {
throw new Error('原生完整性诊断返回了无效数据');
}
return {
status: 'available',
pid: result.pid,
executablePath: result.executablePath,
process: result.process,
file: result.file,
};
} catch (error) {
return {
status: 'unavailable',
error: error instanceof Error ? error.message : String(error),
};
}
}

View File

@@ -3,6 +3,12 @@ import type { HookProcessBaseInfo } from './injector';
export type HookProcessStatus =
'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected';
/** Account the QQ client is signed in as, as reported by its local data. */
export interface HookProcessAccount {
uin: string;
nickname: string;
}
/** Public-facing snapshot of a per-PID HookSession. */
export interface HookProcessInfo extends HookProcessBaseInfo {
injected: boolean;
@@ -12,4 +18,6 @@ export interface HookProcessInfo extends HookProcessBaseInfo {
status: HookProcessStatus;
error: string;
method: string;
/** Locally detected identity; null means unknown, not necessarily signed out. */
account: HookProcessAccount | null;
}

View File

@@ -5,6 +5,7 @@ import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
import type { AccountLoginState } from '../src/qq-account';
// Regression cover for the WebUI SSE wiring: HookManager must call its
// optional `onSessionsChanged` callback every time the observable set of
@@ -25,11 +26,18 @@ interface Harness {
clientFactory: ReturnType<typeof vi.fn>;
}
function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness {
function makeManager(
opts: {
processes?: number[];
livePipes?: number[];
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
accountReprobeIntervalMs?: number;
} = {},
): Harness {
let pids = opts.processes ?? [];
let live = new Set<number>(opts.livePipes ?? []);
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
@@ -60,11 +68,16 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
inject: vi.fn(async () => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(async () => {}),
},
makeClient: clientFactory,
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: opts.detectAccounts ?? (async () => []),
accountReprobeIntervalMs: opts.accountReprobeIntervalMs,
onSessionsChanged,
});
return {
@@ -152,7 +165,7 @@ describe('HookManager.onSessionsChanged', () => {
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
const pids = [4242];
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(),
intervalMs: 60_000,
});
@@ -164,11 +177,11 @@ describe('HookManager.onSessionsChanged', () => {
} as unknown as BridgeManagerSink,
pipeWatcher,
injector: {
inject: vi.fn(() => ({
inject: vi.fn(async () => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
unload: vi.fn(async () => {}),
},
makeClient: vi.fn(() => {
const c = new EventEmitter() as any;
@@ -183,7 +196,8 @@ describe('HookManager.onSessionsChanged', () => {
return c;
}),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: async () => [],
// onSessionsChanged deliberately omitted
});
await pipeWatcher.start();
@@ -196,6 +210,202 @@ describe('HookManager.onSessionsChanged', () => {
});
});
describe('HookManager periodic account re-probe', () => {
it('shares one account probe between watcher ticks and concurrent snapshots', async () => {
const probe = Promise.withResolvers<AccountLoginState[]>();
const detectAccounts = vi.fn(() => probe.promise);
const ctx = makeManager({ processes: [4242], detectAccounts });
try {
await ctx.pipeWatcher.start();
const first = ctx.manager.listProcesses();
const second = ctx.manager.listProcesses();
await flush();
expect(detectAccounts).toHaveBeenCalledTimes(1);
probe.resolve([{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 }]);
const snapshots = await Promise.all([first, second]);
expect(snapshots.map((list) => list[0]!.account)).toEqual([
{ uin: '10001', nickname: 'Alice' },
{ uin: '10001', nickname: 'Alice' },
]);
} finally {
probe.resolve([]);
ctx.manager.dispose();
}
});
it('keeps all process labels when an operation reads just one process', async () => {
const accounts: AccountLoginState[] = [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 5151 },
];
const detectAccounts = vi.fn(async (pids: readonly number[]) =>
accounts.filter((account) => pids.includes(account.pid!)),
);
const ctx = makeManager({ processes: [4242, 5151], detectAccounts });
try {
await ctx.manager.listProcesses();
const baseline = detectAccounts.mock.calls.length;
expect((await ctx.manager.refreshProcess(4242)).account?.uin).toBe('10001');
ctx.onSessionsChanged.mockClear();
await ctx.pipeWatcher.tickNow();
await flush();
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
expect((await ctx.manager.listProcesses())[1]!.account?.uin).toBe('10002');
} finally {
ctx.manager.dispose();
}
});
it('does not publish a late account result for an exited process', async () => {
const probe = Promise.withResolvers<AccountLoginState[]>();
const ctx = makeManager({ processes: [4242], detectAccounts: () => probe.promise });
try {
await ctx.pipeWatcher.start();
const snapshot = ctx.manager.listProcesses();
await flush();
ctx.setProcesses([]);
await ctx.pipeWatcher.tickNow();
await flush();
ctx.onSessionsChanged.mockClear();
probe.resolve([{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 }]);
await flush();
expect(await snapshot).toEqual([]);
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
expect(await ctx.manager.listProcesses()).toEqual([]);
} finally {
probe.resolve([]);
ctx.manager.dispose();
}
});
// A login can happen with no hook edge at all (QQ signs in after SnowLuma
// started, or before the hook was injected), so no session status changes
// and nothing pushes a fresh processes snapshot. These cover the watcher
// pass that re-reads the account labels and invalidates when they move.
it('publishes when a process gains an account label', async () => {
let accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: null }];
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => accounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
// QQ finished signing in: the account's nt_msg.db is now held by 4242.
accounts = [{ uin: '1', uid: 'u1', nickname: 'A', pid: 4242 }];
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
const list = await ctx.manager.listProcesses();
expect(list[0]!.account).toEqual({ uin: '1', nickname: 'A' });
ctx.manager.dispose();
});
it('stays silent while the labels are unchanged', async () => {
const accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: 4242 }];
const detectAccounts = vi.fn(async () => accounts);
const ctx = makeManager({
processes: [4242],
detectAccounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
// Detection did run again — it just had nothing new to report.
expect(detectAccounts.mock.calls.length).toBeGreaterThan(1);
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
ctx.manager.dispose();
});
it('ignores accounts that are not signed in on any process', async () => {
let accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: null }];
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => accounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
// Only the cached-account set changed (another account signed in on
// another machine/user); no process label moved.
accounts = [
{ uin: '1', uid: 'u1', nickname: 'A', pid: null },
{ uin: '2', uid: 'u2', nickname: 'B', pid: null },
];
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
ctx.manager.dispose();
});
it('throttles the probe to the configured interval', async () => {
const detectAccounts = vi.fn(async () => [] as AccountLoginState[]);
const ctx = makeManager({
processes: [4242],
detectAccounts,
accountReprobeIntervalMs: 60_000,
});
await ctx.pipeWatcher.start();
await flush();
const baseline = detectAccounts.mock.calls.length;
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
await flush();
expect(detectAccounts.mock.calls.length).toBe(baseline);
ctx.manager.dispose();
});
it('keeps working when detection fails, and reports the failure once', async () => {
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => {
throw new Error('login.db unreadable');
},
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
await flush();
await flush();
// Detection failing is not a label change, so nothing is published.
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
expect((await ctx.manager.listProcesses())[0]!.account).toBeNull();
ctx.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] });

View File

@@ -7,6 +7,7 @@ import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { HookInjectResult, ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { AccountLoginState } from '../src/qq-account';
import type { QqHookClient } from '../src/qq-hook-client';
import {
createLogger,
@@ -28,20 +29,21 @@ function makeManager(opts: {
autoLoadOnDiscovery?: boolean;
processes?: number[];
onSessionsChanged?: () => void;
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
inject?: (pid: number) => Promise<HookInjectResult>;
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
}) {
let pids = opts.processes ?? [];
const live = new Set<number>();
const inject = vi.fn(
opts.inject ??
(() => ({
(async () => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
);
const unload = vi.fn();
const unload = vi.fn(async () => {});
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
});
@@ -75,7 +77,9 @@ function makeManager(opts: {
makeClient,
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
onSessionsChanged: opts.onSessionsChanged,
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
// Detection reads QQ's own data directories; tests stay off the host.
detectAccounts: opts.detectAccounts ?? (async () => []),
});
return {
manager,
@@ -469,3 +473,41 @@ describe('shouldAutoLoadPid', () => {
expect(shouldAutoLoadPid(99999, log)).toBe(true);
});
});
describe('HookManager — signed-in account labelling', () => {
it('labels each process with the account detected on it', async () => {
const ctx = makeManager({
processes: [4242, 5151],
detectAccounts: async () => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: null },
],
});
try {
const list = await ctx.manager.listProcesses();
expect(list.map((info) => [info.pid, info.account])).toEqual([
[4242, { uin: '10001', nickname: 'Alice' }],
[5151, null],
]);
} finally {
ctx.manager.dispose();
}
});
it('leaves processes unlabelled when detection fails', async () => {
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => {
throw new Error('login.db unreadable');
},
});
try {
const list = await ctx.manager.listProcesses();
expect(list[0]!.account).toBeNull();
} finally {
ctx.manager.dispose();
}
});
});

View File

@@ -43,7 +43,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
const clients: FakeClient[] = [];
const pipeWatcher = new PipeWatcher({
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
listProcesses: async () => [{ pid: PID, name: 'qq', path: '' }],
listLivePipes: async () => new Set(liveSet),
intervalMs: 60_000, // manual ticks only
});
@@ -58,11 +58,11 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(() => ({
inject: vi.fn(async () => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
unload: vi.fn(async () => {}),
},
makeClient: () => {
const c = new FakeClient();
@@ -70,7 +70,8 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
return c as unknown as QqHookClient;
},
autoLoadOnDiscovery: true,
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
listProcesses: async () => [{ pid: PID, name: 'qq', path: '' }],
detectAccounts: async () => [],
});
// Initial discovery + first connect.

View File

@@ -15,7 +15,7 @@
// - at most one client is alive at any point
// - every prior client's EventEmitter listener count drops to 0 after teardown
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect, onTestFinished, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookSession } from '../src/hook-session';
import type { ManualMapHandle } from '../src/injector';
@@ -57,12 +57,13 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
let pipeLive = true;
const clients: FakeClient[] = [];
const session = new HookSession(61, {
detectLoginUin: async () => null,
injector: {
inject: vi.fn(() => ({
inject: vi.fn(async () => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
unload: vi.fn(async () => {}),
},
makeClient: () => {
const c = new FakeClient();
@@ -71,6 +72,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
},
pipeWatcher: { isPipeLive: () => pipeLive },
});
onTestFinished(() => session.dispose());
await session.load();
session.onPipeUp();
@@ -99,12 +101,13 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
let pipeLive = true;
const clients: FakeClient[] = [];
const session = new HookSession(61, {
detectLoginUin: async () => null,
injector: {
inject: vi.fn(() => ({
inject: vi.fn(async () => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
unload: vi.fn(async () => {}),
},
makeClient: () => {
const c = new FakeClient();
@@ -113,6 +116,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
},
pipeWatcher: { isPipeLive: () => pipeLive },
});
onTestFinished(() => session.dispose());
await session.load();
session.onPipeUp();

View File

@@ -8,7 +8,6 @@ import {
type QqHookClient,
type QqHookPacket,
} from '../src/qq-hook-client';
import type { QqPortLoginInfo } from '../src/qq-port-probe';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
@@ -104,7 +103,7 @@ function makeSession(
pipeLive?: boolean;
clientFailsConnect?: boolean;
onPacket?: PacketSink;
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
detectLoginUin?: (pid: number) => Promise<string | null>;
nativeReadyOnIdentityHint?: boolean;
identityHintFailures?: number;
} = {},
@@ -113,13 +112,12 @@ function makeSession(
let pipeLive = opts.pipeLive ?? false;
const clients: FakeClient[] = [];
const injector = {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
inject: vi.fn(async () => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(async () => {}),
};
// Default probe exposes no identity so the reconcile safety net is inert
// unless a test opts into a known account.
const probeLogin =
opts.probeLogin ?? (async () => ({ port: 0, uin: '', identityKnown: false }));
// Default detection exposes no account so the reconcile safety net is inert
// unless a test opts into a known one.
const detectLoginUin = opts.detectLoginUin ?? (async () => null);
const session = new HookSession(pid, {
injector,
@@ -136,7 +134,7 @@ function makeSession(
// Cast: FakeClient mirrors only the surface HookSession touches.
return c as unknown as QqHookClient;
},
probeLogin,
detectLoginUin,
pipeWatcher: { isPipeLive: () => pipeLive },
onPacket: opts.onPacket,
});
@@ -202,10 +200,10 @@ describe('HookSession — runtime TRACE', () => {
try {
const injector = {
inject: vi.fn(() => {
inject: vi.fn(async () => {
throw new Error('fixture inject failure');
}),
unload: vi.fn(),
unload: vi.fn(async () => {}),
};
const failedLoad = new HookSession(7103, {
injector,
@@ -250,11 +248,11 @@ describe('HookSession — runtime TRACE', () => {
const clients: FakeClient[] = [];
const session = new HookSession(7108, {
injector: {
inject: () => {
inject: async () => {
pipeLive = true;
throw new Error('component loading failed [COMPONENT_LOAD_FAILED]');
},
unload: () => undefined,
unload: async () => undefined,
},
makeClient: () => {
const client = new FakeClient();
@@ -453,8 +451,8 @@ describe('HookSession — load', () => {
},
);
const injector = {
inject: vi.fn(() => loading),
unload: vi.fn(),
inject: vi.fn(async () => loading),
unload: vi.fn(async () => {}),
};
const session = new HookSession(1234, {
injector,
@@ -476,10 +474,10 @@ describe('HookSession — load', () => {
it('inject failure → status error, error message captured', async () => {
const injector = {
inject: vi.fn(() => {
inject: vi.fn(async () => {
throw new Error('inject boom');
}),
unload: vi.fn(),
unload: vi.fn(async () => {}),
};
const session = new HookSession(1234, {
injector,
@@ -500,7 +498,7 @@ describe('HookSession — load', () => {
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
}),
unload: vi.fn(),
unload: vi.fn(async () => {}),
};
const session = new HookSession(1234, {
injector,
@@ -680,11 +678,11 @@ describe('HookSession — unload', () => {
const session = new HookSession(pid, {
injector: {
inject: vi.fn(() => ({
inject: vi.fn(async () => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(),
unload: vi.fn(async () => {}),
},
makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => pipeLive, tickNow },
@@ -701,6 +699,48 @@ describe('HookSession — unload', () => {
});
describe('HookSession — serialization', () => {
it('waits for native unload before starting a queued load', async () => {
const ctx = makeSession();
await ctx.session.load();
let finish!: () => void;
ctx.injector.unload.mockReturnValueOnce(
new Promise<void>((resolve) => {
finish = resolve;
}),
);
const unloading = ctx.session.unload();
const loading = ctx.session.load();
await flush();
expect(ctx.injector.unload).toHaveBeenCalledOnce();
expect(ctx.injector.inject).toHaveBeenCalledTimes(1);
expect(ctx.session.toInfo().injected).toBe(true);
finish();
await unloading;
await loading;
expect(ctx.injector.inject).toHaveBeenCalledTimes(2);
ctx.session.dispose();
});
it('retains the handle when native unload rejects so it can be retried', async () => {
const ctx = makeSession();
await ctx.session.load();
ctx.injector.unload.mockRejectedValueOnce(new Error('unload rejected'));
await expect(ctx.session.unload()).resolves.toMatchObject({
status: 'error',
error: 'unload rejected',
injected: true,
});
await expect(ctx.session.unload()).resolves.toMatchObject({
status: 'available',
injected: false,
});
expect(ctx.injector.unload).toHaveBeenNthCalledWith(2, ctx.session.pid, DUMMY_HANDLE);
ctx.session.dispose();
});
it('user mashing load → unload → load runs in order, end state consistent', async () => {
const ctx = makeSession({ pipeLive: false });
@@ -866,10 +906,10 @@ describe('HookSession — pipe-down must not clobber a settled error', () => {
it('onPipeDown after a failed load leaves the error status intact', async () => {
const injector = {
inject: vi.fn(() => {
inject: vi.fn(async () => {
throw new Error('inject boom');
}),
unload: vi.fn(),
unload: vi.fn(async () => {}),
};
const session = new HookSession(1234, {
injector,
@@ -1003,10 +1043,35 @@ describe('HookSession — packet forwarding', () => {
});
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
it('discards an identity read started before a pipe reconnect', async () => {
const detection = Promise.withResolvers<string | null>();
const ctx = makeSession({ pipeLive: true, detectLoginUin: () => detection.promise });
try {
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
const previous = ctx.currentClient();
previous.close();
await flush();
ctx.session.onPipeUp();
await flush();
const current = ctx.currentClient();
expect(current).not.toBe(previous);
detection.resolve('10001');
await flush();
expect(current.loginIdentityHints).toEqual([]);
expect(previous.loginIdentityHints).toEqual([]);
} finally {
detection.resolve(null);
ctx.session.dispose();
}
});
it('keeps the packet sender usable only after native readiness confirms the identity hint', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
detectLoginUin: async () => '10001',
nativeReadyOnIdentityHint: true,
});
let sender: PacketSender | undefined;
@@ -1033,12 +1098,12 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
]);
});
it('treats a port-probed account as an identity hint, not native login proof', async () => {
it('treats a locally detected account as an identity hint, not native login proof', async () => {
// Account identity does not prove request readiness. The bridge must wait
// for a login-state confirmation instead of synthesizing one.
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
detectLoginUin: async () => '10001',
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -1058,7 +1123,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
vi.useFakeTimers();
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
detectLoginUin: async () => '10001',
});
try {
@@ -1079,7 +1144,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
let uin = '10001';
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin, identityKnown: true }),
detectLoginUin: async () => uin,
});
try {
@@ -1104,7 +1169,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
vi.useFakeTimers();
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
detectLoginUin: async () => '10001',
identityHintFailures: 3,
});
@@ -1128,10 +1193,10 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
}
});
it('does not log in when the probe reports not-logged-in', async () => {
it('does not log in when no account is detected', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 0, uin: '', identityKnown: false }),
detectLoginUin: async () => null,
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -1144,10 +1209,10 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
expect(ctx.session.status).toBe('loaded');
});
it('ignores a probe with a non-real uin (0)', async () => {
it('ignores a detected account with a non-real uin (0)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '0', identityKnown: true }),
detectLoginUin: async () => '0',
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -1159,11 +1224,11 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
expect(loginSpy).not.toHaveBeenCalled();
});
it('tolerates a throwing probe (best-effort, no crash/login)', async () => {
it('tolerates a throwing detection (best-effort, no crash/login)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => {
throw new Error('port scan failed');
detectLoginUin: async () => {
throw new Error('account detection unavailable');
},
});
const loginSpy = vi.fn();
@@ -1177,14 +1242,14 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
expect(ctx.session.status).toBe('loaded');
});
it('detects a login that lands on a LATER interval probe', async () => {
it('detects a login that lands on a LATER interval check', async () => {
vi.useFakeTimers();
try {
let identityKnown = false;
let signedIn = false;
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown }),
detectLoginUin: async () => (signedIn ? '10001' : null),
nativeReadyOnIdentityHint: true,
});
const loginSpy = vi.fn();
@@ -1195,8 +1260,8 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet)
expect(loginSpy).not.toHaveBeenCalled();
identityKnown = true; // QQ exposes the restored identity
await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up
signedIn = true; // the account's database shows up as signed in
await vi.advanceTimersByTimeAsync(3000); // next interval check picks it up
expect(loginSpy).toHaveBeenCalledOnce();
expect(ctx.session.status).toBe('online');
@@ -1208,8 +1273,8 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
it('does not double-emit when the pushed frame logs in first', async () => {
// Pushed-frame login wins; a subsequent probe with the same uin must not
// re-emit (handleLoginState dedups), and the reconcile timer is stopped.
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', identityKnown: true }));
const ctx = makeSession({ pipeLive: true, probeLogin });
const detectLoginUin = vi.fn(async () => '10001');
const ctx = makeSession({ pipeLive: true, detectLoginUin });
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -1414,27 +1479,27 @@ describe('HookSession — end-to-end receive health (#233)', () => {
});
});
describe('HookSession — login reconcile does not stack concurrent probes', () => {
it('skips overlapping ticks while a slow probe is in flight', async () => {
describe('HookSession — login reconcile does not stack concurrent detections', () => {
it('skips overlapping ticks while a slow detection is in flight', async () => {
vi.useFakeTimers();
try {
// A probe that never resolves — simulates a slow port scan spanning
// A detection that never resolves — simulates a slow read spanning
// multiple intervals. The in-flight guard must call it only once.
const probeLogin = vi.fn(
const detectLoginUin = vi.fn(
() =>
new Promise<never>(() => {
/* pending */
}),
);
const ctx = makeSession({ pipeLive: true, probeLogin });
const ctx = makeSession({ pipeLive: true, detectLoginUin });
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (starts, stays pending)
await vi.advanceTimersByTimeAsync(9000); // 3 more interval ticks
expect(probeLogin).toHaveBeenCalledTimes(1); // not stacked
expect(detectLoginUin).toHaveBeenCalledTimes(1); // not stacked
} finally {
vi.useRealTimers();
}

View File

@@ -20,7 +20,9 @@ vi.mock('../src/qq-hook-client', () => ({
listSnowlumaPipePidsSync: listPidsMock,
}));
const INJECTOR_DIR = path.dirname(fileURLToPath(new URL('../src/injector.ts', import.meta.url)));
const NATIVE_PATH_DIR = path.dirname(
fileURLToPath(new URL('../../common/src/native-path.ts', import.meta.url)),
);
const ORIGINAL_PLATFORM = process.platform;
const ORIGINAL_ARCH = process.arch;
@@ -41,17 +43,15 @@ function restorePlatform(): void {
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
}
function nativeSearchDirs(cwd = process.cwd()): string[] {
function nativeSearchDirs(): string[] {
return [
path.resolve(INJECTOR_DIR, 'native'),
path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'),
path.resolve(cwd, 'dist', 'native'),
path.resolve(cwd, 'packages', 'runtime', 'native'),
path.resolve(NATIVE_PATH_DIR, 'native'),
path.resolve(NATIVE_PATH_DIR, '..', '..', 'runtime', 'native'),
];
}
function nativeCandidate(fileName: string, dirIndex: number, cwd = process.cwd()): string {
return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName);
function nativeCandidate(fileName: string, dirIndex: number): string {
return path.join(nativeSearchDirs()[dirIndex]!, fileName);
}
function allowExisting(paths: readonly string[]): void {
@@ -61,15 +61,17 @@ function allowExisting(paths: readonly string[]): void {
function fakeAddon(
overrides: {
getAllMainProcess?: number[];
loadModuleManual?: (pid: number, dylibPath: string) => unknown;
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
getAllMainProcessAsync?: number[];
loadModuleManualAsync?: (pid: number, dylibPath: string) => Promise<typeof HANDLE>;
unloadModuleManualAsync?: (pid: number, handle: typeof HANDLE) => Promise<void>;
} = {},
) {
return {
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []),
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)),
getAllMainProcessAsync: vi.fn(async () => overrides.getAllMainProcessAsync ?? []),
loadModuleManualAsync: vi.fn(overrides.loadModuleManualAsync ?? (async () => HANDLE)),
unloadModuleManualAsync: vi.fn(
overrides.unloadModuleManualAsync ?? (async () => undefined),
),
};
}
@@ -110,8 +112,6 @@ describe('resolveHookNativePath', () => {
expect(probed).toEqual([
nativeCandidate('snowluma-linux-x64.node', 0),
nativeCandidate('snowluma-linux-x64.node', 1),
nativeCandidate('snowluma-linux-x64.node', 2),
nativeCandidate('snowluma-linux-x64.node', 3),
]);
});
@@ -132,7 +132,7 @@ describe('resolveHookNativePath', () => {
it('skips missing earlier directories for the injectable .so', async () => {
setPlatform('linux', 'arm64');
const winner = nativeCandidate('snowluma-linux-arm64.so', 2);
const winner = nativeCandidate('snowluma-linux-arm64.so', 1);
allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector();
@@ -141,7 +141,7 @@ describe('resolveHookNativePath', () => {
it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
setPlatform('win32', 'x64');
const winner = nativeCandidate('snowluma-win32-x64.dll', 3);
const winner = nativeCandidate('snowluma-win32-x64.dll', 1);
allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector();
@@ -157,7 +157,7 @@ describe('resolveHookNativePath', () => {
expect(resolveHookNativePath('node')).toBe(winner);
});
it('re-reads process.cwd() for the dist/native fallback', async () => {
it('does not load an unrelated native addon from the working directory', async () => {
setPlatform('darwin', 'arm64');
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
const winner = path.join(
@@ -169,7 +169,7 @@ describe('resolveHookNativePath', () => {
allowExisting([winner]);
const { resolveHookNativePath } = await loadInjector();
expect(resolveHookNativePath('node')).toBe(winner);
expect(resolveHookNativePath('node')).toBeNull();
});
});
@@ -248,14 +248,25 @@ describe('getNativeHookAddon / getNativeHookLoadError', () => {
});
describe('listHookProcesses', () => {
it('rejects an obsolete addon without calling its synchronous enumerator', async () => {
setPlatform('win32', 'x64');
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
const getAllMainProcess = vi.fn(() => [9]);
installDlopen({ getAllMainProcess });
const { listHookProcesses } = await loadInjector();
await expect(listHookProcesses()).rejects.toThrow('getAllMainProcessAsync');
expect(getAllMainProcess).not.toHaveBeenCalled();
});
it('on darwin maps sorted pipe pids without opening the native addon', async () => {
setPlatform('darwin', 'arm64');
listPidsMock.mockReturnValue(new Set([42, 7, 15]));
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] }));
const dlopen = installDlopen(fakeAddon({ getAllMainProcessAsync: [99] }));
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([
expect(await listHookProcesses()).toEqual([
{ pid: 7, name: 'qq', path: '' },
{ pid: 15, name: 'qq', path: '' },
{ pid: 42, name: 'qq', path: '' },
@@ -269,14 +280,16 @@ describe('listHookProcesses', () => {
listPidsMock.mockReturnValue(new Set());
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([]);
expect(await listHookProcesses()).toEqual([]);
});
it('on non-darwin returns [] when the addon cannot be loaded', async () => {
it('reports a missing addon instead of an empty process set', async () => {
setPlatform('linux', 'x64');
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([]);
await expect(listHookProcesses()).rejects.toThrow(
'No hook native addon found for linux-x64',
);
});
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
@@ -285,12 +298,12 @@ describe('listHookProcesses', () => {
allowExisting([nodePath]);
installDlopen(
fakeAddon({
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
getAllMainProcessAsync: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
}),
);
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([
expect(await listHookProcesses()).toEqual([
{ pid: 2, name: 'qq', path: '' },
{ pid: 8, name: 'qq', path: '' },
]);
@@ -299,10 +312,10 @@ describe('listHookProcesses', () => {
it('on win32 names processes QQ.exe', async () => {
setPlatform('win32', 'x64');
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
installDlopen(fakeAddon({ getAllMainProcess: [9] }));
installDlopen(fakeAddon({ getAllMainProcessAsync: [9] }));
const { listHookProcesses } = await loadInjector();
expect(listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]);
expect(await listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]);
});
});
@@ -324,13 +337,13 @@ describe('injectHookProcess', () => {
await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64');
});
it('awaits a thenable loadModuleManual handle', async () => {
it('awaits native asynchronous injection', async () => {
setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
const soPath = nativeCandidate('snowluma-linux-x64.so', 0);
allowExisting([nodePath, soPath]);
const addon = fakeAddon({
loadModuleManual: () => Promise.resolve(HANDLE),
loadModuleManualAsync: () => Promise.resolve(HANDLE),
});
installDlopen(addon);
@@ -339,24 +352,8 @@ describe('injectHookProcess', () => {
method: 'loadModuleManual',
handle: HANDLE,
});
expect(addon.loadModuleManual).toHaveBeenCalledTimes(1);
expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath);
});
it('accepts a synchronous loadModuleManual return value', async () => {
setPlatform('darwin', 'arm64');
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2);
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3);
allowExisting([nodePath, soPath]);
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
installDlopen(addon);
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(77)).resolves.toEqual({
method: 'loadModuleManual',
handle: HANDLE,
});
expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath);
expect(addon.loadModuleManualAsync).toHaveBeenCalledTimes(1);
expect(addon.loadModuleManualAsync).toHaveBeenCalledWith(4242, soPath);
});
it('injects snowluma-win32-x64.dll on win32 x64', async () => {
@@ -364,7 +361,7 @@ describe('injectHookProcess', () => {
const nodePath = nativeCandidate('snowluma-win32-x64.node', 0);
const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0);
allowExisting([nodePath, dllPath]);
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
const addon = fakeAddon({ loadModuleManualAsync: async () => HANDLE });
installDlopen(addon);
const { injectHookProcess } = await loadInjector();
@@ -372,7 +369,7 @@ describe('injectHookProcess', () => {
method: 'loadModuleManual',
handle: HANDLE,
});
expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath);
expect(addon.loadModuleManualAsync).toHaveBeenCalledWith(5150, dllPath);
});
it('propagates a rejected loadModuleManual', async () => {
@@ -383,7 +380,7 @@ describe('injectHookProcess', () => {
]);
installDlopen(
fakeAddon({
loadModuleManual: () => Promise.reject(new Error('map failed')),
loadModuleManualAsync: () => Promise.reject(new Error('map failed')),
}),
);
@@ -393,10 +390,24 @@ describe('injectHookProcess', () => {
});
describe('unloadHookProcess', () => {
it('propagates native unload rejection', async () => {
setPlatform('linux', 'x64');
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
installDlopen(
fakeAddon({
unloadModuleManualAsync: async () => {
throw new Error('unload failed');
},
}),
);
const { unloadHookProcess } = await loadInjector();
await expect(unloadHookProcess(4242, HANDLE)).rejects.toThrow('unload failed');
});
it('throws the missing-addon load error', async () => {
setPlatform('linux', 'x64');
const { unloadHookProcess } = await loadInjector();
expect(() => unloadHookProcess(4242, HANDLE)).toThrow(
await expect(unloadHookProcess(4242, HANDLE)).rejects.toThrow(
'No hook native addon found for linux-x64',
);
});
@@ -408,8 +419,8 @@ describe('unloadHookProcess', () => {
installDlopen(addon);
const { unloadHookProcess } = await loadInjector();
expect(unloadHookProcess(4242, HANDLE)).toBeUndefined();
expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1);
expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE);
await expect(unloadHookProcess(4242, HANDLE)).resolves.toBeUndefined();
expect(addon.unloadModuleManualAsync).toHaveBeenCalledTimes(1);
expect(addon.unloadModuleManualAsync).toHaveBeenCalledWith(4242, HANDLE);
});
});

View File

@@ -1,4 +1,5 @@
import { describe, it, expect } from 'vitest';
import { afterEach, describe, it, expect, vi } from 'vitest';
import { createLogger } from '@snowluma/common/logger';
import { PipeWatcher } from '../src/pipe-watcher';
import type { HookProcessBaseInfo } from '../src/injector';
@@ -6,7 +7,7 @@ function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<num
let processes = initial.processes;
let live = initial.live;
const watcher = new PipeWatcher({
listProcesses: () => processes,
listProcesses: async () => processes,
// Defensively copy so the watcher can't mutate the test's reference.
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
@@ -36,6 +37,167 @@ function captureEvents(watcher: PipeWatcher): EventRow[] {
}
describe('PipeWatcher', () => {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it('waits for a fresh scan when another tick is already reading processes', async () => {
let release!: (processes: HookProcessBaseInfo[]) => void;
const pending = new Promise<HookProcessBaseInfo[]>((resolve) => {
release = resolve;
});
const latest = [{ pid: 1234, name: 'QQ.exe', path: '' }];
const listProcesses = vi.fn().mockReturnValueOnce(pending).mockResolvedValue(latest);
const watcher = new PipeWatcher({
listProcesses,
listLivePipes: async () => new Set([1234]),
});
const first = watcher.tickNow();
let completed = false;
const second = watcher.tickNow().then(() => {
completed = true;
});
await Promise.resolve();
expect(completed).toBe(false);
release([]);
await Promise.all([first, second]);
expect(listProcesses).toHaveBeenCalledTimes(2);
expect(watcher.isPipeLive(1234)).toBe(true);
watcher.dispose();
});
it.each(['processes', 'pipes'] as const)(
'discards a pending %s scan after stop',
async (stage) => {
let release!: () => void;
let entered!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const started = new Promise<void>((resolve) => {
entered = resolve;
});
const processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
const listProcesses = vi.fn(async () => {
if (stage === 'processes') {
entered();
await gate;
}
return processes;
});
const listLivePipes = vi.fn(async () => {
if (stage === 'pipes') {
entered();
await gate;
}
return new Set([1234]);
});
const watcher = new PipeWatcher({ listProcesses, listLivePipes });
const events = captureEvents(watcher);
const tick = vi.fn();
watcher.on('tick', tick);
const reading = watcher.start();
await started;
const queued = watcher.tickNow();
watcher.stop();
release();
await Promise.all([reading, queued]);
await watcher.tickNow();
watcher.wake();
expect(events).toEqual([]);
expect(tick).not.toHaveBeenCalled();
expect(watcher.isProcessAlive(1234)).toBe(false);
expect(listProcesses).toHaveBeenCalledOnce();
expect(listLivePipes).toHaveBeenCalledTimes(stage === 'pipes' ? 1 : 0);
watcher.dispose();
},
);
it('keeps a wake requested by a tick listener ahead of the regular interval', async () => {
vi.useFakeTimers();
const listProcesses = vi.fn(async () => []);
const watcher = new PipeWatcher({
listProcesses,
listLivePipes: async () => new Set(),
intervalMs: 60_000,
});
watcher.once('tick', () => watcher.wake());
await watcher.start();
await vi.advanceTimersByTimeAsync(1);
expect(listProcesses).toHaveBeenCalledTimes(2);
watcher.dispose();
});
it('reports a scheduled tick failure and continues polling', async () => {
vi.useFakeTimers();
const listProcesses = vi.fn(async () => []);
const log = createLogger('PipeWatcherTest');
const warn = vi.spyOn(log, 'warn').mockImplementation(() => {});
const watcher = new PipeWatcher({
listProcesses,
listLivePipes: async () => new Set(),
intervalMs: 250,
log,
});
try {
await watcher.start();
watcher.once('tick', () => {
throw new Error('subscriber failed');
});
await vi.advanceTimersByTimeAsync(250);
expect(warn).toHaveBeenCalledWith('poll failed: %s', 'subscriber failed');
await vi.advanceTimersByTimeAsync(250);
expect(listProcesses).toHaveBeenCalledTimes(3);
} finally {
watcher.dispose();
}
});
it('publishes the complete snapshot before notifying subscribers', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
const snapshots: boolean[][] = [];
const observe = () =>
snapshots.push([ctx.watcher.isProcessAlive(1234), ctx.watcher.isPipeLive(1234)]);
ctx.watcher.on('process-discovered', observe);
ctx.watcher.on('pipe-up', observe);
ctx.watcher.on('pipe-down', observe);
ctx.watcher.on('process-gone', observe);
await ctx.watcher.tickNow();
ctx.setProcesses([]);
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(snapshots).toEqual([
[true, true],
[true, true],
[false, false],
[false, false],
]);
ctx.watcher.dispose();
});
it('stops emitting the current diff when a subscriber stops the watcher', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
ctx.watcher.on('process-discovered', () => ctx.watcher.stop());
const up = vi.fn();
const tick = vi.fn();
ctx.watcher.on('pipe-up', up);
ctx.watcher.on('tick', tick);
await ctx.watcher.tickNow();
expect(up).not.toHaveBeenCalled();
expect(tick).not.toHaveBeenCalled();
ctx.watcher.dispose();
});
it('passes the current process snapshot to pipe discovery', async () => {
const processes = [
{ pid: 1234, name: 'qq', path: '/opt/QQ/qq' },
@@ -43,7 +205,7 @@ describe('PipeWatcher', () => {
];
let observed: readonly HookProcessBaseInfo[] | undefined;
const watcher = new PipeWatcher({
listProcesses: () => processes,
listProcesses: async () => processes,
listLivePipes: async (current) => {
observed = current;
return new Set();
@@ -208,7 +370,7 @@ describe('PipeWatcher', () => {
let live = new Set<number>();
let shouldThrow = true;
const watcher = new PipeWatcher({
listProcesses: () => {
listProcesses: async () => {
if (shouldThrow) {
throw new Error('boom');
}
@@ -239,7 +401,7 @@ describe('PipeWatcher', () => {
let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
let failPipeDiscovery = false;
const watcher = new PipeWatcher({
listProcesses: () => processes,
listProcesses: async () => processes,
listLivePipes: async () => {
if (failPipeDiscovery) {
throw new Error('permission denied');
@@ -277,7 +439,7 @@ describe('PipeWatcher', () => {
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
let live = new Set<number>([1234]);
const watcher = new PipeWatcher({
listProcesses: () => result,
listProcesses: async () => result,
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});

View File

@@ -1,57 +1,120 @@
import { describe, it, expect, vi } from 'vitest';
import { createNativeProcessEnumerator } from '../src/process-enumerator';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createProcessEnumerator } from '../src/process-enumerator';
import type { HookProcessBaseInfo } from '../src/injector';
const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' });
describe('createNativeProcessEnumerator', () => {
describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => {
it('returns the sync lister result', async () => {
const en = createNativeProcessEnumerator({
addonPath: null,
fallbackSync: () => [QQ(10), QQ(20)],
processName: 'qq',
});
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]);
en.dispose();
});
function deferred() {
let resolve!: (processes: HookProcessBaseInfo[]) => void;
let reject!: (error: Error) => void;
const promise = new Promise<HookProcessBaseInfo[]>((done, fail) => {
resolve = done;
reject = fail;
});
return { promise, resolve, reject };
}
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
const en = createNativeProcessEnumerator({
addonPath: null,
fallbackSync: () => {
throw new Error('boom');
},
processName: 'qq',
});
expect(await en.enumerate()).toBeNull();
en.dispose();
});
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
describe('process enumeration', () => {
it('shares one native request between concurrent callers', async () => {
const request = deferred();
const listProcesses = vi.fn(() => request.promise);
const enumerator = createProcessEnumerator({ listProcesses });
const first = enumerator.enumerate();
expect(enumerator.enumerate()).toBe(first);
request.resolve([QQ(1), QQ(2)]);
expect(await first).toEqual([QQ(1), QQ(2)]);
expect(listProcesses).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
enumerator.dispose();
});
describe('worker isolation that cannot load the addon → permanent fallback', () => {
it('falls back to the sync lister after the worker reports a fatal load error', async () => {
const fallback = vi.fn(() => [QQ(7)]);
const en = createNativeProcessEnumerator({
// A path that exists nowhere → process.dlopen throws in the worker →
// the worker posts 'fatal' → isolation is abandoned for good.
addonPath: '/nonexistent/snowluma-test.node',
fallbackSync: fallback,
processName: 'qq',
timeoutMs: 200,
it('keeps timed-out native work in flight until it actually finishes', async () => {
const request = deferred();
const listProcesses = vi.fn(() => request.promise).mockResolvedValueOnce([QQ(1)]);
const enumerator = createProcessEnumerator({ listProcesses, timeoutMs: 100 });
expect(await enumerator.enumerate()).toEqual([QQ(1)]);
const stalled = enumerator.enumerate();
await vi.advanceTimersByTimeAsync(100);
expect(await stalled).toBeNull();
for (let i = 0; i < 10; i++) {
expect(await enumerator.enumerate()).toBeNull();
}
expect(listProcesses).toHaveBeenCalledTimes(2);
request.resolve([QQ(2)]);
await vi.advanceTimersByTimeAsync(0);
listProcesses.mockResolvedValueOnce([QQ(3)]);
expect(await enumerator.enumerate()).toEqual([QQ(3)]);
expect(await stalled).toBeNull();
enumerator.dispose();
});
it.each(['throw', 'reject'] as const)(
'keeps a %s unknown and allows a fresh request',
async (kind) => {
const listProcesses = vi.fn<() => Promise<HookProcessBaseInfo[]>>(() => {
if (kind === 'throw') {
throw new Error('process table unavailable');
}
return Promise.reject(new Error('process table unavailable'));
});
const enumerator = createProcessEnumerator({ listProcesses });
expect(await enumerator.enumerate()).toBeNull();
expect(vi.getTimerCount()).toBe(0);
listProcesses.mockResolvedValueOnce([]);
expect(await enumerator.enumerate()).toEqual([]);
enumerator.dispose();
},
);
// First call spawns the worker; the fatal message drains it to UNKNOWN.
const first = await en.enumerate();
expect(first).toBeNull();
it('handles a rejection after timeout and recovers on the next poll', async () => {
const request = deferred();
const listProcesses = vi.fn(() => request.promise);
const enumerator = createProcessEnumerator({ listProcesses, timeoutMs: 100 });
const pending = enumerator.enumerate();
await vi.advanceTimersByTimeAsync(100);
expect(await pending).toBeNull();
request.reject(new Error('late failure'));
await vi.advanceTimersByTimeAsync(0);
listProcesses.mockResolvedValueOnce([QQ(4)]);
expect(await enumerator.enumerate()).toEqual([QQ(4)]);
enumerator.dispose();
});
// Give the 'fatal' message a moment to flip isolationBroken if it hadn't
// already, then subsequent calls take the synchronous fallback.
await new Promise((r) => setTimeout(r, 50));
const second = await en.enumerate();
expect(second).toEqual([QQ(7)]);
expect(fallback).toHaveBeenCalled();
en.dispose();
});
it('settles disposal immediately without accepting late native results', async () => {
const request = deferred();
const listProcesses = vi.fn(() => request.promise);
const enumerator = createProcessEnumerator({ listProcesses });
const pending = enumerator.enumerate();
await Promise.resolve();
enumerator.dispose();
enumerator.dispose();
expect(await pending).toBeNull();
expect(vi.getTimerCount()).toBe(0);
request.resolve([QQ(1)]);
expect(await enumerator.enumerate()).toBeNull();
expect(listProcesses).toHaveBeenCalledTimes(1);
});
it('never calls the lister after disposal', async () => {
const listProcesses = vi.fn(async () => [QQ(1)]);
const enumerator = createProcessEnumerator({ listProcesses });
enumerator.dispose();
expect(await enumerator.enumerate()).toBeNull();
expect(listProcesses).not.toHaveBeenCalled();
});
it('does not start queued native work when disposed in the same tick', async () => {
const listProcesses = vi.fn(async () => [QQ(1)]);
const enumerator = createProcessEnumerator({ listProcesses });
const pending = enumerator.enumerate();
enumerator.dispose();
expect(await pending).toBeNull();
expect(listProcesses).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,142 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { mkdtemp, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { SqliteDatabase } from '@snowluma/sqlite';
import { isQqProcessName, getDatabaseHolders } from '../src/qq-account/database-holders';
const native = vi.hoisted(() => ({ addon: vi.fn<() => unknown>(() => null) }));
vi.mock('../src/injector', () => ({ getNativeHookAddon: native.addon }));
const IS_LINUX = process.platform === 'linux';
const ORIGINAL_PLATFORM = process.platform;
/** Run `getDatabaseHolders` as if the host were Windows, with a stubbed addon. */
async function asWindows<T>(addon: unknown, run: () => Promise<T>): Promise<T> {
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
native.addon.mockReturnValue(addon);
try {
return await run();
} finally {
Object.defineProperty(process, 'platform', {
value: ORIGINAL_PLATFORM,
configurable: true,
});
}
}
afterEach(() => {
native.addon.mockReset();
native.addon.mockReturnValue(null);
});
describe('database holder probe', () => {
it.runIf(IS_LINUX)('reports nothing for a file that is not there', async () => {
const missing = path.join(os.tmpdir(), `snowluma-absent-${process.pid}.db`);
expect(await getDatabaseHolders(missing)).toEqual([]);
});
it.runIf(IS_LINUX)('finds the process holding a database', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-lock-'));
const file = path.join(directory, 'nt_msg.db');
const db = new SqliteDatabase(file);
try {
// A rollback-journal write transaction takes a POSIX lock on the
// database file itself, which is exactly what a signed-in client
// holds on the account's nt_msg.db.
await db.exec('PRAGMA journal_mode = DELETE');
await db.exec('CREATE TABLE t(value TEXT)');
await db.exec('BEGIN IMMEDIATE');
const holders = await getDatabaseHolders(file);
const self = holders.find((holder) => holder.pid === process.pid);
expect(self).toBeDefined();
// The holder is named from /proc/<pid>/comm, and that name is what
// keeps a holder that is not QQ from being mistaken for one.
expect(self!.name.length).toBeGreaterThan(0);
expect(isQqProcessName(self!.name)).toBe(false);
await db.exec('ROLLBACK');
expect(
(await getDatabaseHolders(file)).some((holder) => holder.pid === process.pid),
).toBe(false);
} finally {
await db.close();
await rm(directory, { recursive: true, force: true });
}
});
});
describe('Windows holder probe', () => {
it('propagates rejected native queries instead of treating them as no login', async () => {
await expect(
asWindows(
{
getFileHoldersAsync: async () => {
throw new Error('RmGetList failed: 5');
},
},
() => getDatabaseHolders('C:\\nt_msg.db'),
),
).rejects.toThrow('RmGetList failed: 5');
});
it('reports the holders the addon lists', async () => {
const holders = await asWindows(
{
getFileHoldersAsync: async () => [
{ pid: 4242, name: 'QQ.exe' },
{ pid: 7, name: 'weq' },
],
},
() => getDatabaseHolders('C:\\Tencent Files\\10001\\nt_qq\\nt_db\\nt_msg.db'),
);
expect(holders).toEqual([
{ pid: 4242, name: 'QQ.exe' },
{ pid: 7, name: 'weq' },
]);
});
it.each([[{ pid: 0, name: 'QQ' }], [{ pid: 9 }], [null], 'not-an-array'])(
'reports malformed native results: %j',
async (result) => {
await expect(
asWindows({ getFileHoldersAsync: async () => result }, () =>
getDatabaseHolders('C:\\nt_msg.db'),
),
).rejects.toThrow('Invalid database holders');
},
);
it('accepts an empty holder list', async () => {
expect(
await asWindows({ getFileHoldersAsync: async () => [] }, () =>
getDatabaseHolders('C:\\nt_msg.db'),
),
).toEqual([]);
});
it.each([null, {}])('reports an unavailable native probe: %j', async (addon) => {
await expect(asWindows(addon, () => getDatabaseHolders('C:\\nt_msg.db'))).rejects.toThrow(
'requires a hook addon with getFileHoldersAsync',
);
});
});
describe('QQ process names', () => {
it('accepts the name each platform reports for the client', () => {
expect(isQqProcessName('QQ')).toBe(true);
expect(isQqProcessName('QQ.exe')).toBe(true);
expect(isQqProcessName(' qq ')).toBe(true);
});
it('rejects other holders', () => {
expect(isQqProcessName('node')).toBe(false);
expect(isQqProcessName('qqmusic')).toBe(false);
expect(isQqProcessName('')).toBe(false);
});
});

View File

@@ -0,0 +1,241 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { spawn } from 'node:child_process';
import { mkdtemp, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
const mocks = vi.hoisted(() => ({
readLocalAccounts: vi.fn(),
getDatabaseHolders: vi.fn(),
}));
// The account list and the holder probe are covered on their own; this file is
// about how the two are joined.
vi.mock('../src/qq-account/login-db', () => ({ readLocalAccounts: mocks.readLocalAccounts }));
vi.mock('../src/qq-account/database-holders', async (importOriginal) => ({
...(await importOriginal<typeof import('../src/qq-account/database-holders')>()),
getDatabaseHolders: mocks.getDatabaseHolders,
}));
import { detectAccountLogins, detectAccountLoginsForPids } from '../src/qq-account/detect';
import { loginDbPaths, ntMsgDbPath } from '../src/qq-account/paths';
const ALICE = { uin: '10001', uid: 'u_alice', nickname: 'Alice' };
const BOB = { uin: '10002', uid: 'u_bob', nickname: 'Bob' };
const roots: string[] = [];
const children: Array<ReturnType<typeof spawn>> = [];
afterEach(async () => {
mocks.readLocalAccounts.mockReset();
mocks.getDatabaseHolders.mockReset();
for (const child of children.splice(0)) {
child.kill();
}
for (const root of roots.splice(0)) {
await rm(root, { recursive: true, force: true });
}
});
async function makeRoot(): Promise<string> {
const root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-detect-'));
roots.push(root);
return root;
}
/**
* A live process whose `/proc/<pid>/environ` carries `HOME` (and any extra
* variables given).
*
* `XDG_CONFIG_HOME` is dropped unless the caller sets it: it outranks `HOME`
* when deriving the data root, and a CI runner exports its own, which would
* otherwise decide the result instead of the HOME under test.
*
* Resolves only once the child has run past `execve`, because `/proc/<pid>`
* still shows the parent's environment before that.
*/
function spawnWithHome(home: string, extra: Record<string, string> = {}): Promise<number> {
return new Promise((resolve, reject) => {
const env: NodeJS.ProcessEnv = { ...process.env };
delete env.XDG_CONFIG_HOME;
Object.assign(env, { HOME: home }, extra);
const child = spawn(
process.execPath,
['-e', 'console.log("ready"); setTimeout(() => {}, 30000)'],
{ env, stdio: ['ignore', 'pipe', 'ignore'] },
);
children.push(child);
child.stdout!.once('data', () => resolve(child.pid!));
child.once('error', reject);
});
}
describe('local account detection', () => {
it('labels each account with the process holding its database', async () => {
const root = await makeRoot();
mocks.readLocalAccounts.mockResolvedValue({ accounts: [ALICE, BOB], failures: [] });
mocks.getDatabaseHolders.mockImplementation(async (dbPath: string) => {
if (dbPath === ntMsgDbPath(root, ALICE)) {
return [{ pid: 4242, name: 'qq' }];
}
// A holder that is not the client must not be mistaken for one.
return [{ pid: 999, name: 'node' }];
});
await expect(detectAccountLogins([root])).resolves.toEqual([
{ ...ALICE, pid: 4242 },
{ ...BOB, pid: null },
]);
});
it('merges the accounts of every root instead of stopping at the first', async () => {
const own = await makeRoot();
const extra = await makeRoot();
mocks.readLocalAccounts.mockImplementation(async (root: string) =>
root === own ? { accounts: [ALICE], failures: [] } : { accounts: [BOB], failures: [] },
);
mocks.getDatabaseHolders.mockImplementation(async (dbPath: string) =>
dbPath === ntMsgDbPath(extra, BOB) ? [{ pid: 5151, name: 'qq' }] : [],
);
await expect(detectAccountLogins([own, extra])).resolves.toEqual([
{ ...ALICE, pid: null },
{ ...BOB, pid: 5151 },
]);
// An account held under an instance's own HOME is still labelled, which
// is what a single-root lookup cannot do.
expect(mocks.getDatabaseHolders).toHaveBeenCalledWith(ntMsgDbPath(extra, BOB));
});
it('keeps account records with the same uin scoped to their own root', async () => {
const first = await makeRoot();
const second = await makeRoot();
mocks.readLocalAccounts.mockImplementation(async (root: string) =>
root === first
? { accounts: [ALICE], failures: [] }
: { accounts: [{ ...ALICE, nickname: 'Stale' }], failures: [] },
);
mocks.getDatabaseHolders.mockImplementation(async (file: string) =>
file === ntMsgDbPath(second, ALICE) ? [{ pid: 5151, name: 'qq' }] : [],
);
await expect(detectAccountLogins([first, second])).resolves.toEqual([
{ ...ALICE, pid: null },
{ ...ALICE, nickname: 'Stale', pid: 5151 },
]);
});
it('reports nothing when there are no roots', async () => {
await expect(detectAccountLogins([])).resolves.toEqual([]);
expect(mocks.readLocalAccounts).not.toHaveBeenCalled();
});
it('logs a named reason when a login.db is present but unreadable', async () => {
const root = await makeRoot();
const entries: LogEntry[] = [];
const previousLevel = getLogLevel();
setLogLevel('debug');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
mocks.readLocalAccounts.mockResolvedValue({
accounts: [],
failures: [
{
path: loginDbPaths(root)[0]!,
reason: 'undecryptable',
},
],
});
mocks.getDatabaseHolders.mockResolvedValue([]);
// An unreadable login.db must not look like "no accounts": an
// operator reading the log has to see why nothing was reported.
await detectAccountLogins([root]);
} finally {
unsubscribe();
setLogLevel(previousLevel);
}
const warned = entries.filter(
(entry) => entry.level === 'warn' && entry.scope === 'QqAccount',
);
expect(warned).toHaveLength(1);
expect(warned[0]!.message).toContain('login.db unreadable');
expect(warned[0]!.message).toContain('undecryptable');
});
});
describe.runIf(process.platform === 'linux')('per-process data roots', () => {
it('reads each pid against the HOME that process runs under', async () => {
const home = await makeRoot();
const pid = await spawnWithHome(home);
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.getDatabaseHolders.mockResolvedValue([]);
await detectAccountLoginsForPids([pid]);
// `<HOME>/.config/QQ`, from the child's environment rather than ours.
expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(home, '.config', 'QQ'));
});
it('asks each root once when several processes share a HOME', async () => {
const home = await makeRoot();
const pids = [await spawnWithHome(home), await spawnWithHome(home)];
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.getDatabaseHolders.mockResolvedValue([]);
await detectAccountLoginsForPids(pids);
expect(mocks.readLocalAccounts).toHaveBeenCalledTimes(1);
});
it('honours XDG_CONFIG_HOME of the process over its HOME', async () => {
const home = await makeRoot();
const configHome = await makeRoot();
const pid = await spawnWithHome(home, { XDG_CONFIG_HOME: configHome });
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.getDatabaseHolders.mockResolvedValue([]);
await detectAccountLoginsForPids([pid]);
// The XDG variable outranks HOME, as it does for the client itself.
expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(configHome, 'QQ'));
});
it('keeps each process on its own root when the HOMEs differ', async () => {
const first = await makeRoot();
const second = await makeRoot();
const pids = [await spawnWithHome(first), await spawnWithHome(second)];
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.getDatabaseHolders.mockResolvedValue([]);
await detectAccountLoginsForPids(pids);
expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(first, '.config', 'QQ'));
expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(second, '.config', 'QQ'));
});
it('does not substitute another HOME when the pid is gone', async () => {
const home = await makeRoot();
const pid = await spawnWithHome(home);
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.getDatabaseHolders.mockResolvedValue([]);
// The child exits, so its environment is no longer readable.
await new Promise<void>((resolve) => {
const child = children[children.length - 1]!;
child.once('exit', () => resolve());
child.kill();
});
await detectAccountLoginsForPids([pid]);
expect(mocks.readLocalAccounts).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,195 @@
/**
* Encryption helpers for the account-detection tests.
*
* The shipped code only decrypts, so producing an encrypted fixture means
* mirroring SQLCipher's page layout here: `[client header][page 1]…` with each
* page ending in `IV || page HMAC`, and a `-wal` whose frame header stays
* plaintext while the page inside it is encrypted.
*/
import { createCipheriv, createHmac, pbkdf2Sync, randomBytes } from 'node:crypto';
import type { KdfHmacAlgorithm, PageHmacAlgorithm } from '../src/qq-account/sqlcipher';
export interface FixtureAlgorithm {
pageHmac: PageHmacAlgorithm;
kdfHmac: KdfHmacAlgorithm;
}
export const FIXTURE_PASSPHRASE = 'BD156D6710D54D8782F4';
export const FIXTURE_PAGE_SIZE = 4096;
export const FIXTURE_HEADER_SIZE = 1024;
export const FIXTURE_WAL_HEADER_SIZE = 32;
export const FIXTURE_WAL_FRAME_HEADER_SIZE = 24;
const DIGEST_BYTES: Record<PageHmacAlgorithm, number> = {
none: 0,
sha1: 20,
sha256: 32,
sha512: 64,
};
const KDF_ITERATIONS = 4000;
const HMAC_KEY_ITERATIONS = 2;
const HMAC_SALT_MASK = 0x3a;
export function reserveBytes(algorithm: FixtureAlgorithm): number {
return Math.ceil((16 + DIGEST_BYTES[algorithm.pageHmac]) / 16) * 16;
}
/** Encrypt a plaintext SQLite image the way QQ NT stores it. */
export function encryptImage(
plain: Buffer,
algorithm: FixtureAlgorithm,
passphrase = FIXTURE_PASSPHRASE,
salt = randomBytes(16),
): Buffer {
const pageCount = plain.length / FIXTURE_PAGE_SIZE;
const key = pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, 32, algorithm.kdfHmac);
const output = Buffer.alloc(FIXTURE_HEADER_SIZE + plain.length);
for (let index = 0; index < pageCount; index++) {
const pageNumber = index + 1;
const skip = pageNumber === 1 ? 16 : 0;
const body = plain.subarray(
index * FIXTURE_PAGE_SIZE + skip,
(index + 1) * FIXTURE_PAGE_SIZE,
);
if (pageNumber === 1) {
// Page 1 stores the KDF salt where SQLite keeps its magic.
salt.copy(output, FIXTURE_HEADER_SIZE);
}
encryptPageInto(
output,
FIXTURE_HEADER_SIZE + index * FIXTURE_PAGE_SIZE,
body,
pageNumber,
key,
salt,
algorithm,
);
}
return output;
}
/** Encrypt the pages of a real (plaintext) WAL, recomputing the frame checksums. */
export function encryptWal(
plainWal: Buffer,
encryptedImage: Buffer,
algorithm: FixtureAlgorithm,
passphrase = FIXTURE_PASSPHRASE,
): Buffer {
const salt = encryptedImage.subarray(FIXTURE_HEADER_SIZE, FIXTURE_HEADER_SIZE + 16);
const key = pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, 32, algorithm.kdfHmac);
const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE;
const output = Buffer.alloc(plainWal.length);
plainWal.copy(output, 0, 0, FIXTURE_WAL_HEADER_SIZE);
let running = walChecksum([0, 0], [output.subarray(0, FIXTURE_WAL_HEADER_SIZE - 8)], true);
for (
let offset = FIXTURE_WAL_HEADER_SIZE;
offset + frameSize <= plainWal.length;
offset += frameSize
) {
const frameHeader = plainWal.subarray(offset, offset + FIXTURE_WAL_FRAME_HEADER_SIZE);
const pageNumber = frameHeader.readUInt32BE(0);
const skip = pageNumber === 1 ? 16 : 0;
const page = plainWal.subarray(offset + FIXTURE_WAL_FRAME_HEADER_SIZE, offset + frameSize);
encryptPageInto(
output,
offset + FIXTURE_WAL_FRAME_HEADER_SIZE,
page.subarray(skip),
pageNumber,
key,
salt,
algorithm,
);
const stored = output.subarray(offset, offset + FIXTURE_WAL_FRAME_HEADER_SIZE);
frameHeader.copy(stored, 0, 0, 8);
running = walChecksum(
running,
[
stored.subarray(0, 8),
output.subarray(offset + FIXTURE_WAL_FRAME_HEADER_SIZE, offset + frameSize),
],
true,
);
stored.writeUInt32BE(running[0], 16);
stored.writeUInt32BE(running[1], 20);
}
return output;
}
/**
* SQLite's rolling WAL checksum, as the fixture needs it to rebuild frame
* checksums — and to prove the shipped implementation agrees with what SQLite
* itself wrote in a real `-wal`.
*/
export function walChecksum(
seed: [number, number],
chunks: readonly Buffer[],
littleEndian: boolean,
): [number, number] {
let first = seed[0];
let second = seed[1];
for (const chunk of chunks) {
for (let offset = 0; offset + 8 <= chunk.length; offset += 8) {
const high = littleEndian ? chunk.readUInt32LE(offset) : chunk.readUInt32BE(offset);
const low = littleEndian
? chunk.readUInt32LE(offset + 4)
: chunk.readUInt32BE(offset + 4);
first = (first + high + second) >>> 0;
second = (second + low + first) >>> 0;
}
}
return [first, second];
}
function encryptPageInto(
output: Buffer,
pageOffset: number,
body: Buffer,
pageNumber: number,
key: Buffer,
salt: Buffer,
algorithm: FixtureAlgorithm,
): void {
// Page 1 stores the KDF salt where SQLite keeps its magic, so its ciphertext
// starts one salt past the page boundary.
const offset = pageOffset + (pageNumber === 1 ? 16 : 0);
const reserve = reserveBytes(algorithm);
const cipherLength = body.length - reserve;
const iv = randomBytes(16);
const cipher = createCipheriv('aes-256-cbc', key, iv);
cipher.setAutoPadding(false);
const ciphertext = Buffer.concat([
cipher.update(body.subarray(0, cipherLength)),
cipher.final(),
]);
ciphertext.copy(output, offset);
iv.copy(output, offset + cipherLength);
const digestBytes = DIGEST_BYTES[algorithm.pageHmac];
if (digestBytes === 0) {
return;
}
const hmacSalt = Buffer.from(salt.map((byte) => byte ^ HMAC_SALT_MASK));
const hmacKey = pbkdf2Sync(key, hmacSalt, HMAC_KEY_ITERATIONS, 32, algorithm.kdfHmac);
const pageNumberBytes = Buffer.alloc(4);
pageNumberBytes.writeUInt32LE(pageNumber);
const digest = createHmac(algorithm.pageHmac, hmacKey)
.update(ciphertext)
.update(iv)
.update(pageNumberBytes)
.digest();
digest.copy(output, offset + cipherLength + 16);
}

View File

@@ -0,0 +1,246 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdir, mkdtemp, rm, utimes, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { SqliteDatabase } from '@snowluma/sqlite';
const mocks = vi.hoisted(() => ({
detectAlgorithm: vi.fn(),
decryptDatabase: vi.fn(),
}));
// The page crypto is covered on its own; account reading stands on top of it, so
// the fixtures below hand over plaintext images and the decrypt step is stubbed
// to pass them through.
vi.mock('../src/qq-account/sqlcipher', () => ({
detectAlgorithm: mocks.detectAlgorithm,
decryptDatabase: mocks.decryptDatabase,
}));
vi.mock('../src/qq-account/paths', () => ({
loginDbPaths: (root: string) => [path.join(root, PRIMARY), path.join(root, SECONDARY)],
}));
import { readLocalAccounts } from '../src/qq-account/login-db';
const PRIMARY = path.join('global', 'nt_db', 'login.db');
const SECONDARY = path.join('nt_qq', 'global', 'nt_db', 'login.db');
/** Write a plaintext database with QQ's account table at `file`. */
async function writeLoginDb(
file: string,
rows: ReadonlyArray<readonly [string, string, string]>,
): Promise<void> {
await mkdir(path.dirname(file), { recursive: true });
await rm(file, { force: true });
await rm(`${file}-wal`, { force: true });
const db = new SqliteDatabase(file);
try {
await db.exec('CREATE TABLE login_table("1000" TEXT, "1001" TEXT, "1007" TEXT)');
for (const [uin, uid, nickname] of rows) {
await db.prepare('INSERT INTO login_table VALUES (?, ?, ?)').run(uin, uid, nickname);
}
} finally {
await db.close();
}
}
async function makeRoot(
rows: ReadonlyArray<readonly [string, string, string]>,
secondaryRows: ReadonlyArray<readonly [string, string, string]> = [],
): Promise<string> {
const root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-login-'));
await writeLoginDb(path.join(root, PRIMARY), rows);
if (secondaryRows.length > 0) {
await writeLoginDb(path.join(root, SECONDARY), secondaryRows);
}
return root;
}
const roots: string[] = [];
beforeEach(() => {
mocks.detectAlgorithm.mockReturnValue({ pageHmac: 'sha1', kdfHmac: 'sha512' });
mocks.decryptDatabase.mockImplementation((image: Buffer) => ({ image, walFrames: 0 }));
});
afterEach(async () => {
mocks.detectAlgorithm.mockReset();
mocks.decryptDatabase.mockReset();
for (const root of roots.splice(0)) {
await rm(root, { recursive: true, force: true });
}
});
async function trackedRoot(
rows: ReadonlyArray<readonly [string, string, string]>,
secondaryRows: ReadonlyArray<readonly [string, string, string]> = [],
): Promise<string> {
const root = await makeRoot(rows, secondaryRows);
roots.push(root);
return root;
}
describe('local account list', () => {
it('reads the accounts QQ cached locally', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
await expect(readLocalAccounts(root)).resolves.toEqual({
accounts: [{ uin: '10001', uid: 'u_a', nickname: 'Alice' }],
failures: [],
});
});
it('merges both login.db locations, letting the primary win on a clash', async () => {
const root = await trackedRoot(
[
['10001', 'u_a', 'Alice'],
['10002', 'u_b', 'Bob'],
],
[
['10001', 'u_a_stale', 'AliceStale'],
['10003', 'u_c', 'Carol'],
],
);
expect(await readLocalAccounts(root)).toEqual({
accounts: [
{ uin: '10001', uid: 'u_a', nickname: 'Alice' },
{ uin: '10002', uid: 'u_b', nickname: 'Bob' },
{ uin: '10003', uid: 'u_c', nickname: 'Carol' },
],
failures: [],
});
});
it('re-decrypts only when the database or its sidecar changes', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
const file = path.join(root, PRIMARY);
await readLocalAccounts(root);
await readLocalAccounts(root);
expect(mocks.decryptDatabase).toHaveBeenCalledTimes(1);
// A login that just happened rewrites the database; the new rows have to
// show up instead of the cached list.
await writeLoginDb(file, [
['10001', 'u_a', 'Alice'],
['10002', 'u_b', 'Bob'],
]);
await utimes(file, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000));
expect((await readLocalAccounts(root)).accounts).toHaveLength(2);
expect(mocks.decryptDatabase).toHaveBeenCalledTimes(2);
// The sidecar counts as a change too: a batch committed to the WAL only
// leaves login.db untouched.
await writeFile(`${file}-wal`, Buffer.alloc(0));
await readLocalAccounts(root);
expect(mocks.decryptDatabase).toHaveBeenCalledTimes(3);
});
it('shares concurrent reads of the same database image', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
const reports = await Promise.all([readLocalAccounts(root), readLocalAccounts(root)]);
expect(reports[0]).toEqual(reports[1]);
expect(mocks.decryptDatabase).toHaveBeenCalledTimes(1);
});
it('reports an unreadable WAL instead of reading a stale base image', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
const file = path.join(root, PRIMARY);
await mkdir(`${file}-wal`);
const report = await readLocalAccounts(root);
expect(report.accounts).toEqual([]);
expect(report.failures).toMatchObject([{ path: file, reason: 'read-failed' }]);
expect(report.failures[0]!.error).toBeDefined();
});
it('reports missing schema columns instead of accepting quoted column names as identities', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
const file = path.join(root, PRIMARY);
const db = new SqliteDatabase(file);
try {
await db.exec('ALTER TABLE login_table DROP COLUMN "1001"');
} finally {
await db.close();
}
const report = await readLocalAccounts(root);
expect(report.accounts).toEqual([]);
expect(report.failures).toMatchObject([{ path: file, reason: 'query-failed' }]);
expect(report.failures[0]!.error).toBeDefined();
});
it('reports no accounts when the file cannot be decrypted, and retries later', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
mocks.detectAlgorithm.mockReturnValue(null);
await expect(readLocalAccounts(root)).resolves.toEqual({
accounts: [],
failures: [{ path: path.join(root, PRIMARY), reason: 'undecryptable' }],
});
mocks.detectAlgorithm.mockReturnValue({ pageHmac: 'sha1', kdfHmac: 'sha512' });
const file = path.join(root, PRIMARY);
await utimes(file, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000));
await expect(readLocalAccounts(root)).resolves.toEqual({
accounts: [{ uin: '10001', uid: 'u_a', nickname: 'Alice' }],
failures: [],
});
});
it('names an unreadable login.db instead of reporting "no accounts"', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
mocks.detectAlgorithm.mockReturnValue(null);
// A login.db that cannot be decrypted is not the same as a machine with
// no accounts, and the caller has to be able to tell them apart.
await expect(readLocalAccounts(root)).resolves.toEqual({
accounts: [],
failures: [{ path: path.join(root, PRIMARY), reason: 'undecryptable' }],
});
});
it('keeps an unreadable sidecar from hiding the accounts a good database has', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']], [['10002', 'u_b', 'Bob']]);
const secondary = path.join(root, SECONDARY);
const bogus = Buffer.alloc(8192, 7);
mocks.detectAlgorithm.mockImplementation((image: Buffer) =>
image[0] === 7 ? null : { pageHmac: 'sha1', kdfHmac: 'sha512' },
);
await writeFile(secondary, bogus);
const report = await readLocalAccounts(root);
expect(report.accounts.map((account) => account.uin)).toEqual(['10001']);
expect(report.failures).toEqual([{ path: secondary, reason: 'undecryptable' }]);
});
it('skips rows that carry no usable identity', async () => {
const root = await trackedRoot([
['10001', 'u_a', 'Alice'],
['10002', '', 'Broken'],
['', 'u_d', 'Nameless'],
['../10001', 'u_e', 'Invalid UIN'],
]);
await expect(readLocalAccounts(root)).resolves.toEqual({
accounts: [{ uin: '10001', uid: 'u_a', nickname: 'Alice' }],
failures: [],
});
});
it('reports no accounts when login.db is missing', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-login-'));
roots.push(root);
// Neither candidate file exists: nothing cached, and nothing to report.
await expect(readLocalAccounts(root)).resolves.toEqual({ accounts: [], failures: [] });
});
});

View File

@@ -0,0 +1,51 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import path from 'node:path';
import { qqDataRoots, qqDataRootsForPid } from '../src/qq-account/paths';
const files = vi.hoisted(() => ({ read: vi.fn() }));
vi.mock('node:fs', () => ({ readFileSync: files.read }));
const platform = process.platform;
beforeEach(() => {
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
});
afterEach(() => {
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
files.read.mockReset();
});
describe('account data root isolation', () => {
it('uses the client HOME and honours its XDG configuration', () => {
files.read.mockReturnValue('HOME=/clients/a\0IGNORED=value\0');
expect(qqDataRootsForPid(42)).toEqual([path.join('/clients/a', '.config', 'QQ')]);
files.read.mockReturnValue('HOME=/clients/a\0XDG_CONFIG_HOME=/clients/config\0');
expect(qqDataRootsForPid(42)).toEqual([path.join('/clients/config', 'QQ')]);
});
it('does not guess a HOME when the client environment has none', () => {
files.read.mockReturnValue('OTHER=value\0');
expect(qqDataRootsForPid(42)).toEqual([]);
});
it('reports no root for an exited process', () => {
files.read.mockImplementation(() => {
throw Object.assign(new Error('gone'), { code: 'ENOENT' });
});
expect(qqDataRootsForPid(42)).toEqual([]);
});
it('surfaces permission failures instead of reading another user directory', () => {
const error = Object.assign(new Error('denied'), { code: 'EACCES' });
files.read.mockImplementation(() => {
throw error;
});
expect(() => qqDataRootsForPid(42)).toThrow(error);
});
it('uses only the configured Windows data root', () => {
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
files.read.mockReturnValue('[UserDataSet]\nUserDataSavePath=D:\\QQ\\Tencent Files\n');
expect(qqDataRoots()).toEqual(['D:\\QQ\\Tencent Files']);
expect(files.read).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,106 @@
import { describe, expect, it } from 'vitest';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import {
accountDirName,
loginDbPaths,
ntMsgDbPath,
tencentFilesRootFromUserDataInfo,
} from '../src/qq-account/paths';
const IS_WINDOWS = process.platform === 'win32';
describe('QQ data paths', () => {
it('derives the Linux account directory from the account uid', () => {
// md5(md5("u_test_account") + "nt_kernel")
expect(accountDirName('u_test_account')).toBe('nt_qq_7b9b3c3f2cf89e087b2e024777ea5f5f');
});
it('lists the login.db locations of the current platform', () => {
const root = 'root';
const windows = path.join(root, 'nt_qq', 'global', 'nt_db', 'login.db');
expect(loginDbPaths(root)).toEqual(
IS_WINDOWS ? [windows] : [path.join(root, 'global', 'nt_db', 'login.db'), windows],
);
});
it('locates an account database per platform', () => {
const root = 'root';
const account = { uin: '10001', uid: 'u_test_account' };
expect(ntMsgDbPath(root, account)).toBe(
IS_WINDOWS
? path.join(root, '10001', 'nt_qq', 'nt_db', 'nt_msg.db')
: path.join(root, 'nt_qq_7b9b3c3f2cf89e087b2e024777ea5f5f', 'nt_db', 'nt_msg.db'),
);
});
});
describe('Windows data root detection', () => {
/** Recreate `<Public>/Documents/Tencent/QQ/UserDataInfo.ini` for a fake home. */
async function withUserDataInfo(
contents: string,
run: (home: string) => Promise<void> | void,
): Promise<void> {
const base = await mkdtemp(path.join(os.tmpdir(), 'snowluma-ini-'));
try {
const home = path.join(base, 'user');
const ini = path.join(base, 'Public', 'Documents', 'Tencent', 'QQ', 'UserDataInfo.ini');
await mkdir(path.dirname(ini), { recursive: true });
await writeFile(ini, contents, 'utf8');
await run(home);
} finally {
await rm(base, { recursive: true, force: true });
}
}
it('reads UserDataSavePath from the ini QQ itself writes', async () => {
await withUserDataInfo(
'[UserDataSet]\nUserDataSavePath=D:\\Tencent\\Tencent Files\n',
(home) => {
expect(tencentFilesRootFromUserDataInfo(home)).toBe('D:\\Tencent\\Tencent Files');
},
);
});
it('appends the Tencent Files segment when the ini stops one level short', async () => {
await withUserDataInfo('[UserDataSet]\nUserDataSavePath=D:\\Tencent\n', (home) => {
expect(tencentFilesRootFromUserDataInfo(home)).toBe('D:\\Tencent\\Tencent Files');
});
});
it('ignores other sections and the UserDataSavePathType key', async () => {
await withUserDataInfo(
[
'[UserDataImportSet]',
'OldVerDataPath=D:\\Legacy\\Tencent Files',
'[UserDataSet]',
'UserDataSavePathType=2',
'UserDataSavePath=E:\\Current\\Tencent Files',
'',
].join('\n'),
(home) => {
expect(tencentFilesRootFromUserDataInfo(home)).toBe('E:\\Current\\Tencent Files');
},
);
});
it('reports nothing when the ini is missing', async () => {
const base = await mkdtemp(path.join(os.tmpdir(), 'snowluma-ini-'));
try {
expect(tencentFilesRootFromUserDataInfo(path.join(base, 'absent'))).toBeNull();
} finally {
await rm(base, { recursive: true, force: true });
}
});
it('reports nothing when the ini has no usable path', async () => {
await withUserDataInfo('[UserDataSet]\nUserDataSavePath=\n', (home) => {
expect(tencentFilesRootFromUserDataInfo(home)).toBeNull();
});
});
});

View File

@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest';
import { detectAccountLogins } from '../src/qq-account/detect';
/**
* Account detection against a real QQ data directory.
*
* Point `SNOWLUMA_QQ_DATA_ROOT` at one (for example `~/.config/QQ`) to run
* these; without it they are skipped, which is what CI and any machine without
* the client do. They are the only check that exercises login.db as QQ actually
* writes it, together with the holder probe on the databases it currently holds.
*/
const REAL_DATA_ROOT = process.env.SNOWLUMA_QQ_DATA_ROOT;
describe('account detection against real client data', () => {
it.runIf(Boolean(REAL_DATA_ROOT))('reads the accounts and their processes', async () => {
const accounts = await detectAccountLogins([REAL_DATA_ROOT!]);
expect(accounts.length).toBeGreaterThan(0);
for (const account of accounts) {
expect(account.uin).toMatch(/^\d{5,10}$/);
expect(account.uid).toMatch(/^u_/);
if (account.pid !== null) {
expect(Number.isInteger(account.pid)).toBe(true);
expect(() => process.kill(account.pid!, 0)).not.toThrow();
}
}
});
});

View File

@@ -0,0 +1,324 @@
import { describe, expect, it } from 'vitest';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { SqliteDatabase } from '@snowluma/sqlite';
import {
DATABASE_HEADER_SIZE,
decryptDatabase,
detectAlgorithm,
type SqlcipherAlgorithm,
} from '../src/qq-account/sqlcipher';
import {
FIXTURE_HEADER_SIZE,
FIXTURE_PAGE_SIZE,
FIXTURE_PASSPHRASE,
FIXTURE_WAL_FRAME_HEADER_SIZE,
FIXTURE_WAL_HEADER_SIZE,
encryptImage,
encryptWal,
reserveBytes,
walChecksum,
type FixtureAlgorithm,
} from './qq-account-fixtures';
const SHA1_SHA512: FixtureAlgorithm = { pageHmac: 'sha1', kdfHmac: 'sha512' };
/**
* Reserved space SQLite is told about for an encrypted database: room for the
* IV plus the largest page digest. SQLCipher's own reserve always fits inside
* it, which is why the tail of every page is disposable.
*/
const HEADER_RESERVED_BYTES = 80;
/** Offset of one frame in a `-wal` buffer. */
function frameOffset(index: number): number {
return FIXTURE_WAL_HEADER_SIZE + index * (FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE);
}
/** Last frame index a merge may have applied, or -1 when nothing was committed. */
function lastCommitFrame(wal: Buffer, maxFrameIndex = frameCount(wal) - 1): number {
let last = -1;
for (let index = 0; index <= maxFrameIndex; index++) {
if (wal.readUInt32BE(frameOffset(index) + 4) !== 0) {
last = index;
}
}
return last;
}
function frameCount(wal: Buffer): number {
const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE;
return Math.floor((wal.length - FIXTURE_WAL_HEADER_SIZE) / frameSize);
}
/** Frames up to and including the last commit, i.e. what a merge should apply. */
function committedFrames(wal: Buffer, maxFrameIndex?: number): number {
return lastCommitFrame(wal, maxFrameIndex) + 1;
}
/** Database size the last applicable commit declares. */
function lastCommitSize(wal: Buffer, maxFrameIndex?: number): number {
return wal.readUInt32BE(frameOffset(lastCommitFrame(wal, maxFrameIndex)) + 4);
}
/** Page content as the last applicable commit left it, keyed by page number. */
function committedPages(wal: Buffer, maxFrameIndex?: number): Map<number, Buffer> {
const pages = new Map<number, Buffer>();
const last = lastCommitFrame(wal, maxFrameIndex);
const size = lastCommitSize(wal, maxFrameIndex);
for (let index = 0; index <= last; index++) {
const pageNumber = wal.readUInt32BE(frameOffset(index));
if (pageNumber >= 1 && pageNumber <= size) {
pages.set(
pageNumber,
wal.subarray(
frameOffset(index) + FIXTURE_WAL_FRAME_HEADER_SIZE,
frameOffset(index + 1),
),
);
}
}
return pages;
}
/** Compare one merged page against the page a frame carried. */
function expectPageMatches(
merged: Buffer,
expectedPage: Buffer,
pageNumber: number,
algorithm: FixtureAlgorithm,
): void {
const reserve = reserveBytes(algorithm);
const start = (pageNumber - 1) * FIXTURE_PAGE_SIZE;
// Page 1's SQLite header carries the fields the merge keeps consistent with
// the assembled image (change counter, page count, journal mode), so only the
// page body is compared there.
const bodyStart = pageNumber === 1 ? 100 : 0;
expect(merged.subarray(start + bodyStart, start + FIXTURE_PAGE_SIZE - reserve)).toEqual(
expectedPage.subarray(bodyStart, FIXTURE_PAGE_SIZE - reserve),
);
expect(
merged
.subarray(start + FIXTURE_PAGE_SIZE - reserve, start + FIXTURE_PAGE_SIZE)
.equals(Buffer.alloc(reserve)),
).toBe(true);
}
/** A plaintext image with the header fields the merge keeps consistent. */
function plaintextImage(pageCount: number, marker = 0): Buffer {
const image = Buffer.alloc(pageCount * FIXTURE_PAGE_SIZE);
for (let page = 0; page < pageCount; page++) {
for (let offset = 0; offset < FIXTURE_PAGE_SIZE - HEADER_RESERVED_BYTES; offset++) {
image[page * FIXTURE_PAGE_SIZE + offset] = (page * 31 + offset + marker) % 251;
}
}
image.write('SQLite format 3\0', 0, 'latin1');
image.writeUInt16BE(FIXTURE_PAGE_SIZE, 16);
image[18] = 1;
image[19] = 1;
image[20] = HEADER_RESERVED_BYTES;
image[21] = 64;
image[22] = 32;
image[23] = 32;
image.writeUInt32BE(7, 24);
image.writeUInt32BE(pageCount, 28);
image.writeUInt32BE(7, 92);
return image;
}
/** A real SQLite database in WAL mode, plus the sidecar SQLite wrote for it. */
async function realWalDatabase(
directory: string,
inserts: string[][],
): Promise<{ image: Buffer; wal: Buffer; db: SqliteDatabase }> {
const file = path.join(directory, 'source.db');
const db = new SqliteDatabase(file);
await db.exec('PRAGMA wal_autocheckpoint = 0');
await db.exec('CREATE TABLE t(value TEXT)');
for (const [value] of inserts) {
await db.prepare('INSERT INTO t VALUES (?)').run(value);
}
return { image: await readFile(file), wal: await readFile(`${file}-wal`), db };
}
describe('SQLCipher page decryption', () => {
it('round-trips a page image and normalizes the header', () => {
const plain = plaintextImage(3);
plain[18] = 2; // stored as a WAL-mode database, like QQ writes them
plain[19] = 2;
const encrypted = encryptImage(plain, SHA1_SHA512);
expect(detectAlgorithm(encrypted, FIXTURE_PASSPHRASE)).toEqual(SHA1_SHA512);
const decrypted = decryptDatabase(encrypted, null, FIXTURE_PASSPHRASE, SHA1_SHA512);
expect(decrypted).not.toBeNull();
const expected = Buffer.from(plain);
expected[18] = 1;
expected[19] = 1;
expected.writeUInt32BE(3, 28);
expected.writeUInt32BE(7, 92);
expect(decrypted!.image.equals(expected)).toBe(true);
expect(decrypted!.walFrames).toBe(0);
});
it('probes the algorithm pair instead of assuming one', () => {
const plain = plaintextImage(2);
for (const algorithm of [
{ pageHmac: 'sha256', kdfHmac: 'sha256' },
{ pageHmac: 'sha512', kdfHmac: 'sha1' },
{ pageHmac: 'none', kdfHmac: 'sha512' },
] satisfies SqlcipherAlgorithm[]) {
const encrypted = encryptImage(plain, algorithm);
expect(detectAlgorithm(encrypted, FIXTURE_PASSPHRASE)).toEqual(algorithm);
expect(
decryptDatabase(encrypted, null, FIXTURE_PASSPHRASE, algorithm)!.image.equals(
plain,
),
).toBe(true);
}
});
it('rejects a wrong passphrase and a file that is too short', () => {
const encrypted = encryptImage(plaintextImage(2), SHA1_SHA512);
expect(detectAlgorithm(encrypted, 'wrong-passphrase')).toBeNull();
expect(
detectAlgorithm(Buffer.alloc(DATABASE_HEADER_SIZE + 512), FIXTURE_PASSPHRASE),
).toBeNull();
expect(decryptDatabase(Buffer.alloc(64), null, FIXTURE_PASSPHRASE, SHA1_SHA512)).toBeNull();
});
});
describe('SQLCipher WAL folding', () => {
it('reproduces the frame checksums SQLite itself wrote', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-wal-'));
try {
const { wal, db } = await realWalDatabase(directory, [['a'], ['b']]);
const littleEndian = wal.readUInt32BE(0) === 0x377f0682;
const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE;
expect((wal.length - FIXTURE_WAL_HEADER_SIZE) % frameSize).toBe(0);
const header = walChecksum(
[0, 0],
[wal.subarray(0, FIXTURE_WAL_HEADER_SIZE - 8)],
littleEndian,
);
expect(header).toEqual([wal.readUInt32BE(24), wal.readUInt32BE(28)]);
let running = header;
for (
let offset = FIXTURE_WAL_HEADER_SIZE;
offset + frameSize <= wal.length;
offset += frameSize
) {
const frame = wal.subarray(offset, offset + FIXTURE_WAL_FRAME_HEADER_SIZE);
running = walChecksum(
running,
[
frame.subarray(0, 8),
wal.subarray(offset + FIXTURE_WAL_FRAME_HEADER_SIZE, offset + frameSize),
],
littleEndian,
);
expect(running).toEqual([frame.readUInt32BE(16), frame.readUInt32BE(20)]);
}
await db.close();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it('folds every committed frame into the decrypted image', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-wal-'));
try {
const { image, wal, db } = await realWalDatabase(directory, [['a'], ['b']]);
const encryptedImage = encryptImage(image, SHA1_SHA512);
const encryptedWal = encryptWal(wal, encryptedImage, SHA1_SHA512);
const decrypted = decryptDatabase(
encryptedImage,
encryptedWal,
FIXTURE_PASSPHRASE,
SHA1_SHA512,
);
expect(decrypted!.walFrames).toBe(committedFrames(wal));
expect(decrypted!.image.length).toBe(lastCommitSize(wal) * FIXTURE_PAGE_SIZE);
// Every page a committed frame carried has to arrive as it was written,
// apart from the on-disk IV/HMAC region the encryptor owns.
for (const [pageNumber, page] of committedPages(wal)) {
expectPageMatches(decrypted!.image, page, pageNumber, SHA1_SHA512);
}
await db.close();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it('keeps the intact prefix of a WAL torn by a running client', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-wal-'));
try {
const { image, wal, db } = await realWalDatabase(directory, [['a'], ['b']]);
const encryptedImage = encryptImage(image, SHA1_SHA512);
const encryptedWal = encryptWal(wal, encryptedImage, SHA1_SHA512);
const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE;
const frameCount = (wal.length - FIXTURE_WAL_HEADER_SIZE) / frameSize;
// Shred the last frame's page: everything after the previous commit
// must be dropped rather than half-applied.
encryptedWal[encryptedWal.length - 8] ^= 0xff;
const decrypted = decryptDatabase(
encryptedImage,
encryptedWal,
FIXTURE_PASSPHRASE,
SHA1_SHA512,
);
expect(decrypted).not.toBeNull();
expect(decrypted!.walFrames).toBeLessThan(frameCount);
// Frames up to the tear survive; the merge still stops at the last
// commit they contain rather than applying a partial transaction.
expect(decrypted!.walFrames).toBe(committedFrames(wal, frameCount - 2));
// Everything the surviving commits wrote has to be in the image.
for (const [pageNumber, page] of committedPages(wal, frameCount - 2)) {
expectPageMatches(decrypted!.image, page, pageNumber, SHA1_SHA512);
}
await db.close();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
});
describe('SQLCipher header handling', () => {
it('keeps the client header opaque and stores the salt at the start of page 1', () => {
const plain = plaintextImage(2);
const encrypted = encryptImage(plain, SHA1_SHA512);
const header = encrypted.subarray(0, FIXTURE_HEADER_SIZE);
expect(header.equals(Buffer.alloc(FIXTURE_HEADER_SIZE))).toBe(true);
expect(
encrypted
.subarray(FIXTURE_HEADER_SIZE + 16, FIXTURE_HEADER_SIZE + 48)
.equals(plain.subarray(16, 48)),
).toBe(false);
});
});

View File

@@ -133,6 +133,20 @@ afterEach(async () => {
tmpDir = null;
});
describe('QqHookClient login wait lifecycle', () => {
it('rejects when closed while resuming a completed connection', async () => {
const client = new QqHookClient(12345);
vi.spyOn(client, 'connect').mockResolvedValue({
pid: 12345,
pipeName: 'test',
recvPipe: false,
});
const waiting = client.waitForLogin();
client.close();
await expect(waiting).rejects.toThrow('closed');
});
});
describe('listLiveLinuxPipePids', () => {
it('ignores stale-looking control socket names when the probe rejects them', async () => {
const runtimeDir = await makeRuntimeDir();

View File

@@ -1,724 +0,0 @@
import { EventEmitter } from 'events';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getLogLevel, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
const execMock = vi.hoisted(() => vi.fn());
const httpGetMock = vi.hoisted(() => vi.fn());
const httpsGetMock = vi.hoisted(() => vi.fn());
vi.mock('child_process', () => ({ exec: execMock }));
vi.mock('http', () => ({
default: { get: httpGetMock },
get: httpGetMock,
}));
vi.mock('https', () => ({
default: { get: httpsGetMock },
get: httpsGetMock,
}));
import { probeQqLoginInfo } from '../src/qq-port-probe';
const originalPlatform = process.platform;
const EXEC_OPTIONS = { timeout: 1500, killSignal: 'SIGKILL' };
const PTLOGIN_HEADERS = {
Host: 'localhost.ptlogin2.qq.com',
Referer: 'https://xui.ptlogin2.qq.com/',
Cookie: 'pt_local_token=0',
};
type ExecCallback = (error: Error | null, result?: { stdout: string; stderr: string }) => void;
type RequestLike = EventEmitter & { destroy: ReturnType<typeof vi.fn> };
function setPlatform(platform: string): void {
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
}
function mockExec(replies: Record<string, string | Error>): void {
execMock.mockImplementation((command: string, _options: unknown, callback: ExecCallback) => {
const reply = replies[command];
if (reply === undefined) {
callback(new Error(`unexpected command ${command}`));
return;
}
if (reply instanceof Error) {
callback(reply);
return;
}
callback(null, { stdout: reply, stderr: '' });
});
}
function execCommands(): string[] {
return execMock.mock.calls.map((call) => String(call[0]));
}
function ssLine(port: number, pid: number, owner: 'comma' | 'paren' = 'comma'): string {
const tag = owner === 'comma' ? `pid=${pid},fd=9` : `pid=${pid}`;
return `LISTEN 0 128 127.0.0.1:${port} 0.0.0.0:* users:(("qq",${tag}))`;
}
function netstatLine(localAddr: string, pid: number): string {
return ` TCP ${localAddr} 0.0.0.0:0 LISTENING ${pid}`;
}
function jsonp(accounts: unknown[]): string {
return `ptui_getuins_CB(${JSON.stringify(accounts)});`;
}
function requestStub(): RequestLike {
const req = new EventEmitter() as RequestLike;
req.destroy = vi.fn();
return req;
}
function replyBody(body: string | ReadonlyArray<string | Buffer>) {
return (
_url: string,
_options: unknown,
onResponse: (res: EventEmitter) => void,
): RequestLike => {
const req = requestStub();
const res = new EventEmitter();
onResponse(res);
const chunks = typeof body === 'string' ? [body] : body;
for (const chunk of chunks) {
res.emit('data', chunk);
}
res.emit('end');
return req;
};
}
function replyError(error: Error) {
return (): RequestLike => {
const req = requestStub();
queueMicrotask(() => req.emit('error', error));
return req;
};
}
beforeEach(() => {
execMock.mockReset();
httpGetMock.mockReset();
httpsGetMock.mockReset();
setPlatform('linux');
});
afterEach(() => {
setPlatform(originalPlatform);
vi.useRealTimers();
});
describe('probeQqLoginInfo — unix listing', () => {
it('returns null when ss cannot list sockets', async () => {
mockExec({ 'ss -tlnp': new Error('ss: not found') });
await expect(probeQqLoginInfo(3310)).resolves.toBeNull();
expect(execCommands()).toEqual(['ss -tlnp']);
expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS);
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
it('reports a logged-out identity when the PID has no sockets and pgrep is below 6', async () => {
mockExec({
'ss -tlnp': 'State Recv-Q Send-Q Local Address:Port Peer Address:Port\n',
'pgrep -c qq': '5\n',
});
await expect(probeQqLoginInfo(3311)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
expect(execCommands()).toEqual(['ss -tlnp', 'pgrep -c qq']);
expect(execMock.mock.calls[1]?.[1]).toEqual(EXEC_OPTIONS);
});
it('treats a pgrep count of 0 as logged out', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '0\n',
});
await expect(probeQqLoginInfo(3312)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
});
it('treats a non-numeric pgrep count as 0 and therefore logged out', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': 'qq: no process found\n',
});
await expect(probeQqLoginInfo(3313)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
});
it('returns null when there are no sockets and pgrep is 6 or higher', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '6\n',
});
await expect(probeQqLoginInfo(3314)).resolves.toBeNull();
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '9\n',
});
await expect(probeQqLoginInfo(3315)).resolves.toBeNull();
});
it('does not treat a failed pgrep as logged out', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': new Error('pgrep: exit 1'),
});
await expect(probeQqLoginInfo(3316)).resolves.toBeNull();
});
it('uses the first listening port as a logged-out hint when no Ptlogin port is present', async () => {
mockExec({
'ss -tlnp': [ssLine(9218, 4410), ssLine(18000, 4410)].join('\n'),
'pgrep -c qq': ' 4 \n',
});
await expect(probeQqLoginInfo(4410)).resolves.toEqual({
port: 9218,
uin: '',
identityKnown: false,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
it('returns null for non-Ptlogin ports when the QQ process count is ambiguous', async () => {
mockExec({
'ss -tlnp': ssLine(9218, 4411),
'pgrep -c qq': '7\n',
});
await expect(probeQqLoginInfo(4411)).resolves.toBeNull();
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
it('collects unique ports from ss lines that name the PID with either pid=N, or pid=N)', async () => {
mockExec({
'ss -tlnp': [
'LISTEN 0 128 127.0.0.1:4301users:(("qq",pid=4412,fd=1))',
ssLine(4301, 4412, 'comma'),
ssLine(4301, 4412, 'comma'),
ssLine(4305, 4412, 'paren'),
ssLine(4305, 9999, 'comma'),
'ESTAB 0 0 127.0.0.1:4307 127.0.0.1:443 users:(("qq",pid=4412,fd=4))',
].join('\n'),
});
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '10001', nickname: 'Ada' }])));
await expect(probeQqLoginInfo(4412)).resolves.toEqual({
port: 4301,
uin: '10001',
nickName: 'Ada',
identityKnown: true,
});
expect(httpsGetMock).toHaveBeenCalledTimes(2);
expect(httpsGetMock.mock.calls[0]?.[0]).toBe(
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
);
});
});
describe('probeQqLoginInfo — Ptlogin identity', () => {
it('reads a single account from an odd Ptlogin port over https', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5501) });
httpsGetMock.mockImplementation(
replyBody(
jsonp([
{
uin: 319427101,
account: 1,
nickname: 'Snow',
extra: 'ignored',
},
]),
),
);
await expect(probeQqLoginInfo(5501)).resolves.toEqual({
port: 4301,
uin: '319427101',
nickName: 'Snow',
identityKnown: true,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).toHaveBeenCalledTimes(2);
expect(httpsGetMock.mock.calls[0]?.[1]).toEqual({
headers: PTLOGIN_HEADERS,
timeout: 500,
rejectUnauthorized: false,
});
});
it('reads a single account from an even Ptlogin port over http', async () => {
mockExec({ 'ss -tlnp': ssLine(4302, 5502) });
httpGetMock.mockImplementation(
replyBody(
jsonp([
{
account: '2880036470',
},
]),
),
);
await expect(probeQqLoginInfo(5502)).resolves.toEqual({
port: 4302,
uin: '2880036470',
nickName: '',
identityKnown: true,
});
expect(httpsGetMock).not.toHaveBeenCalled();
expect(httpGetMock).toHaveBeenCalledTimes(2);
expect(httpGetMock.mock.calls[0]?.[0]).toBe(
'http://127.0.0.1:4302/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
);
expect(httpGetMock.mock.calls[0]?.[1]).toEqual({
headers: PTLOGIN_HEADERS,
timeout: 500,
});
});
it('probes every documented odd Ptlogin port over https', async () => {
for (const port of [4301, 4303, 4305, 4307, 4309]) {
execMock.mockReset();
httpsGetMock.mockReset();
httpGetMock.mockReset();
mockExec({ 'ss -tlnp': ssLine(port, 5510) });
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '70001', nickname: 'Odd' }])));
await expect(probeQqLoginInfo(5510)).resolves.toEqual({
port,
uin: '70001',
nickName: 'Odd',
identityKnown: true,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(String(httpsGetMock.mock.calls[0]?.[0])).toBe(
`https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`,
);
}
});
it('probes every documented even Ptlogin port over http when no odd port is listening', async () => {
for (const port of [4302, 4304, 4306, 4308, 4310]) {
execMock.mockReset();
httpsGetMock.mockReset();
httpGetMock.mockReset();
mockExec({ 'ss -tlnp': ssLine(port, 5511) });
httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '70002', nickname: 'Even' }])));
await expect(probeQqLoginInfo(5511)).resolves.toEqual({
port,
uin: '70002',
nickName: 'Even',
identityKnown: true,
});
expect(httpsGetMock).not.toHaveBeenCalled();
expect(String(httpGetMock.mock.calls[0]?.[0])).toBe(
`http://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`,
);
}
});
it('prefers odd Ptlogin ports and never falls through to even ones', async () => {
mockExec({
'ss -tlnp': [ssLine(4302, 5520), ssLine(4301, 5520)].join('\n'),
});
httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED')));
await expect(probeQqLoginInfo(5520)).resolves.toBeNull();
expect(httpsGetMock).toHaveBeenCalled();
expect(httpGetMock).not.toHaveBeenCalled();
expect(execCommands()).toEqual(['ss -tlnp']);
});
it('tries the next odd Ptlogin port after the first one fails', async () => {
mockExec({
'ss -tlnp': [ssLine(4301, 5521), ssLine(4305, 5521)].join('\n'),
});
httpsGetMock
.mockImplementationOnce(replyBody('<html>nope</html>'))
.mockImplementationOnce(replyBody('<html>nope</html>'))
.mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }])))
.mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }])));
await expect(probeQqLoginInfo(5521)).resolves.toEqual({
port: 4305,
uin: '188888',
nickName: 'Next',
identityKnown: true,
});
expect(httpsGetMock.mock.calls.map((call) => call[0])).toEqual([
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
]);
});
it('stops after the first Ptlogin port that yields a single account', async () => {
mockExec({
'ss -tlnp': [ssLine(4303, 5522), ssLine(4309, 5522)].join('\n'),
});
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '42', nickname: 'First' }])));
await expect(probeQqLoginInfo(5522)).resolves.toEqual({
port: 4303,
uin: '42',
nickName: 'First',
identityKnown: true,
});
expect(httpsGetMock).toHaveBeenCalledTimes(2);
});
it('uses account when uin is missing or empty, including a numeric 0 uin', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5530) });
httpsGetMock
.mockImplementationOnce(
replyBody(jsonp([{ uin: 0, account: 314159, nickname: 'Zero' }])),
)
.mockImplementationOnce(
replyBody(jsonp([{ uin: '', account: '314159', nickname: 'Zero' }])),
);
await expect(probeQqLoginInfo(5530)).resolves.toEqual({
port: 4301,
uin: '314159',
nickName: 'Zero',
identityKnown: true,
});
});
it('returns an empty uin when the single account has neither uin nor account', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5531) });
httpsGetMock.mockImplementation(replyBody('[{"nickname":"Anon"}]'));
await expect(probeQqLoginInfo(5531)).resolves.toEqual({
port: 4301,
uin: '',
nickName: 'Anon',
identityKnown: true,
});
});
it('keeps the shorter of the two pt_get_uins snapshots', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5540) });
httpsGetMock
.mockImplementationOnce(
replyBody(
jsonp([
{ uin: '11', nickname: 'A' },
{ uin: '22', nickname: 'B' },
]),
),
)
.mockImplementationOnce(replyBody(jsonp([{ uin: '33', nickname: 'Cora' }])));
await expect(probeQqLoginInfo(5540)).resolves.toEqual({
port: 4301,
uin: '33',
nickName: 'Cora',
identityKnown: true,
});
});
it('keeps the first snapshot when both pt_get_uins calls have one account', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5541) });
httpsGetMock
.mockImplementationOnce(replyBody(jsonp([{ uin: '100', nickname: 'Left' }])))
.mockImplementationOnce(replyBody(jsonp([{ uin: '200', nickname: 'Right' }])));
await expect(probeQqLoginInfo(5541)).resolves.toEqual({
port: 4301,
uin: '100',
nickName: 'Left',
identityKnown: true,
});
});
it('accepts a single account from the second fetch when the first fetch is unusable', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5542) });
httpsGetMock
.mockImplementationOnce(replyError(new Error('ECONNRESET')))
.mockImplementationOnce(replyBody(jsonp([{ uin: '9090', nickname: 'Retry' }])));
await expect(probeQqLoginInfo(5542)).resolves.toEqual({
port: 4301,
uin: '9090',
nickName: 'Retry',
identityKnown: true,
});
});
it('returns null for an empty pt_get_uins array and does not consult pgrep', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5550) });
httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([]);'));
await expect(probeQqLoginInfo(5550)).resolves.toBeNull();
expect(execCommands()).toEqual(['ss -tlnp']);
});
it('returns null when both snapshots have more than one account', async () => {
mockExec({ 'ss -tlnp': ssLine(4304, 5551) });
httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '1' }, { uin: '2' }])));
await expect(probeQqLoginInfo(5551)).resolves.toBeNull();
});
it('returns null when both fetches fail to parse a pt_get_uins body', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5552) });
httpsGetMock.mockImplementation(replyBody('not-jsonp'));
await expect(probeQqLoginInfo(5552)).resolves.toBeNull();
});
it('returns null when both fetches error', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5553) });
httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED')));
await expect(probeQqLoginInfo(5553)).resolves.toBeNull();
});
it('destroys the request and returns null when both fetches time out', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5554) });
const seen: RequestLike[] = [];
httpsGetMock.mockImplementation(() => {
const req = requestStub();
seen.push(req);
queueMicrotask(() => req.emit('timeout'));
return req;
});
await expect(probeQqLoginInfo(5554)).resolves.toBeNull();
expect(seen).toHaveLength(2);
expect(seen[0]?.destroy).toHaveBeenCalledTimes(1);
expect(seen[1]?.destroy).toHaveBeenCalledTimes(1);
});
it('joins chunked pt_get_uins bodies including Buffer pieces', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5560) });
httpsGetMock.mockImplementation(
replyBody([
'ptui_getuins_CB([',
Buffer.from('{"uin":"10001","nickname":"Ada"}'),
']);',
]),
);
await expect(probeQqLoginInfo(5560)).resolves.toEqual({
port: 4301,
uin: '10001',
nickName: 'Ada',
identityKnown: true,
});
});
it('treats a nickname that closes the JSONP array early as unusable', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5561) });
httpsGetMock.mockImplementation(
replyBody('ptui_getuins_CB([{"nickname":"a]b","uin":"1"}]);'),
);
await expect(probeQqLoginInfo(5561)).resolves.toBeNull();
});
});
describe('probeQqLoginInfo — win32 listing', () => {
beforeEach(() => {
setPlatform('win32');
});
it('returns null when netstat cannot list sockets', async () => {
mockExec({ 'netstat -ano': new Error('netstat: access denied') });
await expect(probeQqLoginInfo(6610)).resolves.toBeNull();
expect(execCommands()).toEqual(['netstat -ano']);
expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS);
});
it('counts QQ.exe rows from tasklist when netstat lists no sockets for the PID', async () => {
mockExec({
'netstat -ano': [
'Active Connections',
'',
' Proto Local Address Foreign Address State PID',
netstatLine('127.0.0.1:4301', 1),
].join('\n'),
'tasklist /fi "imagename eq QQ.exe" /nh': [
'QQ.exe 100 Console 1 10,000 K',
'QQ.exe 101 Console 1 11,000 K',
'explorer.exe 200 Console 1 9,000 K',
].join('\n'),
});
await expect(probeQqLoginInfo(6611)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
expect(execCommands()).toEqual(['netstat -ano', 'tasklist /fi "imagename eq QQ.exe" /nh']);
});
it('returns null when tasklist reports 6 or more QQ.exe rows and the PID has no sockets', async () => {
mockExec({
'netstat -ano': '',
'tasklist /fi "imagename eq QQ.exe" /nh': [
'QQ.exe 1',
'QQ.exe 2',
'QQ.exe 3',
'qq.exe 4',
'QQ.EXE 5',
'QQ.exe 6',
].join('\n'),
});
await expect(probeQqLoginInfo(6612)).resolves.toBeNull();
});
it('does not treat a failed tasklist as logged out', async () => {
mockExec({
'netstat -ano': '',
'tasklist /fi "imagename eq QQ.exe" /nh': new Error('tasklist: exit 1'),
});
await expect(probeQqLoginInfo(6613)).resolves.toBeNull();
});
it('parses netstat rows for the owning PID and skips short or portless lines', async () => {
mockExec({
'netstat -ano': [
'Active Connections',
' TCP 127.0.0.1:4301 LISTENING',
' TCP 127.0.0.1 0.0.0.0:0 LISTENING 6620',
netstatLine('10.0.0.8:18000', 1),
netstatLine('127.0.0.1:4303', 6620),
netstatLine('[::1]:4303', 6620),
netstatLine('127.0.0.1:9218', 6620),
].join('\n'),
});
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '20002', nickname: 'Win' }])));
await expect(probeQqLoginInfo(6620)).resolves.toEqual({
port: 4303,
uin: '20002',
nickName: 'Win',
identityKnown: true,
});
expect(httpsGetMock).toHaveBeenCalledTimes(2);
expect(httpsGetMock.mock.calls[0]?.[0]).toBe(
'https://127.0.0.1:4303/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
);
});
it('uses the first netstat port as a logged-out hint when no Ptlogin port is present', async () => {
mockExec({
'netstat -ano': [
netstatLine('127.0.0.1:18000', 6630),
netstatLine('127.0.0.1:18001', 6630),
].join('\n'),
'tasklist /fi "imagename eq QQ.exe" /nh': 'QQ.exe 100\n',
});
await expect(probeQqLoginInfo(6630)).resolves.toEqual({
port: 18000,
uin: '',
identityKnown: false,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
});
describe('probeQqLoginInfo — overall deadline', () => {
it('returns null and warns after 5000ms if listing never finishes', async () => {
vi.useFakeTimers();
execMock.mockImplementation(() => undefined);
const previousLevel = getLogLevel();
setLogLevel('info');
const warnings: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'LoginProbe' && entry.level === 'warn') {
warnings.push(entry.message);
}
});
try {
const pending = probeQqLoginInfo(9001);
let settled: unknown = 'pending';
void pending.then((value) => {
settled = value;
});
await vi.advanceTimersByTimeAsync(4999);
expect(settled).toBe('pending');
await vi.advanceTimersByTimeAsync(1);
await expect(pending).resolves.toBeNull();
expect(warnings).toEqual(['login check timed out: PID=9001']);
} finally {
unsubscribe();
setLogLevel(previousLevel);
}
});
it('does not warn when the probe finishes before the deadline', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '2\n',
});
const previousLevel = getLogLevel();
setLogLevel('info');
const warnings: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'LoginProbe') {
warnings.push(entry.message);
}
});
try {
await expect(probeQqLoginInfo(9002)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
await probeQqLoginInfo(9002);
expect(warnings).toEqual(['login probe: PID=9002 result=no-ports ports=0 processes=2']);
} finally {
unsubscribe();
setLogLevel(previousLevel);
}
});
it('abandons a hung Ptlogin fetch at the overall deadline', async () => {
vi.useFakeTimers();
mockExec({ 'ss -tlnp': ssLine(4301, 9003) });
httpsGetMock.mockImplementation(() => requestStub());
const pending = probeQqLoginInfo(9003);
await vi.advanceTimersByTimeAsync(5000);
await expect(pending).resolves.toBeNull();
});
});

View File

@@ -1,65 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const execMock = vi.hoisted(() => vi.fn());
const socketCtorMock = vi.hoisted(() =>
vi.fn(function MockSocket() {
throw new Error('interactive QQ probe must not run');
}),
);
vi.mock('child_process', () => ({ exec: execMock }));
vi.mock('net', () => ({
default: { Socket: socketCtorMock },
Socket: socketCtorMock,
}));
import { probeQqLoginInfo } from '../src/qq-port-probe';
describe('probeQqLoginInfo — bounded execution', () => {
beforeEach(() => {
vi.useFakeTimers();
execMock.mockReset();
socketCtorMock.mockClear();
});
afterEach(() => {
vi.useRealTimers();
});
it('allows a later probe after a timed-out attempt', async () => {
execMock.mockImplementation(() => undefined);
const first = probeQqLoginInfo(4242);
await vi.advanceTimersByTimeAsync(10_000);
await expect(first).resolves.toBeNull();
execMock
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '', stderr: '' });
})
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '1\n', stderr: '' });
});
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
});
it('keeps background identity discovery passive', async () => {
execMock
.mockImplementationOnce((_command, _options, callback) => {
callback(null, {
stdout: 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n',
stderr: '',
});
})
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '8\n', stderr: '' });
});
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
expect(socketCtorMock).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,152 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { hasLowProcessIntegrity, type NativeRuntimeIntegrity } from '../src/runtime-integrity';
const native = vi.hoisted(() => ({ load: vi.fn(), error: vi.fn() }));
vi.mock('../src/injector', () => ({
getNativeHookAddon: native.load,
getNativeHookLoadError: native.error,
}));
const platform = process.platform;
const sample = (): NativeRuntimeIntegrity => ({
pid: process.pid,
executablePath: process.execPath,
process: { status: 'ok', rid: 8192 },
file: { status: 'ok', label: null },
});
beforeEach(() => {
vi.resetModules();
vi.resetAllMocks();
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
});
afterEach(() => {
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
});
describe('runtime integrity diagnostics', () => {
it('warns only for a successfully read process token below Medium', () => {
const available = { ...sample(), status: 'available' as const };
for (const rid of [0, 4096]) {
expect(hasLowProcessIntegrity({ ...available, process: { status: 'ok', rid } })).toBe(
true,
);
}
for (const rid of [8192, 8448, 12288, 16384]) {
expect(
hasLowProcessIntegrity({
...available,
process: { status: 'ok', rid },
file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } },
}),
).toBe(false);
}
expect(hasLowProcessIntegrity({ status: 'unsupported' })).toBe(false);
expect(hasLowProcessIntegrity({ status: 'unavailable', error: 'unavailable' })).toBe(false);
expect(
hasLowProcessIntegrity({
...available,
process: { status: 'error', operation: 'OpenProcessToken', code: 5 },
}),
).toBe(false);
});
it('keeps one startup snapshot for logging and all WebUI polls', async () => {
const read = vi.fn().mockResolvedValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrityAsync: read });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
const pending = getRuntimeIntegrity();
expect(getRuntimeIntegrity()).toBe(pending);
const first = await pending;
expect(first).toMatchObject({
status: 'available',
process: { rid: 8192 },
file: { label: null },
});
read.mockResolvedValue({
...sample(),
file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } },
});
expect(await getRuntimeIntegrity()).toBe(first);
expect(read).toHaveBeenCalledTimes(1);
});
it.each(['process', 'file'])(
'retains %s query errors and the other successful result',
async (field) => {
native.load.mockReturnValue({
getRuntimeIntegrityAsync: async () => ({
...sample(),
[field]: { status: 'error', operation: 'Win32Query', code: 5 },
}),
});
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(await getRuntimeIntegrity()).toMatchObject({
status: 'available',
[field]: { status: 'error', operation: 'Win32Query', code: 5 },
});
},
);
it('reports old addons as unavailable rather than Medium', async () => {
native.load.mockReturnValue({});
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(await getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: expect.stringContaining('不支持'),
});
});
it('retains the loader error for the startup log', async () => {
native.load.mockReturnValue(null);
native.error.mockReturnValue('dlopen failed: incompatible binary');
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(await getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: 'dlopen failed: incompatible binary',
});
});
it.each([
null,
{ ...sample(), pid: process.pid + 1 },
{ ...sample(), process: { status: 'ok', rid: -1 } },
{ ...sample(), file: { status: 'ok', label: { rid: 4096, inherited: 'yes', policy: 1 } } },
])('rejects malformed or wrong-process native results', async (result) => {
native.load.mockReturnValue({ getRuntimeIntegrityAsync: async () => result });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(await getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: expect.stringContaining('无效数据'),
});
});
it('preserves rejected errors without repeatedly probing on WebUI polls', async () => {
const read = vi
.fn()
.mockRejectedValueOnce(new Error('allocation failed'))
.mockResolvedValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrityAsync: read });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(await getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: 'allocation failed',
});
expect(await getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: 'allocation failed',
});
expect(read).toHaveBeenCalledTimes(1);
});
it('does not load the addon on non-Windows hosts', async () => {
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(await getRuntimeIntegrity()).toEqual({ status: 'unsupported' });
expect(native.load).not.toHaveBeenCalled();
});
});

View File

@@ -1,13 +1,29 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.14.22",
"version": "2.0.0",
"private": true,
"type": "module",
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
"./semver": {
"types": "./src/semver.ts",
"default": "./src/semver.ts"
},
"./version": {
"types": "./src/version.ts",
"default": "./src/version.ts"
},
"./native-path": {
"types": "./src/native-path.ts",
"default": "./src/native-path.ts"
},
"./errors": {
"types": "./src/errors.ts",
"default": "./src/errors.ts"
},
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
@@ -24,6 +40,10 @@
"types": "./src/env.ts",
"default": "./src/env.ts"
},
"./notification-templates": {
"types": "./src/notification-templates.ts",
"default": "./src/notification-templates.ts"
},
"./single-flight-cache": {
"types": "./src/single-flight-cache.ts",
"default": "./src/single-flight-cache.ts"
@@ -79,12 +99,17 @@
},
"devDependencies": {
"@types/node": "catalog:",
"@types/semver": "7.7.1",
"typescript": "catalog:",
"vitest": "^4.1.4"
},
"dependencies": {
"@zxcvbn-ts/core": "^4.1.2",
"@zxcvbn-ts/language-common": "^4.1.3",
"@zxcvbn-ts/language-en": "^4.1.1"
"@zxcvbn-ts/language-en": "^4.1.1",
"semver": "7.7.4"
},
"engines": {
"node": ">=24"
}
}

View File

@@ -0,0 +1,3 @@
export function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}

View File

@@ -1,26 +1,9 @@
const HEX_CHARS = '0123456789abcdef';
const HEX_CHARS_UPPER = '0123456789ABCDEF';
export function toHex(data: Uint8Array | Buffer): string {
let h = '';
for (const b of data) {
h += HEX_CHARS[b >> 4];
h += HEX_CHARS[b & 0xf];
}
return h;
return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString('hex');
}
export function toHexUpper(data: Uint8Array | Buffer): string {
let h = '';
for (const b of data) {
h += HEX_CHARS_UPPER[b >> 4];
h += HEX_CHARS_UPPER[b & 0xf];
}
return h;
return toHex(data).toUpperCase();
}
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {

View File

@@ -1,3 +1,4 @@
import { errorMessage } from './errors';
import fs from 'node:fs';
import path from 'node:path';
import { sanitizeLogLine } from './log-sanitize';
@@ -1237,7 +1238,3 @@ export async function _resetFileTransportForTesting(): Promise<void> {
function isMissing(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}

View File

@@ -0,0 +1,21 @@
import { existsSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
export function resolveRuntimeNativePath(fileName: string): string | null {
// Bundled releases and workspace sources each own their native inputs.
for (const directory of [
path.join(moduleDir, 'native'),
path.resolve(moduleDir, '..', '..', 'runtime', 'native'),
]) {
const candidate = path.join(directory, fileName);
if (existsSync(candidate)) {
return candidate;
}
}
return null;
}

View File

@@ -0,0 +1,14 @@
export const DEFAULT_WEBHOOK_BODY = `{
"title": "账号状态通知:{event}",
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**进程状态**:{status}\\n**时间**:{time}"
}`;
export const DEFAULT_EMAIL_SUBJECT = '账号{event}:{nickname} ({uin})';
export const DEFAULT_EMAIL_BODY = `账号状态发生了改变。
昵称:{nickname}
QQ号:{uin}
当前状态:{event}
进程状态:{status}
时间:{time}`;

View File

@@ -1,5 +1,6 @@
import fs from 'fs';
import path from 'path';
import { isObject } from './coerce';
export interface RuntimeConfig {
webuiPort?: number;
@@ -395,10 +396,6 @@ function parseBoolValue(raw: unknown): boolean | undefined {
return undefined;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isErrnoCode(error: unknown, code: string): boolean {
return error instanceof Error && 'code' in error && error.code === code;
}

View File

@@ -0,0 +1,28 @@
import parse from 'semver/functions/parse.js';
/** Parse a canonical SemVer string; tag prefixes belong at the GitHub boundary. */
export function parseVersion(value: unknown) {
if (typeof value !== 'string') {
return null;
}
const parsed = parse(value);
if (!parsed) {
return null;
}
const canonical = parsed.version + (parsed.build.length ? `+${parsed.build.join('.')}` : '');
return value === canonical ? parsed : null;
}
export function compareVersions(a: string, b: string): number {
const left = parseVersion(a);
const right = parseVersion(b);
if (!left || !right) {
throw new TypeError('Invalid semantic version');
}
return left.compare(right);
}

View File

@@ -1,19 +1,4 @@
/**
* Single-flight + TTL memoization.
*
* Concentrates the "don't refetch what's fresh, and don't stampede the same
* key with concurrent loads" pattern that was hand-rolled (slightly
* differently each time) across the codebase — e.g. `ContactsApi`'s group
* member-list cache and the WebUI update-check. Each copy re-implemented the
* same fiddly trio: a TTL freshness check, an in-flight promise map to
* de-dupe concurrent callers, and `finally`-cleanup of that map. Getting any
* of the three subtly wrong (forgetting the `finally`, caching an error,
* racing the timestamp) is a real hazard — so it lives in one place.
*
* The underlying concern is Tencent risk-control: a busy OneBot client can
* fan out one uncached OIDB fetch per inbound message, and sustained bursts
* trip a ban. TTL + single-flight collapse that fan-out.
*/
/** TTL caching and request deduplication to limit repeated upstream requests. */
export interface SingleFlightCacheOptions<K, V> {
/** Freshness window in ms. A cached entry older than this is reloaded. */
@@ -70,31 +55,35 @@ export class SingleFlightCache<K, V> {
return existing;
}
const task = (async () => {
try {
const value = await this.load(key);
const load = async (): Promise<V> => {
const value = await this.load(key);
if (this.shouldCache(value)) {
this.fresh.set(key, { at: this.now(), value });
}
if (this.inflight.get(key) === task && this.shouldCache(value)) {
this.fresh.set(key, { at: this.now(), value });
}
return value;
} finally {
return value;
};
const task = load().finally(() => {
if (this.inflight.get(key) === task) {
this.inflight.delete(key);
}
})();
});
this.inflight.set(key, task);
return task;
}
/** Drop a cached entry. Does not abort an in-flight load. */
/** Detach the entry and its pending load; existing callers still settle. */
invalidate(key: K): void {
this.fresh.delete(key);
this.inflight.delete(key);
}
/** Drop all cached entries. Does not abort in-flight loads. */
/** Detach all entries and pending loads without aborting existing callers. */
clear(): void {
this.fresh.clear();
this.inflight.clear();
}
}

View File

@@ -0,0 +1,3 @@
import manifest from '../../../package.json' with { type: 'json' };
export const APP_VERSION = manifest.version;

View File

@@ -2,6 +2,12 @@ import { describe, expect, it } from 'vitest';
import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex';
describe('hex', () => {
it('encodes only the selected byte view', () => {
const bytes = Uint8Array.of(0xff, 0x01, 0xab, 0xff);
expect(toHex(bytes.subarray(1, 3))).toBe('01ab');
expect(toHexUpper(Buffer.from(bytes).subarray(1, 3))).toBe('01AB');
});
it('toHex / toHexUpper render bytes as zero-padded hex', () => {
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
expect(toHex(b)).toBe('000fa0ff');

View File

@@ -0,0 +1,73 @@
import { describe, expect, it } from 'vitest';
import { compareVersions, parseVersion } from '../src/semver';
describe('parseVersion', () => {
it.each([
'0.0.0',
'1.2.3',
'1.2.3-rc.1',
'1.2.3-alpha-beta',
'1.2.3+001.build',
'1.2.3-rc.1+build.2',
])('accepts canonical SemVer and preserves its full value: %s', (version) => {
expect(parseVersion(version)?.raw).toBe(version);
});
it.each([
undefined,
null,
123,
{},
'',
'1.2',
'1.2.3.4',
'1.2.x',
'01.2.3',
'1.02.3',
'1.2.03',
'1.2.3-01',
'1.2.3-rc.01',
'1.2.3-rc..1',
'1.2.3-rc_1',
'1.2.3+build..1',
'1.2.3+build_1',
'v1.2.3',
'V1.2.3',
'=1.2.3',
' 1.2.3',
'1.2.3\n',
])('rejects noncanonical input without coercion: %j', (version) => {
expect(parseVersion(version)).toBeNull();
});
});
describe('compareVersions', () => {
it.each([
['1.2.3', '1.2.3', 0],
['1.2.4', '1.2.3', 1],
['1.2.3', '1.2.4', -1],
['1.10.0', '1.9.0', 1],
['2.0.0', '1.9.9', 1],
['3.0.0', '1.0.0', 1],
['1.0.0', '3.0.0', -1],
['1.2.3', '1.2.3-rc.1', 1],
['1.2.3-rc.1', '1.2.3', -1],
['1.2.3-rc.1', '1.2.3-rc.1', 0],
['1.2.3-rc.1', '1.2.3-rc.2', -1],
['1.2.3-rc.2', '1.2.3-rc.1', 1],
['1.2.3-rc.10', '1.2.3-rc.2', 1],
['1.2.3-rc.1+build.2', '1.2.3-rc.1+build.1', 0],
['1.2.3-alpha-beta', '1.2.3-alpha', 1],
['2.0.0-rc.1', '1.9.9', 1],
] as const)('compareVersions(%j, %j) === %s', (a, b, expected) => {
expect(compareVersions(a, b)).toBe(expected);
});
it.each(['1.2', '1.2.3.9', '1.2.x', '', 'v1.2.3', 'V1.2.3', '01.2.3', '1.2.3-rc.01'])(
'rejects invalid versions instead of guessing: %j',
(version) => {
expect(() => compareVersions(version, '1.2.3')).toThrow();
expect(() => compareVersions('1.2.3', version)).toThrow();
},
);
});

View File

@@ -13,6 +13,46 @@ function deferred<T>() {
}
describe('SingleFlightCache', () => {
it.each(['invalidate', 'clear'] as const)(
'%s detaches pending loads from the cache',
async (operation) => {
const old = deferred<string>();
const current = deferred<string>();
const load = vi
.fn()
.mockReturnValueOnce(old.promise)
.mockReturnValueOnce(current.promise);
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
const first = cache.get('key');
cache[operation]('key');
const second = cache.get('key');
expect(load).toHaveBeenCalledTimes(2);
old.resolve('old');
await expect(first).resolves.toBe('old');
expect(cache.get('key')).toBe(second);
current.resolve('current');
await expect(second).resolves.toBe('current');
await expect(cache.get('key')).resolves.toBe('current');
expect(load).toHaveBeenCalledTimes(2);
},
);
it('does not let a late invalidated result overwrite a newer value', async () => {
const old = deferred<string>();
const load = vi.fn().mockReturnValueOnce(old.promise).mockResolvedValue('current');
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
const first = cache.get('key');
cache.invalidate('key');
await expect(cache.get('key')).resolves.toBe('current');
old.resolve('old');
await first;
await expect(cache.get('key')).resolves.toBe('current');
});
it('caches within the TTL and reloads once expired', async () => {
let clock = 1000;
const load = vi.fn(async (k: string) => `${k}@${clock}`);
@@ -147,4 +187,18 @@ describe('SingleFlightCache', () => {
await cache.get('b');
expect(load).toHaveBeenCalledTimes(5);
});
it('allows retry when a loader throws before returning its promise', async () => {
const load = vi
.fn<() => Promise<string>>()
.mockImplementationOnce(() => {
throw new Error('failed before request');
})
.mockResolvedValue('recovered');
const cache = createSingleFlightCache({ ttlMs: 1000, load });
await expect(cache.get('key')).rejects.toThrow('failed before request');
await expect(cache.get('key')).resolves.toBe('recovered');
expect(load).toHaveBeenCalledTimes(2);
});
});

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.14.22",
"version": "2.0.0",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -34,7 +34,7 @@
},
"scripts": {
"build": "vite build",
"build:all": "cross-env BUILD_WEBUI=true vite build",
"build:all": "cross-env BUILD_WEBUI=true pnpm build",
"dev": "tsx src/index.ts",
"test": "vitest run",
"test:watch": "vitest",
@@ -48,7 +48,9 @@
"@snowluma/protocol": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/websocket": "workspace:*",
"otpauth": "^9.5.1"
"fflate": "^0.8.3",
"otpauth": "^9.5.1",
"tar": "^7.5.22"
},
"devDependencies": {
"@hono/node-server": "^1.19.15",
@@ -60,6 +62,10 @@
"typescript": "catalog:",
"vite": "catalog:",
"vite-plugin-cp": "^6.0.3",
"vitest": "^4.1.4"
"vitest": "^4.1.4",
"@snowluma/sqlite": "workspace:*"
},
"engines": {
"node": ">=24"
}
}

View File

@@ -25,6 +25,7 @@ import {
} from '@snowluma/protocol/services/qidian/fetch-corp-info';
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
import { GetGroupShareLink } from '@snowluma/protocol/oidb-services/contacts/get-group-share-link';
import {
SendTuwenArk,
type SendTuwenArkParams,
@@ -157,6 +158,20 @@ export class ContactsApi {
return GetGroupRecommendArk.invoke(this.ctx, { groupId });
}
getGroupShareLink(
groupId: number,
needShortUrl = true,
srcId = 73,
additionalParam = '',
): Promise<string> {
return GetGroupShareLink.invoke(this.ctx, {
groupId,
needShortUrl,
srcId,
additionalParam,
});
}
/** Send a custom 图文 ark card to a C2C peer or group (0xdc2_34). */
sendTuwenArk(params: SendTuwenArkParams): Promise<void> {
return SendTuwenArk.invoke(this.ctx, params);

View File

@@ -318,7 +318,7 @@ export class ExtrasApi {
),
);
}, receiptTimeoutMs);
timeout.unref?.();
timeout.unref();
}),
]));

View File

@@ -10,7 +10,6 @@ import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { protobuf_encode } from '@snowluma/proton';
import { promises as fsp } from 'fs';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
@@ -40,10 +39,6 @@ import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
const log = createLogger('GroupFile');
function asBridge(ctx: BridgeContext): Bridge {
return ctx as unknown as Bridge;
}
// ─────────────── public result types ───────────────
export interface GroupFileInfo {
@@ -296,7 +291,7 @@ export class GroupFileApi {
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
const bridge = this.ctx;
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
// local disk path and stream-hash it — the (up to 4 GiB) file is never
@@ -430,7 +425,7 @@ export class GroupFileApi {
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
const bridge = this.ctx;
// Stage onto a local disk path + stream-hash — the (up to 4 GiB) file is
// never buffered in RAM. headLimit = MD5_HEAD_LIMIT yields the offline-file
// md510MCheckSum in the same single pass.
@@ -724,8 +719,7 @@ export class GroupFileApi {
}
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
const selfUid = await resolveSelfUid(this.ctx);
void userId;
return GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
}
@@ -784,8 +778,7 @@ export class GroupFileApi {
}
async getPrivatePttUrl(node: MediaIndexNode): Promise<string> {
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
const selfUid = await resolveSelfUid(this.ctx);
return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node });
}
@@ -794,8 +787,7 @@ export class GroupFileApi {
}
async getPrivateVideoUrl(node: MediaIndexNode): Promise<string> {
const bridge = asBridge(this.ctx);
const selfUid = await resolveSelfUid(bridge);
const selfUid = await resolveSelfUid(this.ctx);
return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node });
}
}

View File

@@ -2,6 +2,7 @@ import {
commentQzoneMsg,
deleteQzoneMsg,
getQzoneFeeds,
getQzoneMsgDetail,
getQzoneMsgList,
publishQzoneMsg,
setQzoneBlack,
@@ -10,6 +11,7 @@ import {
uploadQzoneImageFromSource,
type QzoneCommentResult,
type QzoneFeedsResult,
type QzoneMsgDetailResult,
type QzoneMsgListResult,
type QzonePublishResult,
type QzoneUpdateRightResult,
@@ -36,6 +38,18 @@ export class QzoneApi {
return getQzoneMsgList(cookieObject, uin, pos, num);
}
/** 获取说说详情和一页评论。省略 targetUin 时使用当前账号。 */
async getMsgDetail(
tid: string,
targetUin?: number,
pos = 0,
num = 20,
): Promise<QzoneMsgDetailResult> {
const uin = targetUin === undefined ? this.ctx.identity.uin : String(targetUin);
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneMsgDetail(cookieObject, uin, tid, pos, num);
}
/**
* 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。
* 始终以机器人自己的身份拉取好友动态。

View File

@@ -1,20 +1,4 @@
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) {
return Math.trunc(value);
}
if (typeof value === 'bigint') {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
return 0;
}
export { toInt } from '@snowluma/protocol/oidb-services/shared';
// The bot's-own-UID resolver is the single source of truth in @snowluma/protocol
// (a Bridge satisfies its BridgeContext slice). Re-exported here so the existing

View File

@@ -17,3 +17,12 @@ export interface BridgeInterface extends BridgeContext {
* QQ has not emitted its cache notification since SnowLuma attached. */
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null;
}
export interface BridgeSessionListener {
started?(uin: string, bridge: BridgeInterface): void;
closed?(uin: string, bridge: BridgeInterface, pid: number): void;
}
export interface BridgeSessionSource {
subscribeSessions(listener: BridgeSessionListener): () => void;
}

View File

@@ -16,19 +16,19 @@ const log = createLogger('Bridge');
const runtimeLog = createLogger('Bridge.Runtime');
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
interface ProcessConnection {
pid: number;
client: PacketSender;
receiveHealthy: boolean;
}
export class Bridge implements BridgeInterface {
readonly identity: IdentityService;
private pids_ = new Set<number>();
private readonly receiveHealthByPid_ = new Map<number, boolean>();
/** Packet senders keyed by their owning QQ process. Keeping the sender and
* PID together is what makes disconnect fallback deterministic: a sender
* can never outlive the PID that supplied it. */
private readonly packetClientsByPid_ = new Map<number, PacketSender>();
/** Insertion order tracks login recency; the newest connection sends packets. */
private readonly connections = new Map<number, ProcessConnection>();
readonly events = new BridgeEventBus();
readonly apis: ApiHub;
private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
private packetClientPid_: number | null = null;
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
@@ -36,11 +36,13 @@ export class Bridge implements BridgeInterface {
// Per-account dedup for QQ NT's already-deduped system pushes (#137).
private readonly sysMsgDedup_ = new SysMsgDedup();
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
private disposed_ = false;
private disposePromise_: Promise<void> | null = null;
private readonly pendingPackets_ = new Set<Promise<void>>();
private rosterWarmupStarted_ = false;
private rosterWarmupSettled_ = false;
private rosterWarmupResult_: RosterWarmupResult | null = null;
private readonly rosterWarmupWaiters_: Array<(result: RosterWarmupResult) => void> = [];
private settleRosterWarmup!: (result: RosterWarmupResult) => void;
private readonly rosterWarmup = new Promise<RosterWarmupResult>((resolve) => {
this.settleRosterWarmup = resolve;
});
constructor(identity: IdentityService) {
this.identity = identity;
@@ -142,39 +144,23 @@ export class Bridge implements BridgeInterface {
});
}
dispose(): void {
this.disposed_ = true;
dispose(): Promise<void> {
if (this.disposePromise_) {
return this.disposePromise_;
}
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
this.pids_.clear();
this.receiveHealthByPid_.clear();
this.packetClientsByPid_.clear();
this.packetClient_ = null;
this.packetClientPid_ = null;
this.connections.clear();
this.onlineClients_ = null;
try {
this.identity.close();
} finally {
// A close failure must remain visible to the caller, but must not leave
// event subscribers attached to a Bridge that Manager already removed.
this.events.clear();
}
}
/** Legacy two-step setter retained for external compatibility. It assigns
* the sender to the most recently attached PID when one exists. New
* BridgeManager code uses bindPid() for an atomic transition. */
setPacketClient(client: PacketSender): void {
this.packetClient_ = client;
const pids = [...this.pids_];
const pid = pids.length > 0 ? pids[pids.length - 1]! : null;
this.packetClientPid_ = pid;
if (pid !== null) {
this.packetClientsByPid_.set(pid, client);
}
this.maybeStartRosterWarmup();
this.disposePromise_ = (async () => {
try {
await Promise.allSettled(this.pendingPackets_);
await this.identity.close();
} finally {
this.events.clear();
}
})();
return this.disposePromise_;
}
registerCmd(cmd: string, parser: CmdParser): void {
@@ -185,34 +171,18 @@ export class Bridge implements BridgeInterface {
return this.pipeline.handlesCmd(cmd);
}
/** Attach a process without a sender. Retained for compatibility; the
* manager uses bindPid() for the atomic PID+sender transition. Re-attaching
* deliberately refreshes recency. */
attachPid(pid: number): void {
this.pids_.delete(pid);
this.pids_.add(pid);
// A fresh/rebound login starts UNKNOWN-but-compatible. The receive
// watchdog only flips this false after observing QQ's own heartbeat and
// then missing the full stale + confirmation window.
this.receiveHealthByPid_.set(pid, true);
}
/** Atomically attach a process and make its sender the active sender.
* Set insertion order is the recency order used for fallback. */
bindPid(pid: number, client: PacketSender): void {
const previousPid = this.packetClientPid_;
const previousClient = this.packetClient_;
this.attachPid(pid);
this.packetClientsByPid_.set(pid, client);
this.packetClient_ = client;
this.packetClientPid_ = pid;
const previous = this.activeConnection;
this.connections.delete(pid);
// A new login stays healthy until the watchdog confirms a failure.
this.connections.set(pid, { pid, client, receiveHealthy: true });
if (previousPid !== pid || previousClient !== client) {
if (previous?.pid !== pid || previous.client !== client) {
runtimeLog.trace(
'bridge_sender_fact event=selected uin=%j pid=%d previousPid=%j',
this.identity.uin,
pid,
previousPid,
previous?.pid ?? null,
);
}
@@ -222,88 +192,70 @@ export class Bridge implements BridgeInterface {
/** @internal BridgeManager lookup used when an incoming packet is the first
* observation that a live PID changed UIN. */
packetClientForPid(pid: number): PacketSender | null {
return this.packetClientsByPid_.get(pid) ?? null;
return this.connections.get(pid)?.client ?? null;
}
detachPid(pid: number): void {
this.pids_.delete(pid);
this.receiveHealthByPid_.delete(pid);
this.packetClientsByPid_.delete(pid);
const wasActive = this.activePid === pid;
this.connections.delete(pid);
const active = this.activeConnection;
if (this.packetClientPid_ !== pid) {
// An unscoped legacy sender cannot be associated with a particular PID.
// It is safe to retain while another PID exists, but never after the
// Bridge becomes empty.
if (this.pids_.size === 0) {
this.packetClient_ = null;
this.packetClientPid_ = null;
}
return;
if (wasActive && active) {
runtimeLog.trace(
'bridge_sender_fact event=fallback uin=%j detachedPid=%d fallbackPid=%d',
this.identity.uin,
pid,
active.pid,
);
log.debug(
'packet sender changed: UIN=%s PID=%d→%d',
this.identity.uin,
pid,
active.pid,
);
}
this.selectFallbackPacketClient(pid);
}
hasPid(pid: number): boolean {
return this.pids_.has(pid);
return this.connections.has(pid);
}
get empty(): boolean {
return this.pids_.size === 0;
return this.connections.size === 0;
}
private get activeConnection(): ProcessConnection | undefined {
return [...this.connections.values()].at(-1);
}
get activePid(): number | null {
if (this.packetClientPid_ !== null && this.pids_.has(this.packetClientPid_)) {
return this.packetClientPid_;
}
const pids = [...this.pids_];
return pids.length > 0 ? pids[pids.length - 1]! : null;
return this.activeConnection?.pid ?? 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;
return [...this.connections.values()].some((connection) => connection.receiveHealthy);
}
setPidReceiveHealthy(pid: number, healthy: boolean): void {
if (!this.pids_.has(pid)) {
const connection = this.connections.get(pid);
if (!connection) {
throw new Error(`Bridge receive-health invariant violated: PID=${pid} is not attached`);
}
this.receiveHealthByPid_.set(pid, healthy);
connection.receiveHealthy = healthy;
}
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
return this.onlineClients_;
}
whenRosterWarmupSettled(): Promise<RosterWarmupResult> {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
return Promise.resolve(this.rosterWarmupResult_);
}
this.maybeStartRosterWarmup();
return new Promise((resolve) => {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
resolve(this.rosterWarmupResult_);
return;
}
this.rosterWarmupWaiters_.push(resolve);
});
return this.rosterWarmup;
}
onPacket(pkt: PacketInfo): Promise<void> {
return this.pipeline.process(pkt);
if (this.disposePromise_) {
return Promise.reject(new Error('Bridge is disposed'));
}
const work = this.identity.initialization.then(() => this.pipeline.process(pkt));
this.pendingPackets_.add(work);
void work.finally(() => this.pendingPackets_.delete(work)).catch(() => undefined);
return work;
}
rememberUploadedFile(meta: UploadedFileMeta): void {
@@ -344,7 +296,9 @@ export class Bridge implements BridgeInterface {
body: Uint8Array,
timeoutMs = packetTimeoutMs(),
): Promise<SendPacketResult> {
if (!this.packetClient_) {
const connection = this.activeConnection;
if (!connection) {
return runWithTraceRequest(() => {
const startedAt = Date.now();
runtimeLog.trace(() => [
@@ -377,11 +331,7 @@ export class Bridge implements BridgeInterface {
}
const startedAt = Date.now();
const result = await this.packetClient_.sendPacket(
serviceCmd,
Buffer.from(body),
timeoutMs,
);
const result = await connection.client.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
const elapsed = Date.now() - startedAt;
const respLen = result.responseData ? result.responseData.length : 0;
@@ -410,52 +360,12 @@ export class Bridge implements BridgeInterface {
return result;
}
private selectFallbackPacketClient(detachedPid: number): void {
const pids = [...this.pids_];
for (let index = pids.length - 1; index >= 0; index -= 1) {
const fallbackPid = pids[index]!;
const fallback = this.packetClientsByPid_.get(fallbackPid);
if (!fallback) {
continue;
}
this.packetClient_ = fallback;
this.packetClientPid_ = fallbackPid;
runtimeLog.trace(
'bridge_sender_fact event=fallback uin=%j detachedPid=%d fallbackPid=%d',
this.identity.uin,
detachedPid,
fallbackPid,
);
log.debug(
'packet sender fallback: UIN=%s detached PID=%d fallback PID=%d',
this.identity.uin,
detachedPid,
fallbackPid,
);
return;
}
this.packetClient_ = null;
this.packetClientPid_ = null;
if (this.pids_.size > 0) {
log.warn(
'packet sender unavailable after PID detach: UIN=%s detached PID=%d remaining PIDs=%d',
this.identity.uin,
detachedPid,
this.pids_.size,
);
}
}
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
private maybeStartRosterWarmup(): void {
if (this.disposed_ || this.rosterWarmupStarted_ || !this.packetClient_) {
if (this.disposePromise_ || this.rosterWarmupStarted_ || this.empty) {
return;
}
@@ -468,7 +378,7 @@ export class Bridge implements BridgeInterface {
void this.runRosterWarmup().then(
(result) =>
this.settleRosterWarmup(
this.disposed_ ? { friendsLoaded: false, groupsLoaded: false } : result,
this.disposePromise_ ? { friendsLoaded: false, groupsLoaded: false } : result,
),
(err) => {
log.warn(
@@ -481,25 +391,17 @@ export class Bridge implements BridgeInterface {
);
}
private settleRosterWarmup(result: RosterWarmupResult): void {
if (this.rosterWarmupSettled_) {
return;
}
this.rosterWarmupSettled_ = true;
this.rosterWarmupResult_ = result;
const waiters = this.rosterWarmupWaiters_.splice(0);
for (const resolve of waiters) {
resolve(result);
}
}
private stillOpen(): boolean {
return !this.disposed_;
return this.disposePromise_ === null;
}
private async runRosterWarmup(): Promise<RosterWarmupResult> {
await this.identity.initialization;
if (this.disposePromise_) {
return { friendsLoaded: false, groupsLoaded: false };
}
const uin = this.identity.uin;
const selfUin = parseInt(uin, 10) || 0;
let selfResolved = false;

View File

@@ -4,41 +4,83 @@ import type { PacketInfo } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from './bridge';
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string, bridge: Bridge) => void;
interface QQSession {
bridge: Bridge;
}
import type { BridgeSessionListener, BridgeSessionSource } from './bridge-interface';
const log = createLogger('Bridge');
const packetLog = createLogger('Bridge.Packet');
const runtimeLog = createLogger('Bridge.Runtime');
export class BridgeManager {
private sessions_ = new Map<string, QQSession>();
private pidToUin_ = new Map<number, string>();
export class BridgeManager implements BridgeSessionSource {
private readonly bridges = new Map<string, Bridge>();
private readonly pidToUin_ = new Map<number, string>();
private readonly closingSessions_ = new Map<string, Set<Promise<void>>>();
private readonly sessionSubscriptions = new Set<{ listener: BridgeSessionListener }>();
private disposal_: Promise<void> | null = null;
private sessionStartedListeners_: SessionStartedCallback[] = [];
private sessionClosedListeners_: SessionClosedCallback[] = [];
/** Additive subscription: every observer (OneBotManager, NotificationManager,
* …) receives every session edge. (Was a single `set*Callback` setter —
* converted to N listeners so a second observer can't clobber the first.)
* The close edge now carries the bridge too, since callers read the last
* nickname before it is disposed. */
addSessionStartedListener(cb: SessionStartedCallback): void {
this.sessionStartedListeners_.push(cb);
/** Hook callbacks remain synchronous; shutdown awaits every detached account. */
dispose(): Promise<void> {
this.sessionSubscriptions.clear();
// Finish synchronous lifecycle observers before collecting detached sessions.
return (this.disposal_ ??= Promise.resolve().then(() => this.disposeSessions()));
}
addSessionClosedListener(cb: SessionClosedCallback): void {
this.sessionClosedListeners_.push(cb);
private async disposeSessions(): Promise<void> {
for (const [uin, session] of this.bridges) {
this.closeSession(uin, session);
}
this.bridges.clear();
this.pidToUin_.clear();
const results = await Promise.allSettled(
[...this.closingSessions_.values()].flatMap((sessions) => [...sessions]),
);
const errors = results.flatMap((result) =>
result.status === 'rejected' ? [result.reason] : [],
);
if (errors.length) {
throw new AggregateError(errors, 'Bridge persistence shutdown failed');
}
}
private closeSession(uin: string, bridge: Bridge): void {
const sessions = this.closingSessions_.get(uin) ?? new Set<Promise<void>>();
const closing = bridge.dispose();
sessions.add(closing);
this.closingSessions_.set(uin, sessions);
void closing.then(
() => {
sessions.delete(closing);
if (sessions.size === 0) {
this.closingSessions_.delete(uin);
}
},
(error) => {
log.error(
'identity close failed: UIN=%s err=%s',
uin,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
},
);
}
/** Listener changes take effect on the next event. Close observers run before
* Bridge disposal, so the final process and account identity remain readable. */
subscribeSessions(listener: BridgeSessionListener): () => void {
const subscription = { listener };
this.sessionSubscriptions.add(subscription);
return () => {
this.sessionSubscriptions.delete(subscription);
};
}
private fireSessionStarted(uin: string, bridge: Bridge): void {
for (const cb of this.sessionStartedListeners_) {
for (const { listener } of [...this.sessionSubscriptions]) {
try {
cb(uin, bridge);
listener.started?.(uin, bridge);
} catch (err) {
log.warn(
'session-started listener threw: %s',
@@ -48,10 +90,10 @@ export class BridgeManager {
}
}
private fireSessionClosed(uin: string, bridge: Bridge): void {
for (const cb of this.sessionClosedListeners_) {
private fireSessionClosed(uin: string, bridge: Bridge, pid: number): void {
for (const { listener } of [...this.sessionSubscriptions]) {
try {
cb(uin, bridge);
listener.closed?.(uin, bridge, pid);
} catch (err) {
log.warn(
'session-closed listener threw: %s',
@@ -74,7 +116,7 @@ export class BridgeManager {
try {
const closed = this.detachPidFromSession(pid, uin);
const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null;
const activePid = this.bridges.get(uin)?.activePid ?? null;
if (closed) {
runtimeLog.trace(
@@ -106,6 +148,10 @@ export class BridgeManager {
}
onPidReceiveHealthChanged(pid: number, healthy: boolean): void {
if (this.disposal_) {
return;
}
const uin = this.pidToUin_.get(pid);
if (!uin) {
@@ -114,19 +160,19 @@ export class BridgeManager {
throw new Error(message);
}
const session = this.sessions_.get(uin);
const session = this.bridges.get(uin);
if (!session || !session.bridge.hasPid(pid)) {
if (!session || !session.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);
session.setPidReceiveHealthy(pid, healthy);
}
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
if (!isRealUin(uin)) {
if (this.disposal_ || !isRealUin(uin)) {
return;
}
@@ -150,14 +196,14 @@ export class BridgeManager {
uin,
previousUin,
);
const previousSession = this.sessions_.get(previousUin);
const previousSession = this.bridges.get(previousUin);
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j',
pid,
uin,
previousSession ? 'previous_session_retained' : 'previous_session_closed',
previousUin,
previousSession?.bridge.activePid ?? null,
previousSession?.activePid ?? null,
);
}
@@ -168,7 +214,7 @@ export class BridgeManager {
uin,
);
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
this.fireSessionStarted(uin, session);
}
runtimeLog.trace(
@@ -177,7 +223,7 @@ export class BridgeManager {
uin,
previousUin && previousUin !== uin ? 'rebound' : 'bound',
created,
session.bridge.activePid,
session.activePid,
Date.now() - startedAt,
);
} catch (error) {
@@ -194,6 +240,10 @@ export class BridgeManager {
}
onPacket(pkt: PacketInfo): void {
if (this.disposal_) {
return;
}
runWithTraceRequest(() => this.onPacketInContext(pkt));
}
@@ -238,13 +288,13 @@ export class BridgeManager {
// Notify session started on first real packet
if (created) {
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
this.fireSessionStarted(uin, session);
}
// Dispatch packet to bridge. The pipeline preserves synchronous parsing and
// dispatch; its promise only marks completion of any async enrichment.
handedToPipeline = true;
completion = session.bridge.onPacket(pkt);
completion = session.onPacket(pkt);
} catch (error) {
this.tracePacketFailure(
pkt,
@@ -290,7 +340,7 @@ export class BridgeManager {
uin: string,
packetClient: PacketSender,
source: 'login' | 'packet',
): { session: QQSession; created: boolean } {
): { session: Bridge; created: boolean } {
const previousUin = this.pidToUin_.get(pid);
if (previousUin && previousUin !== uin) {
@@ -305,7 +355,7 @@ export class BridgeManager {
}
const result = this.ensureSession(uin);
result.session.bridge.bindPid(pid, packetClient);
result.session.bindPid(pid, packetClient);
this.pidToUin_.set(pid, uin);
return result;
}
@@ -317,7 +367,7 @@ export class BridgeManager {
return null;
}
const session = this.sessions_.get(uin);
const session = this.bridges.get(uin);
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
@@ -325,7 +375,7 @@ export class BridgeManager {
throw new Error(message);
}
const packetClient = session.bridge.packetClientForPid(pid);
const packetClient = session.packetClientForPid(pid);
if (packetClient) {
return packetClient;
@@ -345,7 +395,7 @@ export class BridgeManager {
throw new Error(message);
}
const session = this.sessions_.get(uin);
const session = this.bridges.get(uin);
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
@@ -353,57 +403,45 @@ export class BridgeManager {
throw new Error(message);
}
if (!session.bridge.hasPid(pid)) {
if (!session.hasPid(pid)) {
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`;
log.error(message);
throw new Error(message);
}
if (!session.bridge.packetClientForPid(pid)) {
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`;
log.error(message);
throw new Error(message);
}
// Validation is complete. Mutate both sides only after the ownership
// invariant is known to hold, so a fail-fast error preserves the evidence.
this.pidToUin_.delete(pid);
session.bridge.detachPid(pid);
session.detachPid(pid);
if (!session.bridge.empty) {
if (!session.empty) {
return false;
}
this.sessions_.delete(uin);
this.bridges.delete(uin);
log.debug('session closed: UIN=%s', uin);
// Fire before dispose() so listeners can still read bridge.identity.
this.fireSessionClosed(uin, session.bridge);
session.bridge.dispose();
this.fireSessionClosed(uin, session, pid);
this.closeSession(uin, session);
return true;
}
private ensureSession(uin: string): { session: QQSession; created: boolean } {
let session = this.sessions_.get(uin);
private ensureSession(uin: string): { session: Bridge; created: boolean } {
const session = this.bridges.get(uin);
if (session) {
return { session, created: false };
}
const bridge = new Bridge(IdentityService.openForUin(uin));
session = { bridge };
this.sessions_.set(uin, session);
const closing = this.closingSessions_.get(uin);
const beforeOpen = closing ? Promise.all(closing).then(() => undefined) : undefined;
const bridge = new Bridge(IdentityService.openForUin(uin, 'data', beforeOpen));
this.bridges.set(uin, bridge);
// Each downstream consumer (e.g. OneBotInstance) subscribes to
// `bridge.events` directly via the per-kind bus — there is no longer a
// generic firehose to wire here.
return { session, created: true };
return { session: bridge, created: true };
}
getSession(uin: string): QQSession | null {
return this.sessions_.get(uin) ?? null;
}
get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_;
getBridge(uin: string): Bridge | null {
return this.bridges.get(uin) ?? null;
}
}

View File

@@ -1,2 +1,2 @@
declare const __BUILD_WEBUI__: boolean;
declare const __APP_VERSION__: string;
declare const __PACKAGED__: boolean;

View File

@@ -1,4 +1,5 @@
import { HookManager } from '@snowluma/bridge';
import { getRuntimeIntegrity, HookManager } from '@snowluma/bridge';
import { APP_VERSION } from '@snowluma/common/version';
import { configureFileTransport } from '@snowluma/common/log-file-transport';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import {
@@ -15,13 +16,20 @@ import {
runMessageStoreMigrationWorker,
} from '@snowluma/onebot/message-store-migration-worker';
import { workerData } from 'node:worker_threads';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { BridgeManager } from './bridge/manager';
import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
import { initWebUI } from './webui/server';
import { bindSystemFaceCatalog } from './sys-face-catalog';
import { readAppVersion, startNativeStageSync, tempStagePath } from './native-stage-sync';
import { startNativeStageSync, tempStagePath } from './native-stage-sync';
import { logRuntimeIntegrity } from './runtime-integrity-log';
import { RESTART_EXIT_CODE, runApplication } from './update/startup';
const log = createLogger('App');
const updateRoot =
typeof __PACKAGED__ === 'undefined' ? undefined : path.dirname(fileURLToPath(import.meta.url));
function installProcessGuards(): void {
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
@@ -51,8 +59,9 @@ async function main() {
perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN,
});
log.info('SnowLuma starting');
logRuntimeIntegrity(await getRuntimeIntegrity());
const stopNativeStageSync = startNativeStageSync({
version: readAppVersion(import.meta.url),
version: APP_VERSION,
dataDir: 'data',
tempPath: tempStagePath(),
});
@@ -68,12 +77,13 @@ async function main() {
const bridgeManager = new BridgeManager();
bindSystemFaceCatalog(bridgeManager);
const oneBotManager = new OneBotManager();
oneBotManager.bind(bridgeManager);
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
// WebUI state-push wiring: HookManager + BridgeManager edges publish
// `processes` / `qq-list` / `connections` invalidations into a bus the
// /api/state/stream SSE handler subscribes to (no REST polling required).
const stateWiring = createStateWiring();
const stateWiring = createStateWiring(bridgeManager);
const hookManager = new HookManager({
bridgeManager,
autoLoadOnDiscovery,
@@ -84,12 +94,16 @@ async function main() {
log.info('hook auto-load enabled: every discovered QQ process will be injected');
}
oneBotManager.bind(bridgeManager);
stateWiring.bindBridgeManager(bridgeManager);
// Global notification subsystem (account up/down → webhook). Bound AFTER
// OneBotManager so the nickname fallback is already populated when it observes.
const notificationManager = createNotificationManager();
// Lifecycle events identify their PID; an older process with the same UIN
// must not supply facts for a recovered account.
const notificationManager = createNotificationManager(async (uin, pid) => {
const found = (await hookManager.listProcesses()).find(
(p) => p.pid === pid && p.uin === uin,
);
return found ? { status: found.status, pid: found.pid, error: found.error } : undefined;
});
notificationManager.bind(bridgeManager);
let stopWebUI: (() => Promise<void>) | undefined;
@@ -99,7 +113,6 @@ async function main() {
process.env.SNOWLUMA_DEV_WEBUI === '1'
) {
try {
const { initWebUI } = await import('./webui/server');
const started = await initWebUI(
runtimeConfig.webuiPort || 5099,
oneBotManager,
@@ -110,6 +123,10 @@ async function main() {
tlsEnabled: runtimeConfig.webuiTls?.enabled,
trustProxy: runtimeConfig.trustProxy,
stateBus: stateWiring.bus,
updateRoot,
restart: () => {
void shutdown('update', RESTART_EXIT_CODE);
},
},
);
stopWebUI = started.stop;
@@ -122,14 +139,14 @@ async function main() {
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
let shutdownStarted = false;
const shutdown = (signal: string) => async () => {
const shutdown = async (signal: string, requestedExitCode = 0) => {
if (shutdownStarted) {
return;
}
shutdownStarted = true;
log.warn(`Shutting down (${signal})...`);
let exitCode = 0;
let exitCode = requestedExitCode;
try {
await oneBotManager.dispose();
@@ -196,12 +213,38 @@ async function main() {
);
}
try {
await bridgeManager.dispose();
} catch (error) {
exitCode = 1;
log.error(
'bridge shutdown failed: %s',
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
}
await closeLogger();
process.exit(exitCode);
};
process.on('SIGINT', shutdown('SIGINT'));
process.on('SIGTERM', shutdown('SIGTERM'));
process.on('SIGINT', () => {
void shutdown('SIGINT');
});
process.on('SIGTERM', () => {
void shutdown('SIGTERM');
});
if (process.send) {
process.on('message', (message) => {
if (message === 'shutdown') {
void shutdown('launcher');
}
});
process.on('disconnect', () => {
void shutdown('launcher disconnected');
});
process.send('ready');
}
}
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
@@ -226,6 +269,8 @@ if (isMessageStoreMigrationWorkerData(workerData)) {
runMessageStoreMigrationWorker(workerData).catch(() => {
process.exitCode = 1;
});
} else if (updateRoot && !process.env.SNOWLUMA_UPDATE_ROOT) {
void runApplication(updateRoot);
} else {
installProcessGuards();
main().catch(async (error) => {

View File

@@ -109,25 +109,6 @@ export function tempStagePath(
return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`;
}
export function readAppVersion(moduleUrl: string | URL = import.meta.url): string {
if (typeof __APP_VERSION__ === 'string' && __APP_VERSION__) {
return __APP_VERSION__;
}
try {
const raw = readFileSync(new URL('../package.json', moduleUrl), 'utf8');
const version = JSON.parse(raw).version;
if (typeof version === 'string' && version.trim()) {
return version.trim();
}
} catch {
// Built layouts that do not sit next to a package manifest keep the fallback.
}
return '0.0.0';
}
export function errorCode(error: unknown): string {
if (error && typeof error === 'object' && 'code' in error) {
const code = (error as { code?: unknown }).code;
@@ -356,7 +337,7 @@ export function startNativeStageSync(options: StageSyncOptions): { stop: () => v
tick();
const timer = setInterval(tick, options.intervalMs ?? 500);
timer.unref?.();
timer.unref();
return {
stop() {
stopped = true;

View File

@@ -1,14 +1,11 @@
// Global notification-channel store + the pure template renderer.
//
// Mirrors the conventions of `webui/ui-config.ts` (the plan calls for this
// explicitly): every `normalize*` is TOTAL — any unknown / corrupt input
// collapses to a safe default, numbers clamp, unknown keys are dropped — and
// persistence is an atomic write (tmp → rename) behind a module-level cache.
//
// Channels are GLOBAL (defined once here); each UIN opts into a subset via
// `OneBotConfig.notifications.channelIds` (see packages/onebot/src/config.ts).
// Global channels are selected per account by OneBotConfig.notifications.channelIds.
import { boolOr, clampInt, isObject } from '@snowluma/common/coerce';
import { createLogger } from '@snowluma/common/logger';
import {
DEFAULT_WEBHOOK_BODY,
DEFAULT_EMAIL_BODY,
DEFAULT_EMAIL_SUBJECT,
} from '@snowluma/common/notification-templates';
import fs from 'fs';
import path from 'path';
import { extractAddress, parseRecipients } from './smtp';
@@ -79,23 +76,6 @@ export interface NotificationsConfig {
channels: NotificationChannel[];
}
/** Default body template — Server酱-style JSON ({title}/{desp}). The WebUI
* ships additional per-vendor presets (钉钉/Discord/…) as frontend constants
* the operator can drop in. */
export const DEFAULT_BODY_TEMPLATE = `{
"title": "账号状态通知:{event}",
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}"
}`;
export const DEFAULT_SUBJECT_TEMPLATE = '账号{event}:{nickname} ({uin})';
export const DEFAULT_EMAIL_BODY_TEMPLATE = `账号状态发生了改变。
昵称:{nickname}
QQ号:{uin}
当前状态:{event}
时间:{time}`;
const SMTP_HOST_MAX = 253;
const SMTP_USER_MAX = 256;
const SMTP_PASS_MAX = 256;
@@ -114,16 +94,7 @@ export function defaultNotificationsConfig(): NotificationsConfig {
// ─── Template renderer ──────────────────────────────────────────────────────
/**
* Mechanical `{key}` substitution — no logic, no conditionals, no escaping.
* A key present in `vars` is replaced by its value; an unknown `{key}` is left
* untouched (原样) so a typo'd placeholder is visible rather than silently
* blanked. Pure + total (a non-string template yields '').
*
* **JSON safety**: When the template is valid JSON (parseable by JSON.parse),
* values are escaped to prevent breaking the JSON structure — backslashes
* become `\\` and double-quotes become `\"`.
*/
/** Preserve unknown placeholders; escape substituted strings in JSON templates. */
export function renderTemplate(template: string, vars: Record<string, string>): string {
if (typeof template !== 'string') {
return '';
@@ -144,7 +115,7 @@ export function renderTemplate(template: string, vars: Record<string, string>):
}
const val = vars[key];
return isJson ? val.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : val;
return isJson ? JSON.stringify(val).slice(1, -1) : val;
});
}
@@ -315,7 +286,7 @@ function normalizeEmailChannel(
name,
type: 'email',
url: '',
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY, BODY_TEMPLATE_MAX),
enabled: boolOr(raw.enabled, true),
smtpHost,
smtpPort,
@@ -325,8 +296,8 @@ function normalizeEmailChannel(
from,
to,
subjectTemplate:
strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) ||
DEFAULT_SUBJECT_TEMPLATE,
strOr(raw.subjectTemplate, DEFAULT_EMAIL_SUBJECT, SUBJECT_TEMPLATE_MAX) ||
DEFAULT_EMAIL_SUBJECT,
};
}
@@ -368,7 +339,7 @@ function normalizeChannel(raw: unknown): NotificationChannel | null {
name,
type: 'webhook',
url,
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_WEBHOOK_BODY, BODY_TEMPLATE_MAX),
enabled: boolOr(raw.enabled, true),
...(headers ? { headers } : {}),
};

View File

@@ -1,14 +1,5 @@
// Per-UIN debounce state machine for online↔offline notifications.
//
// Uptime-Kuma semantics (grill-locked in the plan): an offline that SURVIVES
// `debounceSeconds` fires an "offline" notification; its later recovery fires
// the paired "online". An offline that self-heals within the window fires
// NOTHING (the blip is suppressed). A cold online — one with no prior fired
// offline — fires nothing (it is not a recovery).
//
// This module is PURE: no timers, no I/O, no clock. It only decides; the
// manager owns the timer + the side effects. That keeps the debounce logic
// fully unit-testable by driving a sequence of events.
// Offline must survive the debounce window before it can emit a recovery pair.
// The manager owns timers and delivery; this machine only decides transitions.
import type { NotificationEvent } from './config';
export type DebounceDecision =
@@ -17,80 +8,48 @@ export type DebounceDecision =
| { kind: 'cancel' }
| { kind: 'emit'; event: NotificationEvent };
interface UinState {
/** An offline debounce timer is armed but has not yet fired. */
pending: boolean;
/** An "offline" notification has fired and is awaiting its recovery. */
firedOffline: boolean;
}
export class DebounceMachine {
private readonly states = new Map<string, UinState>();
private state(uin: string): UinState {
let s = this.states.get(uin);
if (!s) {
s = { pending: false, firedOffline: false };
this.states.set(uin, s);
}
return s;
}
private readonly states = new Map<string, 'pending' | 'offline'>();
/** Account went offline. `debounceSeconds` is read fresh from config so a
* reload takes effect on the next transition. */
onOffline(uin: string, debounceSeconds: number): DebounceDecision {
const s = this.state(uin);
if (s.firedOffline || s.pending) {
if (this.states.has(uin)) {
return { kind: 'none' };
} // already down / already counting
}
// Non-finite / non-positive → no debounce, fire immediately. Stays total:
// never schedule a setTimeout(NaN|Infinity). Production config always
// clamps to a finite [0,3600]; this only hardens direct callers.
if (!Number.isFinite(debounceSeconds) || debounceSeconds <= 0) {
s.firedOffline = true;
this.states.set(uin, 'offline');
return { kind: 'emit', event: 'offline' };
}
s.pending = true;
this.states.set(uin, 'pending');
return { kind: 'schedule', delayMs: debounceSeconds * 1000 };
}
/** Account came online. */
onOnline(uin: string): DebounceDecision {
const s = this.state(uin);
const state = this.states.get(uin);
this.states.delete(uin);
if (s.pending) {
s.pending = false;
return { kind: 'cancel' }; // self-heal within the debounce window — nothing fired
if (state === 'pending') {
return { kind: 'cancel' };
}
if (s.firedOffline) {
s.firedOffline = false;
return { kind: 'emit', event: 'online' }; // recovery, paired with the fired offline
if (state === 'offline') {
return { kind: 'emit', event: 'online' };
}
return { kind: 'none' }; // cold online / already up
return { kind: 'none' };
}
/** The offline debounce window elapsed (the armed timer fired). */
onTimerElapsed(uin: string): DebounceDecision {
const s = this.state(uin);
if (!s.pending) {
if (this.states.get(uin) !== 'pending') {
return { kind: 'none' };
} // cancelled before firing
}
s.pending = false;
s.firedOffline = true;
this.states.set(uin, 'offline');
return { kind: 'emit', event: 'offline' };
}
/** Drop a UIN's state (e.g. on dispose). */
forget(uin: string): void {
this.states.delete(uin);
}
}

View File

@@ -9,9 +9,11 @@
// SMTP send, the clock) are injected so the class is fully unit-testable; the
// real wiring lives in `createNotificationManager()` at the bottom.
import { positiveIntEnv } from '@snowluma/common/env';
import { errorMessage } from '@snowluma/common/errors';
import type { HookProcessInfo } from '@snowluma/bridge/types';
import { createLogger } from '@snowluma/common/logger';
import { loadOneBotConfig } from '@snowluma/onebot/config';
import type { BridgeManager } from '../bridge/manager';
import type { BridgeSessionSource } from '../bridge/bridge-interface';
import {
isEmailChannel,
loadNotificationsConfig,
@@ -27,9 +29,8 @@ const log = createLogger('Notifications');
const DEFAULT_HISTORY_LIMIT = 100;
const DEFAULT_POST_TIMEOUT_MS = 10_000;
const FALLBACK_DEBOUNCE_SECONDS = 30;
/** One delivery attempt; kept only in memory (the plan forbids persistence). */
/** One delivery attempt, retained in bounded in-memory history. */
export interface DeliveryRecord {
time: number;
uin: string;
@@ -58,21 +59,39 @@ export interface MailPayload {
text: string;
}
/**
* Optional hook process snapshot attached to a notification. Missing facts
* mean unknown, not proof that QQ exited. Hook status describes connectivity;
* it does not by itself identify the reason an account went offline.
* Undefined fields render empty in templates.
*/
export type NotificationProcessFacts = Partial<Pick<HookProcessInfo, 'status' | 'pid' | 'error'>>;
export interface NotificationManagerDeps {
/** Global channel store (channels + debounceSeconds). */
loadConfig: () => NotificationsConfig;
/** The channel ids a UIN has opted into. */
loadChannelIds: (uin: string) => string[];
/** Webhook delivery — never throws; failures come back as `{ ok: false }`. */
/** Webhook delivery. Rejections are recorded as failed attempts. */
post: (url: string, body: string, headers?: Record<string, string>) => Promise<PostResult>;
/** SMTP delivery — optional so webhook-only tests stay lean. */
sendMail?: (mail: MailPayload) => Promise<PostResult>;
now: () => number;
historyLimit?: number;
/**
* Optional: look up the lifecycle event's PID and UIN at dispatch time. Omitted
* (or resolving to `undefined`) means "process unknown" — the fact
* variables then render empty rather than leaving `{status}` in the body.
*/
resolveProcess?: (
uin: string,
pid: number | null,
) => Promise<NotificationProcessFacts | undefined>;
}
function errMsg(err: unknown): string {
return err instanceof Error ? err.message : String(err);
interface AccountNotificationContext {
nickname: string;
pid: number | null;
}
/**
@@ -91,10 +110,12 @@ export class NotificationManager {
private readonly deps: NotificationManagerDeps;
private readonly machine = new DebounceMachine();
private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
private readonly nicknames = new Map<string, string>();
private readonly accounts = new Map<string, AccountNotificationContext>();
private readonly history: DeliveryRecord[] = [];
private readonly deliveries = new Map<string, Promise<void>>();
private readonly historyLimit: number;
private disposed = false;
private unsubscribeSessions: (() => void) | null = null;
constructor(deps: NotificationManagerDeps) {
this.deps = deps;
@@ -103,78 +124,71 @@ export class NotificationManager {
/** Subscribe to the global session online/offline edges. Register AFTER
* OneBotManager so the nickname fallback is already populated. */
bind(bridgeManager: BridgeManager): void {
bridgeManager.addSessionStartedListener((uin, bridge) =>
this.handleOnline(uin, bridge.identity.nickname),
);
bridgeManager.addSessionClosedListener((uin, bridge) =>
this.handleOffline(uin, bridge.identity.nickname),
);
}
handleOnline(uin: string, nickname?: string): void {
bind(bridgeManager: BridgeSessionSource): void {
if (this.disposed) {
return;
}
if (nickname) {
this.nicknames.set(uin, nickname);
this.unsubscribeSessions?.();
this.unsubscribeSessions = bridgeManager.subscribeSessions({
started: (uin, bridge) =>
this.handleOnline(uin, bridge.identity.nickname, bridge.activePid),
closed: (uin, bridge, pid) => this.handleOffline(uin, bridge.identity.nickname, pid),
});
}
handleOnline(uin: string, nickname?: string, pid: number | null = null): void {
if (this.disposed) {
return;
}
this.accounts.set(uin, {
nickname: nickname || this.accounts.get(uin)?.nickname || uin,
pid,
});
this.apply(uin, this.machine.onOnline(uin));
}
handleOffline(uin: string, nickname?: string): void {
handleOffline(uin: string, nickname?: string, pid: number | null = null): void {
if (this.disposed) {
return;
}
if (nickname) {
this.nicknames.set(uin, nickname);
}
let debounceSeconds: number;
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
}
private debounceSeconds(): number {
try {
return this.deps.loadConfig().debounceSeconds;
} catch {
return FALLBACK_DEBOUNCE_SECONDS;
debounceSeconds = this.deps.loadConfig().debounceSeconds;
} catch (err) {
log.warn('offline(%s) skipped — config load failed: %s', uin, errorMessage(err));
return;
}
this.accounts.set(uin, {
nickname: nickname || this.accounts.get(uin)?.nickname || uin,
pid,
});
this.apply(uin, this.machine.onOffline(uin, debounceSeconds));
}
private apply(uin: string, decision: DebounceDecision): void {
switch (decision.kind) {
case 'schedule': {
const existing = this.timers.get(uin);
if (existing) {
clearTimeout(existing);
}
const timer = setTimeout(() => {
this.timers.delete(uin);
this.apply(uin, this.machine.onTimerElapsed(uin));
}, decision.delayMs);
// Don't let a pending notification timer keep the process alive.
if (typeof (timer as { unref?: () => void }).unref === 'function') {
(timer as { unref: () => void }).unref();
}
timer.unref();
this.timers.set(uin, timer);
break;
}
case 'cancel': {
const timer = this.timers.get(uin);
if (timer) {
clearTimeout(timer);
this.timers.delete(uin);
}
clearTimeout(this.timers.get(uin));
this.timers.delete(uin);
break;
}
@@ -186,16 +200,48 @@ export class NotificationManager {
}
}
/** Render + deliver a transition to every opted-in, enabled channel and record
* the outcome. Never throws (a bad channel can't break the others). */
async notify(uin: string, event: NotificationEvent): Promise<void> {
/** Queue one transition; channel failures are recorded independently. */
notify(uin: string, event: NotificationEvent): Promise<void> {
if (this.disposed) {
return Promise.resolve();
}
const account = this.accounts.get(uin) ?? { nickname: uin, pid: null };
const previous = this.deliveries.get(uin) ?? Promise.resolve();
// Both enrichment and every channel delivery belong to this transition.
// A slow lookup/send must not let recovery overtake offline for one UIN.
const delivery = previous
.then(() => this.notifyNow(uin, event, account))
.finally(() => {
if (this.deliveries.get(uin) === delivery) {
this.deliveries.delete(uin);
}
});
this.deliveries.set(uin, delivery);
return delivery;
}
private async notifyNow(
uin: string,
event: NotificationEvent,
account: AccountNotificationContext,
): Promise<void> {
if (this.disposed) {
return;
}
let channels: NotificationChannel[];
try {
const cfg = this.deps.loadConfig();
channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin));
} catch (err) {
log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err));
log.warn(
'notify(%s, %s) skipped — config load failed: %s',
uin,
event,
errorMessage(err),
);
return;
}
@@ -203,15 +249,29 @@ export class NotificationManager {
return;
}
const nickname = this.nicknames.get(uin) || uin;
let facts: NotificationProcessFacts | undefined;
try {
facts = await this.deps.resolveProcess?.(uin, account.pid);
} catch (err) {
log.warn('resolveProcess(%s, %s) failed: %s', uin, account.pid, errorMessage(err));
}
const vars: Record<string, string> = {
uin,
nickname,
nickname: account.nickname,
event,
time: new Date(this.deps.now()).toISOString(),
status: facts?.status ?? '',
pid: facts?.pid === undefined ? '' : String(facts.pid),
error: facts?.error ?? '',
};
for (const ch of channels) {
if (this.disposed) {
return;
}
const result = await this.deliver(ch, vars);
this.record({
time: this.deps.now(),
@@ -265,8 +325,7 @@ export class NotificationManager {
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
} catch (err) {
// Injected collaborators are contracted not to throw, but guard anyway.
return { ok: false, error: errMsg(err) };
return { ok: false, error: errorMessage(err) };
}
}
@@ -280,7 +339,7 @@ export class NotificationManager {
try {
channel = this.deps.loadConfig().channels.find((c) => c.id === channelId);
} catch (err) {
return { ok: false, found: false, error: errMsg(err) };
return { ok: false, found: false, error: errorMessage(err) };
}
if (!channel) {
@@ -292,6 +351,9 @@ export class NotificationManager {
nickname: '测试账号',
event: 'offline' as const,
time: new Date(this.deps.now()).toISOString(),
status: 'disconnected',
pid: '1234',
error: '',
};
return { ...(await this.deliver(channel, vars)), found: true };
}
@@ -316,6 +378,8 @@ export class NotificationManager {
}
this.disposed = true;
this.unsubscribeSessions?.();
this.unsubscribeSessions = null;
for (const timer of this.timers.values()) {
clearTimeout(timer);
@@ -344,7 +408,7 @@ export function createDefaultPost(
error: res.ok ? undefined : `HTTP ${res.status}`,
};
} catch (err) {
return { ok: false, error: errMsg(err) };
return { ok: false, error: errorMessage(err) };
}
};
}
@@ -378,13 +442,17 @@ export function createDefaultSendMail(
};
}
/** The real, fully-wired singleton. */
export function createNotificationManager(): NotificationManager {
/** The real, fully-wired singleton. `resolveProcess` is supplied by the
* runtime — this package deliberately knows nothing about HookManager. */
export function createNotificationManager(
resolveProcess?: NotificationManagerDeps['resolveProcess'],
): NotificationManager {
return new NotificationManager({
loadConfig: loadNotificationsConfig,
loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [],
post: createDefaultPost(),
sendMail: createDefaultSendMail(),
now: () => Date.now(),
resolveProcess,
});
}

View File

@@ -0,0 +1,55 @@
import { hasLowProcessIntegrity, type RuntimeIntegrity } from '@snowluma/bridge';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('App');
const LEVEL_NAMES: Record<number, string> = {
0: 'Untrusted',
4096: 'Low',
8192: 'Medium',
8448: 'Medium Plus',
12288: 'High',
16384: 'System',
20480: 'Protected Process',
};
function level(rid: number): string {
return `${LEVEL_NAMES[rid] ?? 'Unknown'} (RID=${rid})`;
}
/** Called once by main(), never by WebUI polling or warning dismissal. */
export function logRuntimeIntegrity(integrity: RuntimeIntegrity): void {
if (integrity.status === 'unsupported') {
return;
}
if (integrity.status === 'unavailable') {
log.warn('Node integrity: unknown (%s)', integrity.error);
return;
}
const token = integrity.process;
const file = integrity.file;
const tokenText =
token.status === 'ok'
? level(token.rid)
: `unknown (${token.operation}, Win32=${token.code})`;
const fileText =
file.status === 'error'
? `unknown (${file.operation}, Win32=${file.code})`
: file.label
? `${level(file.label.rid)}, inherited=${file.label.inherited}, policy=${file.label.policy}`
: 'unlabeled';
// "token=" is reserved for credentials by the shared log redactor.
const report = `Node integrity: pid=${integrity.pid}, process=${tokenText}; EXE=${fileText}`;
if (
token.status === 'error' ||
file.status === 'error' ||
hasLowProcessIntegrity(integrity) ||
(file.label && file.label.rid < 8192)
) {
log.warn(report);
} else {
log.info(report);
}
}

View File

@@ -6,7 +6,7 @@ import {
type SysFaceCatalogStorage,
} from '@snowluma/protocol/sys-face-store';
import { JsonSysFaceCatalogStorage } from '@snowluma/protocol/sys-face-storage';
import type { BridgeManager } from './bridge/manager';
import type { BridgeSessionSource } from './bridge/bridge-interface';
const log = createLogger('SysFace');
@@ -19,7 +19,7 @@ export interface SystemFaceCatalogBindingOptions {
/** Attach the shared system-face catalog to Bridge login edges. The first
* account restores + refreshes it; later accounts reuse the same result. */
export function bindSystemFaceCatalog(
manager: BridgeManager,
manager: BridgeSessionSource,
options: SystemFaceCatalogBindingOptions = {},
): void {
const store = options.store ?? sysFaceStore;
@@ -30,13 +30,15 @@ export function bindSystemFaceCatalog(
);
store.configureStorage(storage);
manager.addSessionStartedListener((uin, bridge) => {
void store.prewarm(bridge).catch((error) => {
log.error(
'system face catalog login prewarm failed: uin=%s error=%s',
uin,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
});
manager.subscribeSessions({
started: (uin, bridge) => {
void store.prewarm(bridge).catch((error) => {
log.error(
'system face catalog login prewarm failed: uin=%s error=%s',
uin,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
});
},
});
}

View File

@@ -1,15 +1,5 @@
// Advisory update check against the public GitHub Releases API.
//
// Strictly read-only (T0): SnowLuma never downloads or applies anything
// itself — cross-platform self-update is a minefield (Windows locks loaded
// .node/.dll/node.exe, Docker bakes the app into image layers, bare installs
// have no supervisor). We only tell the WebUI that a newer *stable* release
// exists and link the user to it; they download and apply manually.
//
// The result is cached to stay well under GitHub's 60 req/hr unauthenticated
// rate limit, and every failure degrades silently (the UI just shows
// "无法检查更新" rather than nagging).
import { APP_VERSION } from '@snowluma/common/version';
import { compareVersions, parseVersion } from '@snowluma/common/semver';
import { createLogger } from '@snowluma/common/logger';
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
@@ -46,58 +36,11 @@ interface GithubRelease {
published_at?: string;
}
export function currentVersion(): string {
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
}
function isEnabled(): boolean {
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
}
/**
* Compare two dotted versions. Returns >0 if `a` is newer than `b`, <0 if
* older, 0 if equal. The numeric core (major.minor.patch) compares
* numerically; a prerelease (`-rc.1`) ranks below its release. Good enough
* for "is the latest stable strictly newer than what we run" — and avoids
* pulling in a `semver` runtime dependency (the dist bundle ships none).
*/
export function compareVersions(a: string, b: string): number {
const parse = (v: string) => {
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
while (nums.length < 3) {
nums.push(0);
}
return { nums, pre };
};
const pa = parse(a);
const pb = parse(b);
for (let i = 0; i < 3; i++) {
if (pa.nums[i] !== pb.nums[i]) {
return pa.nums[i] - pb.nums[i];
}
}
if (pa.pre === pb.pre) {
return 0;
}
if (!pa.pre) {
return 1;
} // release > prerelease
if (!pb.pre) {
return -1;
}
return pa.pre < pb.pre ? -1 : 1;
}
// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's
// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results
// are intentionally not cached (shouldCache) so the next check retries.
@@ -145,13 +88,18 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
}
const rel = (await res.json()) as GithubRelease;
const tag = (rel.tag_name ?? '').trim();
const tag = typeof rel.tag_name === 'string' ? rel.tag_name.trim() : '';
if (!tag) {
return { ...base, error: 'no tag' };
}
const latest = tag.replace(/^v/, '');
const latest = tag.startsWith('v') ? tag.slice(1) : tag;
if (!parseVersion(latest)) {
return { ...base, error: 'invalid release version' };
}
return {
current,
latest,
@@ -173,7 +121,7 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
* are not cached so the next check retries.
*/
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
const current = currentVersion();
const current = APP_VERSION;
if (!isEnabled()) {
return { ...emptyResult(current), error: 'disabled' };

View File

@@ -0,0 +1,187 @@
import { createHash } from 'node:crypto';
import { createWriteStream } from 'node:fs';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { unzipSync } from 'fflate';
import { x as extractTar } from 'tar';
import { isRuntimeEntry, readManifest } from './files';
interface ReleaseAsset {
url: string;
size: number;
digest: string;
}
export function assetName(version: string, target: string): string {
const platform = target.replace('win32', 'win');
return `SnowLuma-v${version}-${platform}-lite.${target.startsWith('win32') ? 'zip' : 'tar.gz'}`;
}
async function releaseAsset(version: string, target: string): Promise<ReleaseAsset> {
const name = assetName(version, target);
const response = await fetch(
`https://api.github.com/repos/SnowLuma/SnowLuma/releases/tags/v${version}`,
{
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': 'SnowLuma',
'X-GitHub-Api-Version': '2022-11-28',
},
signal: AbortSignal.timeout(15_000),
},
);
if (!response.ok) {
throw new Error(`获取更新失败: GitHub ${response.status}`);
}
const release: unknown = await response.json();
if (
!release ||
typeof release !== 'object' ||
!('assets' in release) ||
!Array.isArray(release.assets)
) {
throw new Error('发布信息无效');
}
const asset: unknown = release.assets.find(
(item: unknown) =>
item !== null && typeof item === 'object' && 'name' in item && item.name === name,
);
const url = `https://github.com/SnowLuma/SnowLuma/releases/download/v${version}/${name}`;
if (
!asset ||
typeof asset !== 'object' ||
!('size' in asset) ||
typeof asset.size !== 'number' ||
!Number.isSafeInteger(asset.size) ||
asset.size <= 0 ||
!('digest' in asset) ||
typeof asset.digest !== 'string' ||
!/^sha256:[a-f0-9]{64}$/.test(asset.digest)
) {
throw new Error('更新包不存在或缺少校验信息');
}
return { url, size: asset.size, digest: asset.digest };
}
export function archivePath(name: string): string {
const normalized = name.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/$/, '');
if (normalized === '.' || normalized === '') {
return '';
}
const parts = normalized.split('/');
if (
!isRuntimeEntry(parts[0]) ||
parts.some((part) => !part || part === '.' || part === '..' || /[:\0]/.test(part))
) {
throw new Error(`更新包路径无效: ${name}`);
}
return normalized;
}
export async function downloadUpdate(
directory: string,
version: string,
target: string,
): Promise<void> {
const asset = await releaseAsset(version, target);
const response = await fetch(asset.url, { signal: AbortSignal.timeout(10 * 60_000) });
if (!response.ok || !response.body) {
throw new Error(`下载更新失败: HTTP ${response.status}`);
}
const archive = path.join(directory, 'archive');
const hash = createHash('sha256');
let received = 0;
await pipeline(
Readable.fromWeb(response.body),
new Transform({
transform(chunk: Buffer, _encoding, callback) {
received += chunk.length;
if (received > asset.size) {
callback(new Error('更新包大小不匹配'));
return;
}
hash.update(chunk);
callback(null, chunk);
},
}),
createWriteStream(archive, { flags: 'wx' }),
);
if (received !== asset.size || `sha256:${hash.digest('hex')}` !== asset.digest) {
throw new Error('更新包校验失败');
}
const payload = path.join(directory, 'payload');
await mkdir(payload);
if (target.startsWith('win32')) {
const files = unzipSync(await readFile(archive), {
filter: (entry) => {
archivePath(entry.name);
return true;
},
});
for (const [name, bytes] of Object.entries(files)) {
const relative = archivePath(name);
if (!relative || name.endsWith('/')) {
continue;
}
const destination = path.join(payload, relative);
await mkdir(path.dirname(destination), { recursive: true });
await writeFile(destination, bytes, { flag: 'wx' });
}
} else {
let invalidEntry: Error | undefined;
await extractTar({
file: archive,
cwd: payload,
strict: true,
filter: (name, entry) => {
try {
archivePath(name);
if (
!('type' in entry) ||
(entry.type !== 'File' && entry.type !== 'Directory')
) {
throw new Error('更新包包含链接或特殊文件');
}
return true;
} catch (error) {
invalidEntry = error instanceof Error ? error : new Error(String(error));
return false;
}
},
});
if (invalidEntry) {
throw invalidEntry;
}
}
const manifest = await readManifest(payload);
if (manifest.version !== version || manifest.target !== target) {
throw new Error('更新包版本或平台不匹配');
}
}

View File

@@ -0,0 +1,273 @@
import { access, cp, lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { constants, existsSync } from 'node:fs';
import os from 'node:os';
import { parseVersion } from '@snowluma/common/semver';
export const MANIFEST_FILE = 'release.json';
export async function updateDirectory(root: string, temporaryRoot = os.tmpdir()): Promise<string> {
const local = path.join(root, 'tmp', 'update');
// A locally staged update must remain discoverable if system tmp becomes available again.
if (existsSync(local)) {
return local;
}
const identity = createHash('sha256').update(path.resolve(root)).digest('hex').slice(0, 16);
const directory = path.join(temporaryRoot, `snowluma-update-${identity}`);
try {
await mkdir(directory, { recursive: true });
await access(directory, constants.W_OK);
return directory;
} catch (error) {
if (
!(error instanceof Error) ||
!('code' in error) ||
!['EACCES', 'EPERM', 'EROFS'].includes(String(error.code))
) {
throw error;
}
await mkdir(local, { recursive: true });
return local;
}
}
export interface ReleaseManifest {
version: string;
target: string;
entries: string[];
}
const runtimeEntries = new Set([
'native',
'client',
'package.json',
MANIFEST_FILE,
'launcher.bat',
'launcher.sh',
'check-node-version.cjs',
'EULA.md',
'PRIVACY.md',
]);
export function isRuntimeEntry(name: string): boolean {
return runtimeEntries.has(name) || /^[\w-]+\.mjs(?:\.map)?$/.test(name);
}
function entryList(value: unknown): value is string[] {
return (
Array.isArray(value) &&
value.every((entry) => typeof entry === 'string' && isRuntimeEntry(entry)) &&
new Set(value).size === value.length
);
}
export async function exists(file: string): Promise<boolean> {
try {
await lstat(file);
return true;
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
return false;
}
throw error;
}
}
export async function readManifest(root: string): Promise<ReleaseManifest> {
const value: unknown = JSON.parse(await readFile(path.join(root, MANIFEST_FILE), 'utf8'));
if (
!value ||
typeof value !== 'object' ||
!('version' in value) ||
typeof value.version !== 'string' ||
!parseVersion(value.version) ||
!('target' in value) ||
typeof value.target !== 'string' ||
!/^(win32-x64|linux-(x64|arm64))$/.test(value.target) ||
!('entries' in value) ||
!entryList(value.entries)
) {
throw new Error('更新包清单无效');
}
const entries = value.entries;
if (
![
'index.mjs',
'native',
'client',
'package.json',
MANIFEST_FILE,
'check-node-version.cjs',
'EULA.md',
'PRIVACY.md',
value.target.startsWith('win32') ? 'launcher.bat' : 'launcher.sh',
].every((entry) => entries.includes(entry))
) {
throw new Error('更新包清单无效');
}
return { version: value.version, target: value.target, entries: value.entries };
}
async function checkEntryTypes(root: string, entries: string[]): Promise<void> {
for (const entry of entries) {
const stat = await lstat(path.join(root, entry));
const directory = entry === 'native' || entry === 'client';
if (directory ? !stat.isDirectory() : !stat.isFile()) {
throw new Error(`更新包文件类型无效: ${entry}`);
}
}
}
interface Transaction {
entries: string[];
original: string[];
}
async function readTransaction(file: string): Promise<Transaction> {
const value: unknown = JSON.parse(await readFile(file, 'utf8'));
if (
!value ||
typeof value !== 'object' ||
!('entries' in value) ||
!entryList(value.entries) ||
!('original' in value) ||
!entryList(value.original)
) {
throw new Error('更新恢复记录无效');
}
const entries = value.entries;
if (value.original.some((entry) => !entries.includes(entry))) {
throw new Error('更新恢复记录无效');
}
return { entries: value.entries, original: value.original };
}
async function restore(root: string, pending: string, transaction: Transaction): Promise<void> {
for (const entry of transaction.entries) {
const backup = path.join(pending, 'backup', entry);
const destination = path.join(root, entry);
if (transaction.original.includes(entry)) {
await replaceEntry(backup, destination, path.join(root, '.update-install'));
} else {
await rm(destination, { recursive: true, force: true });
}
}
await rm(path.join(pending, 'transaction.json'));
}
async function replaceEntry(source: string, destination: string, temporary: string): Promise<void> {
await rm(temporary, { recursive: true, force: true });
await cp(source, temporary, { recursive: true });
// Files stay present until their replacement is ready, including the entry point.
if ((await lstat(source)).isDirectory()) {
await rm(destination, { recursive: true, force: true });
}
await rename(temporary, destination);
}
// Called before loading native libraries, after the previous process has exited.
export async function applyPendingUpdate(root: string): Promise<string | null> {
const directory = await updateDirectory(root);
const pending = path.join(directory, 'pending');
const completed = path.join(directory, 'completed');
await rm(completed, { recursive: true, force: true });
await rm(path.join(directory, 'downloading'), { recursive: true, force: true });
await rm(path.join(root, '.update-install'), { recursive: true, force: true });
if (!(await exists(pending))) {
await rm(directory, { recursive: true });
return null;
}
const journal = path.join(pending, 'transaction.json');
if (await exists(journal)) {
await restore(root, pending, await readTransaction(journal));
}
const payload = path.join(pending, 'payload');
const next = await readManifest(payload);
const current = await readManifest(root);
if (next.target !== current.target) {
throw new Error('更新包平台不匹配');
}
await checkEntryTypes(payload, next.entries);
const entries = [...new Set([...current.entries, ...next.entries])];
const original: string[] = [];
for (const entry of entries) {
if (await exists(path.join(root, entry))) {
if ((await lstat(path.join(root, entry))).isSymbolicLink()) {
throw new Error(`更新目标不能是符号链接: ${entry}`);
}
original.push(entry);
}
}
const transaction = { entries, original };
const backup = path.join(pending, 'backup');
await rm(backup, { recursive: true, force: true });
await mkdir(backup);
for (const entry of original) {
await cp(path.join(root, entry), path.join(backup, entry), { recursive: true });
}
await writeFile(`${journal}.tmp`, JSON.stringify(transaction));
await rename(`${journal}.tmp`, journal);
try {
for (const entry of next.entries) {
await replaceEntry(
path.join(payload, entry),
path.join(root, entry),
path.join(root, '.update-install'),
);
}
for (const entry of current.entries) {
if (!next.entries.includes(entry)) {
await rm(path.join(root, entry), { recursive: true, force: true });
}
}
// Renaming commits the transaction before cleanup, including across a crash.
await rename(pending, completed);
} catch (error) {
try {
await restore(root, pending, transaction);
} catch (restoreError) {
throw new AggregateError(
[error, restoreError],
'更新失败,恢复未完成;下次启动将继续恢复',
);
}
throw error;
}
await rm(directory, { recursive: true });
return next.version;
}

View File

@@ -0,0 +1,99 @@
import { existsSync } from 'node:fs';
import { mkdir, rename, rm } from 'node:fs/promises';
import path from 'node:path';
import { createLogger } from '@snowluma/common/logger';
import { parseVersion } from '@snowluma/common/semver';
import { downloadUpdate } from './download';
import { exists, MANIFEST_FILE, readManifest, updateDirectory } from './files';
const log = createLogger('Update');
export type UpdateState =
| { phase: 'unavailable'; message: string }
| { phase: 'idle' }
| { phase: 'downloading' | 'ready' | 'restarting'; version: string }
| { phase: 'error'; message: string };
export async function createUpdateService(
root: string | undefined,
current: string,
options: { download?: typeof downloadUpdate; isContainer?: boolean } = {},
) {
const download = options.download ?? downloadUpdate;
let state: UpdateState;
let target = '';
let staging = '';
if (!root || !existsSync(path.join(root, MANIFEST_FILE))) {
state = { phase: 'unavailable', message: '在线更新仅支持发行包' };
} else if (
options.isContainer ??
(existsSync('/.dockerenv') || Boolean(process.env.container))
) {
state = { phase: 'unavailable', message: '请更新容器镜像' };
} else {
const manifest = await readManifest(root);
target = manifest.target;
staging = await updateDirectory(root);
const pending = path.join(staging, 'pending', 'payload');
state = (await exists(pending))
? { phase: 'ready', version: (await readManifest(pending)).version }
: { phase: 'idle' };
}
const prepare = async (version: string): Promise<void> => {
const directory = path.join(staging, 'downloading');
try {
await rm(directory, { recursive: true, force: true });
await mkdir(directory, { recursive: true });
await download(directory, version, target);
await rm(path.join(directory, 'archive'));
await rename(directory, path.join(staging, 'pending'));
state = { phase: 'ready', version };
log.info('v%s 已下载,重启后应用', version);
} catch (error) {
log.error('下载更新失败: %s', error);
let message = error instanceof Error ? error.message : String(error);
try {
await rm(directory, { recursive: true, force: true });
} catch (cleanupError) {
message += `;清理更新文件失败: ${String(cleanupError)}`;
log.error('清理更新文件失败: %s', cleanupError);
}
state = { phase: 'error', message };
}
};
return {
status: () => ({ current, ...state }),
start(version: unknown) {
if (state.phase !== 'idle' && state.phase !== 'error') {
throw new Error(
state.phase === 'unavailable' ? state.message : '更新正在进行或等待重启',
);
}
const parsed = parseVersion(version);
if (!parsed || parsed.prerelease.length || parsed.compare(current) <= 0) {
throw new Error('请选择更新的正式版本');
}
state = { phase: 'downloading', version: parsed.raw };
log.info('下载 v%s', parsed.raw);
void prepare(parsed.raw);
},
restart() {
if (state.phase !== 'ready') {
throw new Error('更新包尚未就绪');
}
state = { phase: 'restarting', version: state.version };
},
};
}
export type UpdateService = Awaited<ReturnType<typeof createUpdateService>>;

View File

@@ -0,0 +1,75 @@
import { spawn } from 'node:child_process';
import path from 'node:path';
import { applyPendingUpdate } from './files';
export const RESTART_EXIT_CODE = 75;
export async function runApplication(root: string): Promise<void> {
let stopping = false;
let child: ReturnType<typeof spawn> | undefined;
const requestShutdown = () => {
if (child?.connected) {
child.send('shutdown', (error) => {
if (error) {
console.error('[App] 发送退出请求失败:', error);
}
});
}
};
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.on(signal, () => {
stopping = true;
if (process.platform === 'win32') {
requestShutdown();
} else {
child?.kill(signal);
}
});
}
try {
do {
const version = await applyPendingUpdate(root);
if (version) {
console.info(`[Update] 已更新至 v${version}`);
}
if (stopping) {
break;
}
const code = await new Promise<number>((resolve, reject) => {
child = spawn(
process.execPath,
[...process.execArgv, path.join(root, 'index.mjs'), ...process.argv.slice(2)],
{
stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
env: { ...process.env, SNOWLUMA_UPDATE_ROOT: root },
},
);
child.once('error', reject);
child.on('message', (message) => {
if (message === 'ready' && stopping) {
requestShutdown();
}
});
child.once('exit', (exitCode, signal) =>
resolve(exitCode ?? (signal === 'SIGINT' ? 130 : 143)),
);
});
child = undefined;
if (code !== RESTART_EXIT_CODE || stopping) {
process.exitCode = code === RESTART_EXIT_CODE ? 0 : code;
break;
}
} while (!stopping);
} catch (error) {
console.error('[Update] 启动失败:', error);
process.exitCode = 1;
}
}

View File

@@ -1,16 +1,3 @@
/**
* Connection-status diff loop. OneBot adapters don't have an internal
* event-emitter for connection state (listening / connected / client-count
* changes), so this loop polls `getConnectionStatuses()` and publishes
* `connections` to the StateBus when the JSON-serialised snapshot changes
* vs the previous tick.
*
* Cheap (500ms default cadence, 1-3 accounts, ~hundreds of bytes), only
* fires the StateBus when state actually moves — so the SSE handler only
* pushes a fresh `connections` frame when the user would actually see
* something update.
*/
import { createLogger, runWithTraceRequest } from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { StateBus } from './state-bus';
@@ -33,16 +20,12 @@ export interface ConnectionDiffLoopOptions {
intervalMs?: number;
}
export interface ConnectionDiffLoopHandle {
/** Stop the loop. Subsequent snapshot mutations produce nothing. */
dispose(): void;
}
export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle {
/** One shared loop while clients subscribe; each subscription returns its release handle. */
export function createConnectionPoller(opts: ConnectionDiffLoopOptions): () => () => void {
const intervalMs = opts.intervalMs ?? 500;
let lastSerialized = '';
let haveBaseline = false;
let disposed = false;
let lastSerialized: string | undefined | null = null;
let subscribers = 0;
let timer: ReturnType<typeof setInterval> | null = null;
// One-shot diagnostic latch: a projector that starts throwing only after
// a shape regression would otherwise wedge the baseline silently — no
// publishes, no log, no symptom besides "the dashboard's connections
@@ -51,7 +34,7 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
let warnedProjectorThrew = false;
const tick = (): void => {
if (disposed) {
if (subscribers === 0) {
return;
}
@@ -112,13 +95,12 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
const serialized = JSON.stringify(comparable);
if (!haveBaseline) {
if (lastSerialized === null) {
// First successful observation. The SSE handler's sendAllInitial
// already shipped a `connections` frame to every connected client
// on connect, so the baseline is what they already have — emitting
// it again would be a duplicate. Just store it.
lastSerialized = serialized;
haveBaseline = true;
return;
}
@@ -139,21 +121,28 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
});
};
const timer = setInterval(tick, intervalMs);
// Don't pin the Node event loop: the loop is permanent for the server
// lifetime by design, but tests / a future hot-reload scenario must be
// able to exit cleanly without an outstanding interval ref. Mirrors the
// tokenJanitor pattern in server.ts.
timer.unref?.();
return () => {
if (subscribers++ === 0) {
lastSerialized = null;
tick();
timer = setInterval(tick, intervalMs);
timer.unref();
}
return {
dispose(): void {
if (disposed) {
let subscribed = true;
return () => {
if (!subscribed) {
return;
}
disposed = true;
clearInterval(timer);
},
subscribed = false;
if (--subscribers === 0 && timer !== null) {
clearInterval(timer);
timer = null;
lastSerialized = null;
}
};
};
}

View File

@@ -20,6 +20,7 @@ import os from 'os';
import path from 'path';
import { randomBytes } from 'crypto';
import { traceWebuiMutationRequestChunk } from './mutation-trace';
import { sseResponse } from './sse-response';
/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but
* kept distinct so the two cleanup stories don't entangle. */
@@ -203,70 +204,43 @@ export function buildStreamInvokeResponse(
signal: AbortSignal,
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
): Response {
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
let closed = false;
return sseResponse(signal, (channel) => {
const isAlive = () => !channel.isClosed();
const onAbort = () => {
closed = true;
};
const emit = async (json: string): Promise<void> => {
if (!isAlive()) {
throw new Error('stream transport closed');
}
signal.addEventListener('abort', onAbort);
const isAlive = () => !closed && !signal.aborted;
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
let spins = 0;
const emit = async (json: string): Promise<void> => {
if (!isAlive()) {
throw new Error('stream transport closed');
}
while (isAlive() && (channel.desiredSize() ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
await delay(DRAIN_WAIT_MS);
spins += 1;
}
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
let spins = 0;
if (!isAlive()) {
throw new Error('stream transport closed');
}
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
await delay(DRAIN_WAIT_MS);
spins += 1;
}
if (!isAlive()) {
throw new Error('stream transport closed');
}
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
};
channel.raw(channel.encode(`data: ${json}\n\n`));
};
const run = async () => {
try {
await driver(rawRequest, emit, isAlive);
} catch (err) {
if (isAlive()) {
const msg = err instanceof Error ? err.message : 'stream error';
try {
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`,
),
);
} catch {
/* controller already torn down */
}
channel.send({ status: 'failed', retcode: 1400, message: msg, wording: msg });
}
} finally {
signal.removeEventListener('abort', onAbort);
try {
controller.close();
} catch {
/* already closed */
}
channel.close();
}
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
};
void run();
});
}

View File

@@ -41,7 +41,15 @@ export const webuiSecurityHeaders: MiddlewareHandler = async (c, next) => {
);
};
export function extractBearerToken(request: Request): string {
export function extractWebuiSessionToken(request: Request): string {
const sessionToken = request.headers.get('x-snowluma-token');
// Authorization belongs to the proxy when it uses HTTP authentication.
// Only clients without the dedicated header use the legacy Bearer transport.
if (sessionToken !== null) {
return sessionToken;
}
const authorization = request.headers.get('authorization');
return authorization?.startsWith('Bearer ') ? authorization.slice(7) : '';
}

View File

@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger } from '@snowluma/common/logger';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
@@ -434,10 +435,6 @@ function invoke(options: RestoreBackupOptions, operation: RestoreOperation): voi
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'

View File

@@ -1,6 +1,8 @@
import { APP_VERSION } from '@snowluma/common/version';
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import { getRuntimeIntegrity, hasLowProcessIntegrity } from '@snowluma/bridge';
import {
clearManagedLogs,
configureFileTransport,
@@ -76,10 +78,10 @@ import { restoreBackup, RestoreTransactionError, type RestorePhase } from './res
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
import { createFramePusher } from './debug-stream';
import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools';
import { sseResponse } from './sse-response';
import { sseResponse as createSseResponse } from './sse-response';
import { bindStateStream } from './state-stream';
import type { StateBus, StateResource } from './state-bus';
import { startConnectionDiffLoop } from './connection-diff-loop';
import { createConnectionPoller } from './connection-diff-loop';
import { comparableConnectionSnapshot } from './connection-snapshot';
import { traceAuthenticatedWebuiMutation } from './mutation-trace';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
@@ -98,7 +100,9 @@ import {
sniffImageMime,
writeBackgroundImage,
} from './ui-config';
import { currentVersion, getUpdateInfo } from './update-check';
import { getUpdateInfo } from '../update/check';
import { createUpdateService } from '../update/service';
import { updateRoutes } from './update-routes';
import { buildFullTraceDownload } from './log-export';
import { loadNotificationsConfig, saveNotificationsConfig } from '../notifications/config';
import type { NotificationManager } from '../notifications/manager';
@@ -107,7 +111,7 @@ import { registerStorageRoutes } from './storage-routes';
import { LogStorageSettingsManager } from './storage-settings';
import {
clearAvatarSessionCookie,
extractBearerToken,
extractWebuiSessionToken,
readAvatarSessionToken,
registerLoginRequestSecurity,
setAvatarSessionCookie,
@@ -628,6 +632,8 @@ export async function initWebUI(
tlsEnabled?: boolean;
trustProxy?: string;
stateBus?: StateBus;
restart?: () => void;
updateRoot?: string;
} = {},
): Promise<{ port: number; stop: () => Promise<void> }> {
const host = listener.host || '127.0.0.1';
@@ -657,40 +663,6 @@ export async function initWebUI(
// rate-limit bucketing; this resolver fails closed with an empty address.
const getSecurityClientIp = makeClientIpResolver(trustProxyMode, '');
// Connection-status diff loop: OneBot adapters don't emit events for
// listening/connected/client-count changes, so we poll the snapshot at
// 500ms and publish 'connections' to the StateBus when it actually
// moves. One loop per server lifetime, lives until process exit (the
// setInterval is .unref'd inside the loop so it doesn't pin the event
// loop on shutdown).
//
// `pickComparable` strips `adapter.detail` — that's a localised human
// string assembled with HH:MM:SS timestamps from the last webhook
// delivery; including it in the diff would make every webhook event
// produce a publish (defeating the diff). We compare name + kind + status,
// plus the structured `lastErrorAt`: a new apply failure must refresh its
// error/time even when the adapter was already degraded. The SSE handler
// still ships the FULL snapshot (with `detail` and `lastError`) — it's only
// the diff key that's pruned.
//
// Trade-off: the rendered detail string (e.g. "3 个客户端", "上次推送
// 14:53:01") only refreshes on the next SSE push or on the 30s REST
// reconcile — not in real time. The user's original reported bugs were
// about process / account edges (which DO push instantly); refreshing
// adapter detail strings at sub-second cadence wasn't required. If it
// becomes one, surface client-count as a structured field on
// AdapterStatus and include it in the comparable.
let connectionDiffLoop: ReturnType<typeof startConnectionDiffLoop> | undefined;
if (listener.stateBus) {
connectionDiffLoop = startConnectionDiffLoop({
bus: listener.stateBus,
getSnapshot: () => oneBotManager.getConnectionStatuses(),
pickComparable: comparableConnectionSnapshot,
intervalMs: 500,
});
}
// Actual bound port (set just before serve; findAvailablePort may bump it).
// Read by GET /api/system/settings so the panel shows what's really live.
let boundPort = desiredPort;
@@ -746,6 +718,9 @@ export async function initWebUI(
}
const app = new Hono();
const shutdownStreams = new AbortController();
const sseResponse = (c: Context, start: Parameters<typeof createSseResponse>[1]) =>
createSseResponse(c.req.raw.signal, start, shutdownStreams.signal);
app.use('*', webuiSecurityHeaders);
registerLoginRequestSecurity(app);
const storageManagement = new StorageManagementService({
@@ -800,7 +775,7 @@ export async function initWebUI(
return next();
}
const token = extractBearerToken(c.req.raw);
const token = extractWebuiSessionToken(c.req.raw);
if (!token) {
return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
@@ -841,11 +816,6 @@ export async function initWebUI(
});
});
// Periodic janitor — keeps sessionTokens / loginAttempts from growing
// unbounded and replaces the per-request O(n) sweep we used to do.
const tokenJanitor = setInterval(purgeExpiredTokens, 60_000);
tokenJanitor.unref?.();
// ─── Login ───────────────────────────────────────────────────────────────
app.post('/api/login', async (c) => {
const ip = getClientIp(c);
@@ -1311,11 +1281,15 @@ export async function initWebUI(
return c.json({ status: 'running' });
});
// Advisory update check — compares the running build against the latest
// GitHub stable release and links the user to it. Read-only: SnowLuma
// never downloads or applies the update itself. `?force=1` bypasses the
// server-side cache (the "立即检查" button). Never errors out — a failed
// check returns `{ hasUpdate: false, error }` and the UI degrades quietly.
const updater = await createUpdateService(
listener.restart ? listener.updateRoot : undefined,
APP_VERSION,
);
app.route(
'/api/update',
updateRoutes(updater, () => listener.restart?.()),
);
app.get('/api/update/check', async (c) => {
const force = c.req.query('force') === 'true' || c.req.query('force') === '1';
return c.json(await getUpdateInfo(force));
@@ -1351,7 +1325,7 @@ export async function initWebUI(
return usage;
}
app.get('/api/system', (c) => {
app.get('/api/system', async (c) => {
const cpus = os.cpus();
const usage = sampleCpuLoad();
const totalMem = os.totalmem();
@@ -1384,6 +1358,7 @@ export async function initWebUI(
},
runtime: {
pid: process.pid,
lowIntegrity: hasLowProcessIntegrity(await getRuntimeIntegrity()),
rss: runtimeMemory.rss,
heapTotal: runtimeMemory.heapTotal,
heapUsed: runtimeMemory.heapUsed,
@@ -1395,7 +1370,7 @@ export async function initWebUI(
// ── System settings (WebUI listener) — Wave A1 ──
// Listener-level changes (port/host/TLS) are persisted but apply only on the
// next restart (no supervisor → no self-restart). The panel surfaces which
// next restart. The panel surfaces which
// fields are currently overridden by env so edits that won't take effect are
// visible.
const SYSTEM_CERT_PATH = path.join('config', 'cert.pem');
@@ -1670,9 +1645,8 @@ export async function initWebUI(
});
// Invoke a Stream API action (or any action) and relay every frame to the
// browser over an SSE body. The frontend reads this with fetch()+a stream
// reader (Bearer auth in the header), so — unlike /api/debug/stream — it does
// NOT need a query-token allowlist entry. Frames are never dropped.
// browser over an SSE body. The frontend uses fetch()+a stream reader so
// the session token stays in a header on this POST. Frames are never dropped.
app.post('/api/debug/invoke-stream', async (c) => {
let body: unknown;
@@ -1713,7 +1687,7 @@ export async function initWebUI(
return buildStreamInvokeResponse(
(rq, emit, alive) => inst.invokeStream(rq, emit, alive),
rawRequest,
c.req.raw.signal,
AbortSignal.any([c.req.raw.signal, shutdownStreams.signal]),
);
});
@@ -1789,8 +1763,15 @@ export async function initWebUI(
// connection-status diff loop). 50ms per-resource debounce coalesces a
// burst (e.g. multiple HookSessions flipping status simultaneously).
const stateBus = listener.stateBus;
const subscribeConnections =
stateBus &&
createConnectionPoller({
bus: stateBus,
getSnapshot: () => oneBotManager.getConnectionStatuses(),
pickComparable: comparableConnectionSnapshot,
});
app.get('/api/state/stream', (c) => {
if (!stateBus) {
if (!stateBus || !subscribeConnections) {
// Build without state-wiring (e.g. a future headless mode) — clients
// fall back to the REST endpoints. Treat as endpoint-not-here.
return c.text('state stream not configured', 503);
@@ -1798,6 +1779,7 @@ export async function initWebUI(
const liveBus = stateBus;
return sseResponse(c, (ch) => {
ch.onClose(subscribeConnections());
const pushFrame = createFramePusher({
desiredSize: ch.desiredSize,
enqueue: ch.raw,
@@ -1849,7 +1831,7 @@ export async function initWebUI(
app.get('/api/logs/export/trace', (c) => {
const exportedAt = new Date().toISOString();
const download = buildFullTraceDownload(getLogSnapshot(), {
version: currentVersion(),
version: APP_VERSION,
operatingSystem: os.platform(),
architecture: os.arch(),
nodeVersion: process.version,
@@ -1946,30 +1928,6 @@ export async function initWebUI(
processAction('refresh', (pid) => hookManager!.refreshProcess(pid)),
);
app.get('/api/processes/:pid/probe-login', async (c) => {
if (!hookManager) {
return c.json({ info: null, message: 'hook manager is not available' }, 503);
}
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) {
return c.json({ info: null, message: 'invalid pid' }, 400);
}
try {
const info = await hookManager.probeProcessLoginInfo(pid);
return c.json({ info });
} catch (err) {
log.warn(
'probe-login pid=%d failed: %s',
pid,
err instanceof Error ? err.message : String(err),
);
return c.json({ info: null, message: '探测失败' }, 500);
}
});
app.get('/api/config/:uin', (c) => {
const uin = c.req.param('uin');
@@ -2363,10 +2321,13 @@ export async function initWebUI(
},
);
});
const tokenJanitor = setInterval(purgeExpiredTokens, 60_000);
tokenJanitor.unref();
return {
port: finalPort,
async stop() {
connectionDiffLoop?.dispose();
clearInterval(tokenJanitor);
shutdownStreams.abort();
await new Promise<void>((resolve, reject) => {
listeningServer.close((err) => (err ? reject(err) : resolve()));
});

View File

@@ -1,38 +1,25 @@
import { type Context } from 'hono';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('WebUI.SSE');
/**
* The per-connection channel handed to an SSE endpoint's `start` callback.
* Everything the endpoint needs to talk to the client, without owning the
* transport lifecycle (heartbeat / teardown / abort / headers).
*/
export interface SseChannel {
/** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */
raw(chunk: Uint8Array): void;
/** Encode a string to bytes (shared TextEncoder). */
encode(s: string): Uint8Array;
/** Convenience: enqueue one `data: <json>\n\n` frame. */
send(payload: unknown): void;
/** Register a cleanup to run once on teardown (unsubscribe / dispose). */
onClose(fn: () => void): void;
/** True after teardown — guard sends from late subscription callbacks. */
onClose(cleanup: () => void): void;
close(): void;
isClosed(): boolean;
/** Underlying controller backpressure signal, for `createFramePusher`. */
desiredSize(): number | null;
}
/**
* The SSE HTTP transport shell shared by the WebUI's live endpoints. Owns the
* TextEncoder, a `closed` guard, a 15s `: heartbeat` keep-alive, teardown
* (clear heartbeat → run registered cleanups → close the controller), safe
* enqueue (a throw means the peer dropped → teardown), the abort listener, and
* the `text/event-stream` headers. `start` wires up the endpoint-specific
* subscription + initial sends via the channel.
*
* Each of `/api/debug/stream`, `/api/state/stream`, `/api/logs/stream`
* previously hand-copied this ~40-line skeleton; a heartbeat-interval /
* teardown-order / header change had to be kept in sync across all three.
*/
export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response {
/** Owns stream cancellation, subscriptions and the keep-alive timer. */
export function sseResponse(
request: AbortSignal,
start: (channel: SseChannel) => void,
shutdown?: AbortSignal,
): Response {
const signal = shutdown ? AbortSignal.any([request, shutdown]) : request;
let cancel!: () => void;
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const encoder = new TextEncoder();
@@ -40,57 +27,78 @@ export function sseResponse(c: Context, start: (ch: SseChannel) => void): Respon
let heartbeat: ReturnType<typeof setInterval> | undefined;
const cleanups: Array<() => void> = [];
const teardown = () => {
const cleanup = (fn: () => void) => {
try {
fn();
} catch (error) {
log.warn('stream cleanup failed: %s', error);
}
};
const teardown = (closeStream = true) => {
if (closed) {
return;
}
closed = true;
clearInterval(heartbeat);
signal.removeEventListener('abort', onAbort);
if (heartbeat) {
clearInterval(heartbeat);
}
for (const fn of cleanups) {
try {
fn();
} catch {
/* ignore */
}
}
try {
if (closeStream) {
controller.close();
} catch {
/* ignore */
}
cleanups.splice(0).forEach(cleanup);
};
const onAbort = () => teardown();
cancel = () => teardown(false);
signal.addEventListener('abort', onAbort, { once: true });
if (signal.aborted) {
teardown();
return;
}
const raw = (chunk: Uint8Array) => {
if (closed) {
return;
}
try {
if (!closed) {
controller.enqueue(chunk);
} catch {
teardown();
}
};
const ch: SseChannel = {
const channel: SseChannel = {
raw,
encode: (s) => encoder.encode(s),
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
onClose: (fn) => {
cleanups.push(fn);
encode: (text) => encoder.encode(text),
send: (payload) => {
if (!closed) {
raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`));
}
},
onClose: (fn) => {
if (closed) {
cleanup(fn);
} else {
cleanups.push(fn);
}
},
close: () => teardown(),
isClosed: () => closed,
desiredSize: () => controller.desiredSize,
};
start(ch);
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
try {
start(channel);
if (!closed) {
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
}
} catch (error) {
teardown();
throw error;
}
},
cancel() {
cancel();
},
});
return new Response(stream, {

View File

@@ -1,21 +1,6 @@
/**
* StateBus — pure pub/sub for WebUI state-resource invalidations.
*
* Three resources are tracked: `processes`, `qq-list`, `connections`. A
* publisher (HookSession status change, BridgeManager session start/close,
* the connection-status diff loop) calls `publish(resource)` to signal "the
* snapshot for THIS resource is stale; whoever cares should re-read". The
* `/api/state/stream` SSE handler subscribes, debounces, and pushes fresh
* snapshots to connected WebUI clients.
*
* Intentionally pure pub/sub (no debounce, no snapshot caching): debounce
* and snapshot reads live with the subscriber so different consumers can
* coalesce on different cadences. Snapshot semantics on fan-out: the
* subscriber set is FROZEN at the start of each publish, so a listener
* that subscribes during the fan-out only sees the FOLLOWING publish, and
* a listener that unsubscribes mid-fan-out does not prevent its peers
* from completing.
*/
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('WebUI.State');
export type StateResource = 'processes' | 'qq-list' | 'connections';
@@ -54,18 +39,17 @@ export class StateBus {
return;
}
// Snapshot the current subscribers — any subscribe()/unsubscribe()
// called by a listener during the fan-out takes effect only for the
// NEXT publish, not this one.
const snapshot = [...this.listeners];
for (const fn of snapshot) {
try {
fn(resource);
} catch {
// Subscriber-internal failure is its own problem. The bus's job
// is to keep delivery moving — surfacing an error here would
// partially abort the fan-out and create skip-the-listener bugs.
} catch (error) {
log.warn(
'state listener failed: resource=%s error=%s',
resource,
error instanceof Error ? error.message : String(error),
);
}
}
}

View File

@@ -1,21 +1,9 @@
/**
* Bind a StateBus to an SSE-friendly `send` callback: every publish becomes
* a debounced fresh-snapshot frame, and `sendAllInitial()` primes a new
* connection with one frame per resource.
*
* Decoupled from the HTTP layer so the route handler in server.ts can drop
* its responsibility down to "open a ReadableStream, hand its enqueue to
* bindStateStream, abort tears it down". Pure logic = unit-testable with
* fake timers; no Response/controller mocking needed.
*
* Per-resource debounce, not global: an 'qq-list' churn during a slow
* 'processes' burst must not delay the qq-list frame, and a 'connections'
* diff loop running at 500ms must not coalesce 10 unrelated processes
* events into one. Each resource is its own timer.
*/
import { errorMessage } from '@snowluma/common/errors';
import { createLogger } from '@snowluma/common/logger';
import type { StateBus, StateResource } from './state-bus';
const log = createLogger('WebUI.StateStream');
export interface StateStreamFrame {
resource: StateResource;
data: unknown;
@@ -45,112 +33,88 @@ const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connec
export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle {
const debounceMs = opts.debounceMs ?? 50;
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
// Single-flight per resource: at most one in-flight flush per resource so
// an uneven snapshot latency cannot interleave sends out of order (a slow
// earlier snapshot landing AFTER a later one, leaving the client's last
// observed frame stale). Publishes arriving while a flush is in flight
// mark `pending` and rearm the debounce timer once the flush completes.
const inFlight = new Set<StateResource>();
const pending = new Set<StateResource>();
let disposed = false;
const flush = async (resource: StateResource): Promise<void> => {
if (disposed) {
return;
function resourceStream(resource: StateResource) {
let timer: ReturnType<typeof setTimeout> | null = null;
let task: Promise<void> | null = null;
let pending = false;
function clearTimer() {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
}
inFlight.add(resource);
try {
let data: unknown;
try {
data = await opts.snapshot(resource);
} catch {
// Per-resource snapshot failure (e.g. listProcesses threw): skip
// this frame so siblings keep flowing. The next publish for the
// same resource gets a fresh attempt.
return;
function flush(): Promise<void> {
if (disposed) {
return Promise.resolve();
}
if (task) {
return task;
}
clearTimer();
task = Promise.resolve()
.then(async () => {
if (disposed) {
return;
}
const data = await opts.snapshot(resource);
if (!disposed) {
opts.send({ resource, data });
}
})
.catch((error) => {
log.warn('state stream %s failed: %s', resource, errorMessage(error));
})
.finally(() => {
task = null;
if (pending) {
pending = false;
schedule();
}
});
return task;
}
function schedule(): void {
if (disposed) {
return;
}
try {
opts.send({ resource, data });
} catch {
// Downstream consumer (e.g. closed SSE controller) — same isolation
// contract as snapshot failures.
if (task) {
pending = true;
return;
}
} finally {
inFlight.delete(resource);
// If a publish arrived during the in-flight window, schedule one
// follow-up flush. Re-uses the debounce so a sustained publish
// stream produces at most one frame per (debounceMs + flushLatency),
// not back-to-back frames.
if (!disposed && pending.has(resource)) {
pending.delete(resource);
schedule(resource);
}
clearTimer();
timer = setTimeout(() => void flush(), debounceMs);
}
return { flush, schedule, clearTimer };
}
const streams = {
processes: resourceStream('processes'),
'qq-list': resourceStream('qq-list'),
connections: resourceStream('connections'),
};
const schedule = (resource: StateResource): void => {
if (disposed) {
return;
}
if (inFlight.has(resource)) {
// Defer to the post-flush re-arm; no new timer until the in-flight
// send completes. This is the load-bearing invariant for ordering.
pending.add(resource);
return;
}
const existing = timers.get(resource);
if (existing) {
clearTimeout(existing);
}
const t = setTimeout(() => {
timers.delete(resource);
void flush(resource);
}, debounceMs);
timers.set(resource, t);
};
const unsubscribe = opts.bus.subscribe(schedule);
const unsubscribe = opts.bus.subscribe((resource) => streams[resource].schedule());
return {
async sendAllInitial(): Promise<void> {
if (disposed) {
return;
}
// Fire all three in parallel. Each resource's snapshot is independent
// so a slow listProcesses() doesn't gate qq-list/connections. Each
// call goes through the single-flight gate so a concurrent bus
// publish during this initial fan-out coalesces correctly.
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
await Promise.all(ALL_RESOURCES.map((resource) => streams[resource].flush()));
},
dispose(): void {
if (disposed) {
return;
}
disposed = true;
unsubscribe();
for (const t of timers.values()) {
clearTimeout(t);
}
timers.clear();
pending.clear();
ALL_RESOURCES.forEach((resource) => streams[resource].clearTimer());
},
};
}

View File

@@ -1,80 +1,31 @@
/**
* State-wiring — couples the publisher edges (HookManager session events,
* BridgeManager session-started / session-closed) to a fresh StateBus so the
* `/api/state/stream` SSE handler can push snapshot invalidations to the
* WebUI without REST polling.
*
* Decoupling rationale:
* - HookManager owns the per-process state-machine; it knows when a
* session's `listProcesses()` view changes. We feed it `onSessionsChanged`
* (callable from outside the bridge package) so this file is the ONLY
* place that imports both the bus and HookManager's dep shape.
* - BridgeManager fires `session-started` / `session-closed` listeners on
* account edges (the OneBot instance list mutates around these). We add
* listeners directly so `qq-list` + `connections` invalidate at the right
* moment without modifying BridgeManager.
*
* `dispose()` sets a latch and neuters the bus. BridgeManager listeners stay
* attached; further session edges publish nothing. Process shutdown disposes
* this wiring before Hook teardown so exit-time closed is not a WebUI invalidate.
*/
import { StateBus } from './state-bus';
import type { BridgeManager } from '../bridge/manager';
import type { BridgeSessionSource } from '../bridge/bridge-interface';
export interface StateWiring {
/** The bus the SSE handler subscribes to. */
readonly bus: StateBus;
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
onSessionsChanged: () => void;
/** Hook into a BridgeManager so its session edges publish 'qq-list' and
* 'connections'. Can be called at most once per wiring (subsequent calls
* add duplicate listeners). */
bindBridgeManager(bm: BridgeManager): void;
/** Drop every listener + neuter the bus so further publishes do nothing. */
onSessionsChanged(): void;
dispose(): void;
}
export function createStateWiring(): StateWiring {
export function createStateWiring(bridgeManager: BridgeSessionSource): StateWiring {
const bus = new StateBus();
let disposed = false;
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
if (disposed) {
return;
}
bus.publish(resource);
const publishAccountChange = (): void => {
bus.publish('qq-list');
bus.publish('connections');
};
const unsubscribe = bridgeManager.subscribeSessions({
started: publishAccountChange,
closed: publishAccountChange,
});
return {
bus,
onSessionsChanged: () => publish('processes'),
bindBridgeManager(bm: BridgeManager): void {
// Account appeared: the qq-list response gains an entry and the
// connections response gains the new account's adapter row. Two
// distinct resource invalidations, in source-of-truth order
// (account exists → only then can adapters be enumerated for it).
bm.addSessionStartedListener(() => {
publish('qq-list');
publish('connections');
});
// Account disappeared: same two resources shrink, same order so a
// racy WebUI receiving both events independently sees the qq-list
// shrink before it tries to render connections for a uin that's
// about to vanish.
bm.addSessionClosedListener(() => {
publish('qq-list');
publish('connections');
});
},
onSessionsChanged: () => bus.publish('processes'),
dispose(): void {
if (disposed) {
return;
}
disposed = true;
bus.dispose();
unsubscribe();
},
};
}

View File

@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import fs from 'node:fs';
import path from 'node:path';
import type { LogCleanupResult, LogStorageStatus } from '@snowluma/common/log-file-transport';
@@ -377,10 +378,6 @@ function validateAccountStorageCategory(value: string): AccountStorageCategory {
throw new StorageManagementInputError(`unsupported account storage category: ${value}`);
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function redactFilesystemPath(message: string, filePath: string, label: string): string {
const absolute = path.resolve(filePath);
return message.split(absolute).join(label).split(filePath).join(label);

View File

@@ -1,4 +1,5 @@
import { isRealUin } from '@snowluma/common/uin';
import { isObject } from '@snowluma/common/coerce';
import type { Hono } from 'hono';
import {
StorageAccountOnlineError,
@@ -367,7 +368,3 @@ function cleanupFailureItem(failure: StorageCleanupResult['failures'][number]):
return failure.item;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}

Some files were not shown because too many files have changed in this diff Show More