Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
68deb48811 | ||
|
|
bdf224cbc9 | ||
|
|
a69ec6fedb | ||
|
|
39d1f40583 | ||
|
|
0cdb389831 | ||
|
|
e60bc3bad2 | ||
|
|
c15b2d857d | ||
|
|
1001f55a06 | ||
|
|
0f358b2ac2 | ||
|
|
652b9c4eda | ||
|
|
95a2d0d257 | ||
|
|
fb39af6c28 | ||
|
|
9b165a8971 | ||
|
|
1faa6c58fa | ||
|
|
38a7c3da63 | ||
|
|
4e2b6b1200 | ||
|
|
5032cbb8c0 | ||
|
|
c54aeffc77 | ||
|
|
f6ca9d5f65 | ||
|
|
8e24995fc3 | ||
|
|
b6d86a586d | ||
|
|
b90d34c9d8 | ||
|
|
5150d83403 | ||
|
|
d6dd748beb | ||
|
|
3c4dbe31a8 | ||
|
|
4c83cc826e | ||
|
|
f85b28d23c | ||
|
|
c7428363cb | ||
|
|
20f48d11ec | ||
|
|
ceb8387ea6 | ||
|
|
7c0519f75f | ||
|
|
effeb66554 | ||
|
|
7496479782 | ||
|
|
6ceb2a3900 |
No files matched your search
@@ -11,6 +11,9 @@ trim_trailing_whitespace = true
|
||||
[*.{json,yml,yaml,md}]
|
||||
indent_size = 2
|
||||
|
||||
[*.{ts,tsx,mts,cts}]
|
||||
indent_size = 4
|
||||
|
||||
[*.py]
|
||||
indent_size = 4
|
||||
|
||||
|
||||
@@ -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`,拖到本输入框上传。
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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\` |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
22.13.0
|
||||
24.21.0
|
||||
@@ -0,0 +1,17 @@
|
||||
# Dependencies, build outputs and local tooling
|
||||
node_modules/
|
||||
.pnpm-store/
|
||||
dist/
|
||||
coverage/
|
||||
.turbo/
|
||||
.vite/
|
||||
.claude/
|
||||
dev/
|
||||
pnpm-lock.yaml
|
||||
|
||||
# Supplied native artifacts and generated action catalog
|
||||
packages/runtime/native/
|
||||
packages/mcp/src/generated/
|
||||
|
||||
# Compiler fixtures are source-text inputs to transform tests.
|
||||
packages/proton/test/fixtures/
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf",
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.ts", "*.tsx", "*.mts", "*.cts"],
|
||||
"options": {
|
||||
"tabWidth": 4
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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` |
|
||||
@@ -59,6 +66,8 @@ pnpm --filter @snowluma/onebot test # example: tests for the affected package
|
||||
pnpm --filter webui test # the frontend package has no @snowluma/ prefix
|
||||
```
|
||||
|
||||
TypeScript formatting uses the root [Prettier configuration](.prettierrc.json), [local ESLint formatting rules](eslint.format.config.ts), and [ignore list](.prettierignore). Use `pnpm format` for all TS/TSX/MTS/CTS files and `pnpm format:check` for a read-only check. For selected files, run `pnpm exec eslint --config eslint.format.config.ts --fix <paths>` followed by `pnpm exec prettier --write <paths>`. These commands enforce four-space indentation, braces around control-statement bodies, and blank lines around statement blocks while preserving other logical spacing. They are separate from CI and its code-quality lint rules. Generated catalogs and compiler fixtures retain their source formatting.
|
||||
|
||||
Use focused tests while iterating. Before handing off a code change, run the full checks required by CONTRIBUTING.md and report anything that could not run. [PR CI](.github/workflows/ci.yml) is the reference; `pnpm run ci` reproduces its commands locally, including dependency installation and the generated-catalog check.
|
||||
|
||||
- **Documentation-only changes:** verify links, paths, commands and `git diff --check`; runtime tests do not validate prose.
|
||||
@@ -79,7 +88,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful
|
||||
- **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content.
|
||||
- **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible.
|
||||
- **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter.
|
||||
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and two-space indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.
|
||||
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and four-space TypeScript indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.
|
||||
- **Keep diagnostics safe.** Use existing sanitization when recording external input. Credentials, private keys, private account data and unredacted captures do not belong in commits, fixtures or public reports.
|
||||
|
||||
## Generated files and related changes
|
||||
|
||||
@@ -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)
|
||||
+33
-6
@@ -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` 应满足上述版本要求,否则安装会直接失败。
|
||||
|
||||
### 拉代码、装依赖、跑起来
|
||||
@@ -104,7 +111,7 @@ git checkout -b fix/onebot-mention-encoding
|
||||
### 2. 写代码
|
||||
|
||||
- **保持改动聚焦**:一个 PR 只做一件事。顺手发现的其他问题请单独开 issue 或新 PR。
|
||||
- **跟随既有风格**:不要为了你个人偏好引入大规模格式化或重命名。
|
||||
- **跟随既有风格**:TypeScript 排版以仓库 Prettier 配置为准;普通功能或修复 PR 只格式化涉及的文件,避免混入无关的大规模格式化或重命名。
|
||||
- **写测试**:修 bug 时优先写一个能复现该 bug 的测试,确认它会 fail,再让它 pass。新增功能至少补上 happy path 的测试。
|
||||
- **不要添加无意义的注释**:标识符已经说清楚的事情不需要再写一遍。注释应当解释"为什么",而不是"做了什么"。
|
||||
|
||||
@@ -169,15 +176,35 @@ git push origin fix/onebot-mention-encoding
|
||||
### 代码风格
|
||||
|
||||
- TypeScript 严格模式,按 `tsconfig.base.json` 配置。
|
||||
- TypeScript 使用四空格缩进,控制语句始终带大括号。排版由根目录 [`.prettierrc.json`](./.prettierrc.json) 和独立的本地 [ESLint 格式规则](./eslint.format.config.ts) 管理;普通 `pnpm lint` 负责代码质量检查。
|
||||
- 优先用现有抽象,不要为"假想的未来需求"提前抽象。
|
||||
- 不要给内部函数加防御性的参数校验,除非是系统边界(用户输入、外部 API)。
|
||||
- 不要保留死代码、被注释掉的代码或者 `// TODO` 没有具体上下文的占位。
|
||||
|
||||
从仓库根目录运行本地格式化命令:
|
||||
|
||||
```bash
|
||||
pnpm format # 为全部 TS/TSX/MTS/CTS 补大括号、空行并排版
|
||||
pnpm format:check # 检查上述规则,不修改文件
|
||||
|
||||
# 只格式化指定文件:先处理控制语句与空行,再排版
|
||||
pnpm exec eslint --config eslint.format.config.ts --fix packages/core/src/index.ts
|
||||
pnpm exec prettier --write packages/core/src/index.ts
|
||||
```
|
||||
|
||||
格式化范围排除 [`.prettierignore`](./.prettierignore) 中的构建产物、生成文件和编译器测试夹具;普通源码与测试都参与格式化。这两个命令供本地使用,不接入 CI。
|
||||
|
||||
空行采用保守规则:在语句块前后留空行,保留已有逻辑分段,不强行拆开连续声明或普通调用,也不在每条 `return`、`break` 前插空行;共用同一分支的连续 `case` 标签保持相邻。JSON、YAML 等文件继续使用原有缩进。
|
||||
|
||||
编辑器请选择项目本地安装的 Prettier 并读取仓库配置。VS Code 可安装
|
||||
`esbenp.prettier-vscode`,将 TypeScript / TypeScript React 的默认格式化器设为
|
||||
Prettier,并按需开启保存时格式化。
|
||||
|
||||
### 测试
|
||||
|
||||
- 单测放在被测代码同包的 `tests/` 或同目录的 `*.test.ts`,按既有风格走。
|
||||
- 测试要描述行为,不要测实现细节。`it('should call internal foo')` 这种是反例。
|
||||
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/core/src/onebot/` 下的 `fake-bridge` 类测试。
|
||||
- 涉及 IO / 时序 / 外部进程的,用现有的 fake/stub 模式,参考 `packages/onebot/tests/` 中的 Bridge 测试替身。
|
||||
|
||||
### 文档
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
+82
-81
@@ -1,14 +1,14 @@
|
||||
import js from '@eslint/js';
|
||||
import eslintConfigPrettier from 'eslint-config-prettier/flat';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import reactRefresh from 'eslint-plugin-react-refresh';
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1');
|
||||
const tsconfigRootDir = import.meta.dirname;
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores([
|
||||
export const sourceIgnores = globalIgnores([
|
||||
'**/dist/**',
|
||||
'**/node_modules/**',
|
||||
'**/coverage/**',
|
||||
@@ -20,89 +20,90 @@ export default defineConfig([
|
||||
'**/test/fixtures/**',
|
||||
'packages/runtime/native/**',
|
||||
'packages/mcp/src/generated/**',
|
||||
]),
|
||||
{
|
||||
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
|
||||
extends: [js.configs.recommended],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
sourceType: 'module',
|
||||
globals: {
|
||||
...globals.es2023,
|
||||
...globals.node,
|
||||
},
|
||||
]);
|
||||
|
||||
export default defineConfig([
|
||||
sourceIgnores,
|
||||
{
|
||||
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
|
||||
extends: [js.configs.recommended],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
sourceType: 'module',
|
||||
globals: {
|
||||
...globals.es2023,
|
||||
...globals.node,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'no-unused-vars': 'off',
|
||||
'no-useless-assignment': 'off',
|
||||
'prefer-const': 'off',
|
||||
'preserve-caught-error': 'off',
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'no-unused-vars': 'off',
|
||||
'no-useless-assignment': 'off',
|
||||
'prefer-const': 'off',
|
||||
'preserve-caught-error': 'off',
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'prefer-const': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/no-empty-object-type': 'off',
|
||||
'@typescript-eslint/no-this-alias': 'off',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'warn',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
{
|
||||
files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'prefer-const': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/no-empty-object-type': 'off',
|
||||
'@typescript-eslint/no-this-alias': 'off',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'warn',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
{
|
||||
files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
{
|
||||
// OIDB service layer is namespace-per-cmd by design — the
|
||||
// structural-typing contract (namespace IS the OidbCallSpec) and
|
||||
// the file:cmd 1:1 mapping are the whole point. Disable the
|
||||
// module-syntax preference here only.
|
||||
files: [
|
||||
'packages/protocol/src/oidb-services/**/*.ts',
|
||||
'packages/protocol/tests/oidb-services/**/*.ts',
|
||||
],
|
||||
rules: {
|
||||
'@typescript-eslint/no-namespace': 'off',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
// OIDB service layer is namespace-per-cmd by design — the
|
||||
// structural-typing contract (namespace IS the OidbCallSpec) and
|
||||
// the file:cmd 1:1 mapping are the whole point. Disable the
|
||||
// module-syntax preference here only.
|
||||
files: [
|
||||
'packages/protocol/src/oidb-services/**/*.ts',
|
||||
'packages/protocol/tests/oidb-services/**/*.ts',
|
||||
],
|
||||
rules: {
|
||||
'@typescript-eslint/no-namespace': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'],
|
||||
extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'prefer-const': 'off',
|
||||
'react-refresh/only-export-components': 'off',
|
||||
'react-hooks/set-state-in-effect': 'off',
|
||||
{
|
||||
files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'],
|
||||
extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'prefer-const': 'off',
|
||||
'react-refresh/only-export-components': 'off',
|
||||
'react-hooks/set-state-in-effect': 'off',
|
||||
},
|
||||
},
|
||||
},
|
||||
eslintConfigPrettier,
|
||||
]);
|
||||
@@ -0,0 +1,39 @@
|
||||
import stylistic from '@stylistic/eslint-plugin';
|
||||
import { defineConfig } from 'eslint/config';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import { sourceIgnores } from './eslint.config.ts';
|
||||
|
||||
// Local formatting only; CI continues to use eslint.config.ts for code quality.
|
||||
export default defineConfig([
|
||||
sourceIgnores,
|
||||
{
|
||||
// Preserve quality-rule suppressions when running only formatting rules.
|
||||
linterOptions: { reportUnusedDisableDirectives: 'off' },
|
||||
},
|
||||
{
|
||||
files: ['**/*.{ts,tsx,mts,cts}'],
|
||||
languageOptions: {
|
||||
parser: tseslint.parser,
|
||||
},
|
||||
plugins: {
|
||||
'@stylistic': stylistic,
|
||||
'@typescript-eslint': tseslint.plugin,
|
||||
'react-hooks': reactHooks,
|
||||
},
|
||||
rules: {
|
||||
curly: ['error', 'all'],
|
||||
'@stylistic/padding-line-between-statements': [
|
||||
'error',
|
||||
{ blankLine: 'always', prev: '*', next: 'block-like' },
|
||||
{ blankLine: 'always', prev: 'block-like', next: '*' },
|
||||
// Stacked case labels share a branch and must stay adjacent.
|
||||
{
|
||||
blankLine: 'never',
|
||||
prev: { selector: 'SwitchCase[consequent.length=0]' },
|
||||
next: ['case', 'default'],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
+9
-23
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.14.22",
|
||||
"version": "2.0.1",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -25,6 +25,8 @@
|
||||
"typecheck": "pnpm -r --if-present typecheck",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"format": "eslint --config eslint.format.config.ts --fix \"**/*.{ts,tsx,mts,cts}\" && prettier --write \"**/*.{ts,tsx,mts,cts}\"",
|
||||
"format:check": "eslint --config eslint.format.config.ts \"**/*.{ts,tsx,mts,cts}\" && prettier --check \"**/*.{ts,tsx,mts,cts}\"",
|
||||
"ci": "node tools/ci-check.mjs",
|
||||
"start": "node dist/index.mjs",
|
||||
"bump": "node tools/bump-version.mjs",
|
||||
@@ -32,39 +34,23 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@stylistic/eslint-plugin": "5.10.0",
|
||||
"@vitest/coverage-istanbul": "4.1.4",
|
||||
"@vitest/coverage-v8": "^4.1.4",
|
||||
"cross-env": "^10.1.0",
|
||||
"eslint": "^10.2.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.5.0",
|
||||
"jiti": "^2.6.1",
|
||||
"prettier": "3.9.10",
|
||||
"typescript": "catalog:",
|
||||
"typescript-eslint": "^8.58.2"
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.14.22",
|
||||
"version": "2.0.1",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
+595
-452
File diff suppressed because it is too large.
Load diff
@@ -1,58 +1,73 @@
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { packetTimeoutMs } from './packet-timeout';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
QqHookClient,
|
||||
type QqHookSendReply,
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
QqHookClient,
|
||||
} from './qq-hook-client';
|
||||
|
||||
export type OutboundHealthListener = (healthy: boolean) => void;
|
||||
|
||||
export class HookPacketClient implements PacketSender {
|
||||
private outboundHealthy = true;
|
||||
private outboundHealthy = true;
|
||||
|
||||
constructor(
|
||||
private readonly client: QqHookClient,
|
||||
private readonly onOutboundHealthChanged?: OutboundHealthListener,
|
||||
) { }
|
||||
constructor(
|
||||
private readonly client: QqHookClient,
|
||||
private readonly onOutboundHealthChanged?: OutboundHealthListener,
|
||||
) {}
|
||||
|
||||
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
|
||||
async sendPacket(
|
||||
serviceCmd: string,
|
||||
body: Buffer,
|
||||
timeoutMs = packetTimeoutMs(),
|
||||
): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: 'qq_hook client is not logged in',
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const reply = await this.client.send(serviceCmd, body, {
|
||||
wantReply: true,
|
||||
replyTimeoutMs: timeoutMs,
|
||||
});
|
||||
this.setOutboundHealthy(true);
|
||||
return {
|
||||
success: reply.error === 0,
|
||||
gotResponse: true,
|
||||
errorCode: reply.error,
|
||||
errorMessage: reply.message,
|
||||
responseData: reply.body,
|
||||
};
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof HookPipeRequestError &&
|
||||
error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE
|
||||
) {
|
||||
this.setOutboundHealthy(false);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const reply = await this.client.send(serviceCmd, body, {
|
||||
wantReply: true,
|
||||
replyTimeoutMs: timeoutMs,
|
||||
}) as QqHookSendReply;
|
||||
this.setOutboundHealthy(true);
|
||||
return {
|
||||
success: reply.error === 0,
|
||||
gotResponse: true,
|
||||
errorCode: reply.error,
|
||||
errorMessage: reply.message || '',
|
||||
responseData: reply.body,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof HookPipeRequestError
|
||||
&& error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE) {
|
||||
this.setOutboundHealthy(false);
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
private setOutboundHealthy(healthy: boolean): void {
|
||||
if (this.outboundHealthy === healthy) {
|
||||
return;
|
||||
}
|
||||
|
||||
private setOutboundHealthy(healthy: boolean): void {
|
||||
if (this.outboundHealthy === healthy) return;
|
||||
this.outboundHealthy = healthy;
|
||||
this.onOutboundHealthChanged?.(healthy);
|
||||
}
|
||||
this.outboundHealthy = healthy;
|
||||
this.onOutboundHealthChanged?.(healthy);
|
||||
}
|
||||
}
|
||||
@@ -1,130 +1,165 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { readFileSync } from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
export interface HookRuntimeDirDeps {
|
||||
platform?: NodeJS.Platform;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
ownUid?: number;
|
||||
readText?: (file: string) => string;
|
||||
platform?: NodeJS.Platform;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
ownUid?: number;
|
||||
readText?: (file: string) => string;
|
||||
}
|
||||
|
||||
function configuredDirectory(value: string | undefined, variable: string): string | null {
|
||||
if (!value) return null;
|
||||
if (!path.isAbsolute(value)) {
|
||||
throw new Error(`${variable} must be an absolute path`);
|
||||
}
|
||||
return value;
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!path.isAbsolute(value)) {
|
||||
throw new Error(`${variable} must be an absolute path`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseProcessEnvironment(raw: string): NodeJS.ProcessEnv {
|
||||
const result: NodeJS.ProcessEnv = {};
|
||||
for (const entry of raw.split('\0')) {
|
||||
if (!entry) continue;
|
||||
const separator = entry.indexOf('=');
|
||||
if (separator <= 0) continue;
|
||||
result[entry.slice(0, separator)] = entry.slice(separator + 1);
|
||||
}
|
||||
return result;
|
||||
const result: NodeJS.ProcessEnv = {};
|
||||
|
||||
for (const entry of raw.split('\0')) {
|
||||
if (!entry) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const separator = entry.indexOf('=');
|
||||
|
||||
if (separator <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result[entry.slice(0, separator)] = entry.slice(separator + 1);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseRealUid(status: string): number | null {
|
||||
const match = /^Uid:\s+(\d+)/m.exec(status);
|
||||
if (!match) return null;
|
||||
const uid = Number(match[1]);
|
||||
return Number.isSafeInteger(uid) && uid >= 0 ? uid : null;
|
||||
const match = /^Uid:\s+(\d+)/m.exec(status);
|
||||
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const uid = Number(match[1]);
|
||||
return Number.isSafeInteger(uid) && uid >= 0 ? uid : null;
|
||||
}
|
||||
|
||||
function isProcessGoneError(error: unknown): boolean {
|
||||
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
||||
return code === 'ENOENT' || code === 'ESRCH';
|
||||
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
||||
return code === 'ENOENT' || code === 'ESRCH';
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
function ownRuntimeDir(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, ownUid: number): string {
|
||||
const explicit = configuredDirectory(
|
||||
env.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
'SNOWLUMA_HOOK_RUNTIME_DIR',
|
||||
);
|
||||
|
||||
function ownRuntimeDir(
|
||||
platform: NodeJS.Platform,
|
||||
env: NodeJS.ProcessEnv,
|
||||
ownUid: number,
|
||||
): string {
|
||||
const explicit = configuredDirectory(
|
||||
env.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
'SNOWLUMA_HOOK_RUNTIME_DIR',
|
||||
);
|
||||
if (explicit) return explicit;
|
||||
if (explicit) {
|
||||
return explicit;
|
||||
}
|
||||
|
||||
const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR');
|
||||
if (xdg) return xdg;
|
||||
const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR');
|
||||
|
||||
if (platform === 'darwin') {
|
||||
const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR');
|
||||
if (tmpdir) return path.join(tmpdir, 'snowluma-hook');
|
||||
}
|
||||
return `/tmp/snowluma-${ownUid}`;
|
||||
if (xdg) {
|
||||
return xdg;
|
||||
}
|
||||
|
||||
if (platform === 'darwin') {
|
||||
const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR');
|
||||
|
||||
if (tmpdir) {
|
||||
return path.join(tmpdir, 'snowluma-hook');
|
||||
}
|
||||
}
|
||||
|
||||
return `/tmp/snowluma-${ownUid}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the socket directory for the target QQ process. The supervisor may
|
||||
* run under a different user, so its own runtime directory is not authoritative.
|
||||
*/
|
||||
export function resolveHookRuntimeDir(
|
||||
targetPid?: number,
|
||||
deps: HookRuntimeDirDeps = {},
|
||||
): string {
|
||||
const platform = deps.platform ?? process.platform;
|
||||
const env = deps.env ?? process.env;
|
||||
const ownUid = deps.ownUid
|
||||
?? (typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid);
|
||||
const readText = deps.readText ?? ((file: string) => readFileSync(file, 'utf8'));
|
||||
export function resolveHookRuntimeDir(targetPid?: number, deps: HookRuntimeDirDeps = {}): string {
|
||||
const platform = deps.platform ?? process.platform;
|
||||
const env = deps.env ?? process.env;
|
||||
const ownUid =
|
||||
deps.ownUid ??
|
||||
(typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid);
|
||||
const readText = deps.readText ?? ((file: string) => readFileSync(file, 'utf8'));
|
||||
|
||||
if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) {
|
||||
return ownRuntimeDir(platform, env, ownUid);
|
||||
}
|
||||
|
||||
let environError: unknown;
|
||||
try {
|
||||
const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`));
|
||||
const explicit = configuredDirectory(
|
||||
targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
`QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`,
|
||||
);
|
||||
if (explicit) return explicit;
|
||||
const xdg = configuredDirectory(
|
||||
targetEnv.XDG_RUNTIME_DIR,
|
||||
`QQ process ${targetPid} XDG_RUNTIME_DIR`,
|
||||
);
|
||||
if (xdg) return xdg;
|
||||
environError = new Error('runtime directory is not present');
|
||||
} catch (error) {
|
||||
// An invalid explicit path is configuration corruption and must remain
|
||||
// visible. Permission/race failures are expected when /proc disappears;
|
||||
// the status-file fallback below can still recover the target uid.
|
||||
if (error instanceof Error && error.message.includes('must be an absolute path')) {
|
||||
throw error;
|
||||
if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) {
|
||||
return ownRuntimeDir(platform, env, ownUid);
|
||||
}
|
||||
environError = error;
|
||||
}
|
||||
|
||||
let statusError: unknown;
|
||||
try {
|
||||
const uid = parseRealUid(readText(`/proc/${targetPid}/status`));
|
||||
if (uid !== null) return `/tmp/snowluma-${uid}`;
|
||||
statusError = new Error('real uid is not available');
|
||||
} catch (error) {
|
||||
statusError = error;
|
||||
}
|
||||
let environError: unknown;
|
||||
|
||||
if (isProcessGoneError(statusError)
|
||||
&& (isProcessGoneError(environError)
|
||||
|| (environError instanceof Error
|
||||
&& environError.message === 'runtime directory is not present'))) {
|
||||
return ownRuntimeDir(platform, env, ownUid);
|
||||
}
|
||||
try {
|
||||
const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`));
|
||||
const explicit = configuredDirectory(
|
||||
targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
`QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`,
|
||||
);
|
||||
|
||||
throw new Error(
|
||||
`cannot resolve hook runtime directory for PID ${targetPid}: `
|
||||
+ `environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`,
|
||||
);
|
||||
if (explicit) {
|
||||
return explicit;
|
||||
}
|
||||
|
||||
const xdg = configuredDirectory(
|
||||
targetEnv.XDG_RUNTIME_DIR,
|
||||
`QQ process ${targetPid} XDG_RUNTIME_DIR`,
|
||||
);
|
||||
|
||||
if (xdg) {
|
||||
return xdg;
|
||||
}
|
||||
|
||||
environError = new Error('runtime directory is not present');
|
||||
} catch (error) {
|
||||
// An invalid explicit path is configuration corruption and must remain
|
||||
// visible. Permission/race failures are expected when /proc disappears;
|
||||
// the status-file fallback below can still recover the target uid.
|
||||
if (error instanceof Error && error.message.includes('must be an absolute path')) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
environError = error;
|
||||
}
|
||||
|
||||
let statusError: unknown;
|
||||
|
||||
try {
|
||||
const uid = parseRealUid(readText(`/proc/${targetPid}/status`));
|
||||
|
||||
if (uid !== null) {
|
||||
return `/tmp/snowluma-${uid}`;
|
||||
}
|
||||
|
||||
statusError = new Error('real uid is not available');
|
||||
} catch (error) {
|
||||
statusError = error;
|
||||
}
|
||||
|
||||
if (
|
||||
isProcessGoneError(statusError) &&
|
||||
(isProcessGoneError(environError) ||
|
||||
(environError instanceof Error &&
|
||||
environError.message === 'runtime directory is not present'))
|
||||
) {
|
||||
return ownRuntimeDir(platform, env, ownUid);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`cannot resolve hook runtime directory for PID ${targetPid}: ` +
|
||||
`environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`,
|
||||
);
|
||||
}
|
||||
+1023
-794
File diff suppressed because it is too large.
Load diff
@@ -9,10 +9,10 @@ import type { HookProcessStatus } from './types';
|
||||
* `loggedIn` *before* tearing the client down, since teardown clears it.
|
||||
*/
|
||||
export interface HookFlags {
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
wasLoggedIn: boolean;
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
wasLoggedIn: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,7 +25,13 @@ export interface HookFlags {
|
||||
* here.
|
||||
*/
|
||||
export function statusFor(flags: HookFlags): HookProcessStatus {
|
||||
if (!flags.injected) return 'available';
|
||||
if (flags.connected) return flags.loggedIn ? 'online' : 'loaded';
|
||||
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
|
||||
if (!flags.injected) {
|
||||
return 'available';
|
||||
}
|
||||
|
||||
if (flags.connected) {
|
||||
return flags.loggedIn ? 'online' : 'loaded';
|
||||
}
|
||||
|
||||
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
|
||||
}
|
||||
@@ -1,5 +1,15 @@
|
||||
export {
|
||||
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
|
||||
type HookProcessStatus, type QqPortLoginInfo
|
||||
HookManager,
|
||||
type BridgeManagerSink,
|
||||
type HookManagerDeps,
|
||||
type HookProcessAccount,
|
||||
type HookProcessBaseInfo,
|
||||
type HookProcessInfo,
|
||||
type HookProcessStatus,
|
||||
} from './hook-manager';
|
||||
|
||||
export { type AccountLoginState, type LocalAccount } from './qq-account';
|
||||
export {
|
||||
getRuntimeIntegrity,
|
||||
hasLowProcessIntegrity,
|
||||
type RuntimeIntegrity,
|
||||
} from './runtime-integrity';
|
||||
@@ -1,141 +1,137 @@
|
||||
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;
|
||||
exceptionTable: bigint;
|
||||
size: number;
|
||||
base: bigint;
|
||||
entry: bigint;
|
||||
exceptionTable: bigint;
|
||||
size: number;
|
||||
}
|
||||
|
||||
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 {
|
||||
pid: number;
|
||||
name: string;
|
||||
path: string;
|
||||
pid: number;
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface HookInjectResult {
|
||||
method: 'loadModuleManual';
|
||||
handle?: ManualMapHandle;
|
||||
method: 'loadModuleManual';
|
||||
handle: ManualMapHandle;
|
||||
}
|
||||
|
||||
let nativeAddon: NativeHookAddon | null = null;
|
||||
let nativeLoadError: string | null = null;
|
||||
|
||||
function loadNativeAddon(addonPath: string): NativeHookAddon {
|
||||
const mod = { exports: {} as Record<string, unknown> };
|
||||
process.dlopen(mod, addonPath);
|
||||
return mod.exports as unknown as NativeHookAddon;
|
||||
const mod = { exports: {} as Record<string, unknown> };
|
||||
process.dlopen(mod, addonPath);
|
||||
return mod.exports as unknown as NativeHookAddon;
|
||||
}
|
||||
|
||||
type HookBinaryExt = 'node' | 'dll' | 'so';
|
||||
|
||||
function platformBinaryName(ext: HookBinaryExt): string {
|
||||
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
|
||||
return `snowluma-${process.platform}-${process.arch}.${ext}`;
|
||||
}
|
||||
|
||||
function platformInjectableExt(): 'dll' | 'so' {
|
||||
return process.platform === 'win32' ? 'dll' : 'so';
|
||||
return process.platform === 'win32' ? 'dll' : 'so';
|
||||
}
|
||||
|
||||
function defaultProcessName(): string {
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
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'),
|
||||
];
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
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 {
|
||||
if (nativeAddon) return nativeAddon;
|
||||
const addonPath = resolveHookNativePath('node');
|
||||
if (!addonPath) {
|
||||
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
nativeAddon = loadNativeAddon(addonPath);
|
||||
nativeLoadError = null;
|
||||
return nativeAddon;
|
||||
} catch (error) {
|
||||
nativeLoadError = error instanceof Error ? error.message : String(error);
|
||||
return null;
|
||||
}
|
||||
if (nativeAddon) {
|
||||
return nativeAddon;
|
||||
}
|
||||
|
||||
const addonPath = resolveHookNativePath('node');
|
||||
|
||||
if (!addonPath) {
|
||||
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
nativeAddon = loadNativeAddon(addonPath);
|
||||
nativeLoadError = null;
|
||||
return nativeAddon;
|
||||
} catch (error) {
|
||||
nativeLoadError = errorMessage(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getNativeHookLoadError(): string | null {
|
||||
return nativeLoadError;
|
||||
return nativeLoadError;
|
||||
}
|
||||
|
||||
export function listHookProcesses(): HookProcessBaseInfo[] {
|
||||
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
|
||||
// means QQ ran with our dylib already mapped, so the dylib's listener
|
||||
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
|
||||
// in the runtime dir as a known process (the watcher's subsequent
|
||||
// connectable-probe gates the pipe-up emit, so a stale dangling socket
|
||||
// here doesn't drive a false connect).
|
||||
if (process.platform === 'darwin') {
|
||||
return [...listSnowlumaPipePidsSync()]
|
||||
.sort((a, b) => a - b)
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) return [];
|
||||
return [...new Set(addon.getAllMainProcess())]
|
||||
.filter(pid => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
export async function 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`
|
||||
// in the runtime dir as a known process (the watcher's subsequent
|
||||
// connectable-probe gates the pipe-up emit, so a stale dangling socket
|
||||
// here doesn't drive a false connect).
|
||||
if (process.platform === 'darwin') {
|
||||
return [...listSnowlumaPipePidsSync()]
|
||||
.sort((a, b) => a - b)
|
||||
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
|
||||
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: '' }));
|
||||
}
|
||||
|
||||
export async function injectHookProcess(pid: number): Promise<HookInjectResult> {
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
const injectableExt = platformInjectableExt();
|
||||
const dllPath = resolveHookNativePath(injectableExt);
|
||||
if (!dllPath) {
|
||||
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
|
||||
}
|
||||
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) };
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
|
||||
const injectableExt = platformInjectableExt();
|
||||
const dllPath = resolveHookNativePath(injectableExt);
|
||||
|
||||
if (!dllPath) {
|
||||
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
|
||||
}
|
||||
|
||||
return { method: 'loadModuleManual', handle: await addon.loadModuleManualAsync(pid, dllPath) };
|
||||
}
|
||||
|
||||
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
addon.unloadModuleManual(pid, handle);
|
||||
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');
|
||||
}
|
||||
|
||||
await addon.unloadModuleManualAsync(pid, handle);
|
||||
}
|
||||
@@ -4,5 +4,5 @@ import { positiveIntEnv } from '@snowluma/common/env';
|
||||
export const DEFAULT_PACKET_TIMEOUT_MS = 15_000;
|
||||
|
||||
export function packetTimeoutMs(env?: NodeJS.ProcessEnv): number {
|
||||
return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env });
|
||||
return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env });
|
||||
}
|
||||
+187
-200
@@ -1,230 +1,217 @@
|
||||
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. */
|
||||
listLivePipes: (processes: readonly HookProcessBaseInfo[]) => Promise<Set<number>>;
|
||||
/** Polling interval in ms. Defaults to 1500, floored to 250. */
|
||||
intervalMs?: number;
|
||||
log?: Logger;
|
||||
/** 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>>;
|
||||
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 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 tickTask: Promise<void> | null = null;
|
||||
private pendingTick = false;
|
||||
private startPromise: Promise<void> | null = null;
|
||||
private stopped = false;
|
||||
|
||||
private livePipes = new Set<number>();
|
||||
private knownPids = new Set<number>();
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private ticking = false;
|
||||
private pendingWake = false;
|
||||
private startPromise: Promise<void> | null = null;
|
||||
private stopped = false;
|
||||
|
||||
constructor(deps: PipeWatcherDeps) {
|
||||
super();
|
||||
this.listProcesses = deps.listProcesses;
|
||||
this.listLivePipes = deps.listLivePipes;
|
||||
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
|
||||
this.log = deps.log ?? createLogger('PipeWatcher');
|
||||
}
|
||||
|
||||
/** Was this PID's pipe live as of the last completed tick? */
|
||||
isPipeLive(pid: number): boolean {
|
||||
return this.livePipes.has(pid);
|
||||
}
|
||||
|
||||
/** Was this PID alive as of the last completed tick? */
|
||||
isProcessAlive(pid: number): boolean {
|
||||
return this.knownPids.has(pid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
|
||||
* and begin the polling loop. Idempotent.
|
||||
*/
|
||||
start(): Promise<void> {
|
||||
if (this.startPromise) return this.startPromise;
|
||||
this.startPromise = (async () => {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
}
|
||||
})();
|
||||
return this.startPromise;
|
||||
}
|
||||
|
||||
/** Pull the next scheduled tick forward to the next event-loop turn. */
|
||||
wake(): void {
|
||||
if (this.stopped) return;
|
||||
this.scheduleNext(0);
|
||||
}
|
||||
|
||||
/** Force a single tick now. Resolves after diff events have been emitted. */
|
||||
tickNow(): Promise<void> {
|
||||
return this.tickOnce();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
constructor(deps: PipeWatcherDeps) {
|
||||
super();
|
||||
this.listProcesses = deps.listProcesses;
|
||||
this.listLivePipes = deps.listLivePipes;
|
||||
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
|
||||
this.log = deps.log ?? createLogger('PipeWatcher');
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.stop();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
private scheduleNext(delayMs: number): void {
|
||||
if (this.stopped) return;
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
isPipeLive(pid: number): boolean {
|
||||
return this.livePipes.has(pid);
|
||||
}
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
void this.tickAndReschedule();
|
||||
}, Math.max(0, delayMs));
|
||||
}
|
||||
|
||||
private async tickAndReschedule(): Promise<void> {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
isProcessAlive(pid: number): boolean {
|
||||
return this.knownPids.has(pid);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read processes + live pipes, emit diff events. If another tick is
|
||||
* already running, mark a follow-up tick so we don't lose a wake().
|
||||
*/
|
||||
private async tickOnce(): Promise<void> {
|
||||
if (this.ticking) {
|
||||
this.pendingWake = true;
|
||||
return;
|
||||
/** Read the initial snapshot and start polling. Repeated calls share startup. */
|
||||
start(): Promise<void> {
|
||||
return (this.startPromise ??= this.tickNow().finally(() => {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
}));
|
||||
}
|
||||
this.ticking = true;
|
||||
try {
|
||||
let processes: HookProcessBaseInfo[] | null;
|
||||
try {
|
||||
processes = await this.listProcesses();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
processes = null;
|
||||
}
|
||||
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
|
||||
// Treating missing data as "everything disappeared" would fire
|
||||
// process-gone for every live PID and dispose healthy sessions — the
|
||||
// freeze-then-teardown footgun behind issue #158. Still emit 'tick' so
|
||||
// the manager's per-tick reconnect retries keep running off last-known
|
||||
// live pipes.
|
||||
if (processes === null) {
|
||||
this.emit('tick');
|
||||
return;
|
||||
}
|
||||
let livePipes: Set<number> | null;
|
||||
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);
|
||||
/** Coalesce wake requests into one scan after the current read. */
|
||||
wake(): void {
|
||||
if (this.stopped) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Pipes that came up. Ignore pipes for processes we don't know
|
||||
// about (would race against an out-of-order tick).
|
||||
const newLivePipes = new Set<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.
|
||||
if (this.tickTask) {
|
||||
this.pendingTick = true;
|
||||
} else {
|
||||
this.scheduleNext(0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Wait for a fresh snapshot, including a scan queued behind an active read. */
|
||||
tickNow(): Promise<void> {
|
||||
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);
|
||||
this.timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.stop();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
private scheduleNext(delayMs: number): void {
|
||||
if (this.stopped) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
}
|
||||
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
void this.tickAndReschedule();
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
private async tickAndReschedule(): Promise<void> {
|
||||
try {
|
||||
await this.tickNow();
|
||||
} catch (error) {
|
||||
this.log.warn('poll failed: %s', errorMessage(error));
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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 {
|
||||
livePipes = await this.listLivePipes(processes);
|
||||
} catch (error) {
|
||||
this.log.warn('listLivePipes failed: %s', errorMessage(error));
|
||||
livePipes = this.livePipes;
|
||||
}
|
||||
|
||||
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]);
|
||||
}
|
||||
}
|
||||
|
||||
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 (newKnownPids.has(pid)) newLivePipes.add(pid);
|
||||
if (!currentPipes.has(pid)) {
|
||||
events.push(['pipe-down', 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);
|
||||
for (const pid of this.knownPids) {
|
||||
if (!knownPids.has(pid)) {
|
||||
events.push(['process-gone', pid]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Processes that disappeared.
|
||||
for (const pid of this.knownPids) {
|
||||
if (!newKnownPids.has(pid)) {
|
||||
this.emit('process-gone', pid);
|
||||
this.knownPids = knownPids;
|
||||
this.livePipes = currentPipes;
|
||||
|
||||
for (const [event, payload] of events) {
|
||||
if (this.stopped) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.emit(event, payload);
|
||||
}
|
||||
}
|
||||
|
||||
this.knownPids = newKnownPids;
|
||||
this.livePipes = newLivePipes;
|
||||
this.emit('tick');
|
||||
} finally {
|
||||
this.ticking = false;
|
||||
if (this.pendingWake) {
|
||||
this.pendingWake = false;
|
||||
// Defer to break sync recursion if a listener calls wake().
|
||||
setImmediate(() => { void this.tickOnce(); });
|
||||
}
|
||||
if (!this.stopped) {
|
||||
this.emit('tick');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -1,238 +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. */
|
||||
enumerate(): Promise<HookProcessBaseInfo[] | null>;
|
||||
dispose(): void;
|
||||
/** 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?". */
|
||||
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;
|
||||
interface ProcessEnumeratorDeps {
|
||||
listProcesses: () => Promise<HookProcessBaseInfo[]>;
|
||||
timeoutMs?: number;
|
||||
log?: Logger;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4000;
|
||||
const DEFAULT_MAX_ORPHANS = 4;
|
||||
export function createProcessEnumerator(deps: ProcessEnumeratorDeps): ProcessEnumerator {
|
||||
const log = deps.log ?? createLogger('ProcessEnumerator');
|
||||
const timeoutMs = deps.timeoutMs ?? 4000;
|
||||
let disposed = false;
|
||||
let pending: {
|
||||
promise: Promise<HookProcessBaseInfo[] | null>;
|
||||
settle: (result: HookProcessBaseInfo[] | null) => void;
|
||||
} | null = null;
|
||||
|
||||
// Worker body (CommonJS — eval workers default to CJS so `require` is available;
|
||||
// `process.dlopen` is a global and needs no module system). Loads the addon
|
||||
// handed in via workerData, then answers each 'enumerate' with the raw pid list
|
||||
// from the blocking native call. All the cheap post-processing stays on main.
|
||||
const WORKER_SOURCE = `
|
||||
const { parentPort, workerData } = require('node:worker_threads');
|
||||
let addon = null;
|
||||
try {
|
||||
const mod = { exports: {} };
|
||||
process.dlopen(mod, workerData.addonPath);
|
||||
addon = mod.exports;
|
||||
} catch (e) {
|
||||
parentPort.postMessage({ type: 'fatal', error: String((e && e.message) || e) });
|
||||
}
|
||||
if (addon) {
|
||||
parentPort.on('message', (msg) => {
|
||||
if (!msg || msg.type !== 'enumerate') return;
|
||||
try {
|
||||
const pids = addon.getAllMainProcess();
|
||||
parentPort.postMessage({ type: 'result', id: msg.id, pids: Array.from(pids) });
|
||||
} catch (e) {
|
||||
parentPort.postMessage({ type: 'error', id: msg.id, error: String((e && e.message) || e) });
|
||||
}
|
||||
});
|
||||
parentPort.postMessage({ type: 'ready' });
|
||||
}
|
||||
`;
|
||||
|
||||
function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] {
|
||||
return [...new Set(pids)]
|
||||
.filter((pid) => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map((pid) => ({ pid, name: processName, path: '' }));
|
||||
}
|
||||
|
||||
export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator {
|
||||
const log = deps.log ?? createLogger('ProcessEnumerator');
|
||||
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
|
||||
|
||||
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
|
||||
// fallback there is a cheap socket read, not a /proc walk.
|
||||
if (!deps.addonPath) {
|
||||
return {
|
||||
async enumerate() {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
},
|
||||
dispose() { /* nothing to tear down */ },
|
||||
enumerate() {
|
||||
if (disposed) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
if (pending) {
|
||||
return pending.promise;
|
||||
}
|
||||
|
||||
let resolve!: (result: HookProcessBaseInfo[] | null) => void;
|
||||
const promise = new Promise<HookProcessBaseInfo[] | null>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
|
||||
const settle = (result: HookProcessBaseInfo[] | null) => {
|
||||
clearTimeout(timer);
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
log.warn(
|
||||
'process enumeration timed out after %dms; keeping prior process set',
|
||||
timeoutMs,
|
||||
);
|
||||
settle(null);
|
||||
}, timeoutMs);
|
||||
pending = { promise, settle };
|
||||
|
||||
// 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;
|
||||
pending?.settle(null);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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 }>();
|
||||
let disposed = false;
|
||||
|
||||
const spawnWorker = (): void => {
|
||||
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
|
||||
worker = w;
|
||||
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
|
||||
if (msg.type === 'ready') return;
|
||||
if (msg.type === 'fatal') {
|
||||
// The addon won't load off-thread — give up on isolation for good and
|
||||
// fall back to the synchronous path from here on. Resolve any in-flight
|
||||
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
|
||||
log.warn('process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration', msg.error ?? '');
|
||||
isolationBroken = true;
|
||||
for (const { resolve } of pending.values()) resolve(null);
|
||||
pending.clear();
|
||||
teardownWorker();
|
||||
return;
|
||||
}
|
||||
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
|
||||
const entry = pending.get(msg.id);
|
||||
if (!entry) return;
|
||||
pending.delete(msg.id);
|
||||
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
|
||||
}
|
||||
});
|
||||
w.on('error', (err) => {
|
||||
log.warn('enumeration worker error: %s', errMsg(err));
|
||||
if (worker === w) teardownWorker();
|
||||
});
|
||||
};
|
||||
|
||||
const teardownWorker = (): void => {
|
||||
const w = worker;
|
||||
worker = null;
|
||||
if (!w) return;
|
||||
// terminate() can't preempt a thread blocked in the native call; it takes
|
||||
// effect once the call returns. Track it as an orphan until it actually
|
||||
// exits so we can bound how many we let pile up.
|
||||
orphans += 1;
|
||||
w.once('exit', () => { orphans = Math.max(0, orphans - 1); });
|
||||
void w.terminate().catch(() => { /* already gone */ });
|
||||
};
|
||||
|
||||
const syncFallback = (): HookProcessBaseInfo[] | null => {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate sync fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
|
||||
if (disposed || isolationBroken) return syncFallback();
|
||||
|
||||
if (!worker) {
|
||||
if (orphans >= maxOrphans) {
|
||||
// Too many blocked workers already piling up (a sustained hang) —
|
||||
// don't spawn more; report UNKNOWN and let them drain.
|
||||
return null;
|
||||
}
|
||||
spawnWorker();
|
||||
}
|
||||
const w = worker;
|
||||
if (!w) return syncFallback();
|
||||
|
||||
const id = ++seq;
|
||||
const resultPromise = new Promise<number[] | null>((resolve) => {
|
||||
pending.set(id, { resolve });
|
||||
});
|
||||
try {
|
||||
w.postMessage({ type: 'enumerate', id });
|
||||
} catch (err) {
|
||||
pending.delete(id);
|
||||
log.warn('failed to post enumerate request: %s', errMsg(err));
|
||||
teardownWorker();
|
||||
return syncFallback();
|
||||
}
|
||||
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<'timeout'>((resolve) => {
|
||||
timer = setTimeout(() => resolve('timeout'), timeoutMs);
|
||||
});
|
||||
const outcome = await Promise.race([resultPromise, timeout]);
|
||||
if (timer) clearTimeout(timer);
|
||||
|
||||
if (outcome === 'timeout') {
|
||||
pending.delete(id);
|
||||
log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs);
|
||||
teardownWorker();
|
||||
return null;
|
||||
}
|
||||
if (outcome === null) {
|
||||
// Native call threw inside the worker — treat as a transient failure,
|
||||
// keep prior state rather than nuking every session.
|
||||
return null;
|
||||
}
|
||||
return mapPids(outcome, deps.processName);
|
||||
},
|
||||
|
||||
dispose() {
|
||||
disposed = true;
|
||||
for (const { resolve } of pending.values()) resolve(null);
|
||||
pending.clear();
|
||||
const w = worker;
|
||||
worker = null;
|
||||
if (w) void w.terminate().catch(() => { /* ignore */ });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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 '';
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
+1204
-929
File diff suppressed because it is too large.
Load diff
@@ -1,228 +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 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) return null;
|
||||
|
||||
if (ports.length === 0) {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return { port: 0, uin: '', identityKnown: false };
|
||||
}
|
||||
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) {
|
||||
return {
|
||||
port: ports[0] || 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Background discovery must remain passive. Interactive application
|
||||
// endpoints are deliberately excluded from automatic probing.
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,23 @@
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
export type HookProcessStatus =
|
||||
| 'available'
|
||||
| 'loading'
|
||||
| 'connecting'
|
||||
| 'loaded'
|
||||
| 'online'
|
||||
| 'error'
|
||||
| 'disconnected';
|
||||
'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;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
uin: string;
|
||||
status: HookProcessStatus;
|
||||
error: string;
|
||||
method: string;
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
uin: string;
|
||||
status: HookProcessStatus;
|
||||
error: string;
|
||||
method: string;
|
||||
/** Locally detected identity; null means unknown, not necessarily signed out. */
|
||||
account: HookProcessAccount | null;
|
||||
}
|
||||
@@ -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
|
||||
@@ -13,203 +14,437 @@ import type { QqHookClient } from '../src/qq-hook-client';
|
||||
// browser without REST polling.
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
interface Harness {
|
||||
manager: HookManager;
|
||||
pipeWatcher: PipeWatcher;
|
||||
bridgeManager: BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
setProcesses: (next: number[]) => void;
|
||||
setLivePipes: (next: number[]) => void;
|
||||
onSessionsChanged: ReturnType<typeof vi.fn>;
|
||||
clientFactory: ReturnType<typeof vi.fn>;
|
||||
manager: HookManager;
|
||||
pipeWatcher: PipeWatcher;
|
||||
bridgeManager: BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
setProcesses: (next: number[]) => void;
|
||||
setLivePipes: (next: number[]) => void;
|
||||
onSessionsChanged: ReturnType<typeof vi.fn>;
|
||||
clientFactory: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
|
||||
function makeManager(opts: { processes?: number[]; livePipes?: 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: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
const clientFactory = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { /* succeed without doing anything */ };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
onPidReceiveHealthChanged: vi.fn(),
|
||||
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
const onSessionsChanged = vi.fn();
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: clientFactory,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
onSessionsChanged,
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
pipeWatcher,
|
||||
bridgeManager,
|
||||
onSessionsChanged,
|
||||
clientFactory,
|
||||
setProcesses: (next) => { pids = next; },
|
||||
setLivePipes: (next) => { live = new Set(next); },
|
||||
};
|
||||
}
|
||||
|
||||
describe('HookManager.onSessionsChanged', () => {
|
||||
it('fires when the watcher discovers a new QQ process', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
await ctx.pipeWatcher.start();
|
||||
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports a process is gone', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
// Inject so the session is in 'connecting' state; the next pipe-up
|
||||
// makes attemptConnect succeed and status flips to 'loaded'.
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setLivePipes([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
ctx.onSessionsChanged.mockImplementation(() => { throw new Error('listener boom'); });
|
||||
await ctx.pipeWatcher.start();
|
||||
ctx.setProcesses([4242]);
|
||||
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
|
||||
await flush();
|
||||
// A second tick still fires the callback — it wasn't unregistered by
|
||||
// the prior throw.
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
ctx.setProcesses([4242, 5555]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
|
||||
const pids = [4242];
|
||||
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: '' })),
|
||||
listLivePipes: async () => new Set(),
|
||||
intervalMs: 60_000,
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
const manager = new HookManager({
|
||||
bridgeManager: {
|
||||
const clientFactory = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
|
||||
(c as any).connectAll = async () => {
|
||||
/* succeed without doing anything */
|
||||
};
|
||||
|
||||
(c as any).close = () => {
|
||||
(c as any).isClosed = true;
|
||||
};
|
||||
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: vi.fn(() => {
|
||||
const c = new EventEmitter() as any;
|
||||
c.isClosed = false; c.isLoggedIn = false;
|
||||
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
c.connectAll = async () => undefined;
|
||||
c.close = () => { c.isClosed = true; };
|
||||
return c;
|
||||
}),
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
// onSessionsChanged deliberately omitted
|
||||
onPidReceiveHealthChanged: vi.fn(),
|
||||
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
const onSessionsChanged = vi.fn();
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(async () => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(async () => {}),
|
||||
},
|
||||
makeClient: clientFactory,
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
detectAccounts: opts.detectAccounts ?? (async () => []),
|
||||
accountReprobeIntervalMs: opts.accountReprobeIntervalMs,
|
||||
onSessionsChanged,
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
pipeWatcher,
|
||||
bridgeManager,
|
||||
onSessionsChanged,
|
||||
clientFactory,
|
||||
setProcesses: (next) => {
|
||||
pids = next;
|
||||
},
|
||||
setLivePipes: (next) => {
|
||||
live = new Set(next);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('HookManager.onSessionsChanged', () => {
|
||||
it('fires when the watcher discovers a new QQ process', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
await ctx.pipeWatcher.start();
|
||||
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports a process is gone', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
// Inject so the session is in 'connecting' state; the next pipe-up
|
||||
// makes attemptConnect succeed and status flips to 'loaded'.
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setLivePipes([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
ctx.onSessionsChanged.mockImplementation(() => {
|
||||
throw new Error('listener boom');
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
ctx.setProcesses([4242]);
|
||||
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
|
||||
await flush();
|
||||
// A second tick still fires the callback — it wasn't unregistered by
|
||||
// the prior throw.
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
ctx.setProcesses([4242, 5555]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
|
||||
const pids = [4242];
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
const manager = new HookManager({
|
||||
bridgeManager: {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(async () => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(async () => {}),
|
||||
},
|
||||
makeClient: vi.fn(() => {
|
||||
const c = new EventEmitter() as any;
|
||||
c.isClosed = false;
|
||||
c.isLoggedIn = false;
|
||||
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
c.connectAll = async () => undefined;
|
||||
|
||||
c.close = () => {
|
||||
c.isClosed = true;
|
||||
};
|
||||
|
||||
return c;
|
||||
}),
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
detectAccounts: async () => [],
|
||||
// onSessionsChanged deliberately omitted
|
||||
});
|
||||
await pipeWatcher.start();
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
const list = await manager.listProcesses();
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0].pid).toBe(4242);
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
await pipeWatcher.start();
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
const list = await manager.listProcesses();
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0].pid).toBe(4242);
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookManager receive-health wiring (#233)', () => {
|
||||
it('forwards stale and recovered receive health for the owning PID', async () => {
|
||||
const ctx = makeManager({ processes: [4242], livePipes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await ctx.manager.refreshProcess(4242);
|
||||
await flush();
|
||||
it('forwards stale and recovered receive health for the owning PID', async () => {
|
||||
const ctx = makeManager({ processes: [4242], livePipes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await ctx.manager.refreshProcess(4242);
|
||||
await flush();
|
||||
|
||||
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
try {
|
||||
client.emit('packet', {
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
vi.advanceTimersByTime(105_000);
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenCalledWith(4242, false);
|
||||
try {
|
||||
client.emit('packet', {
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
vi.advanceTimersByTime(105_000);
|
||||
|
||||
client.emit('packet', {
|
||||
seq: 2,
|
||||
error: 0,
|
||||
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(4242, true);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenCalledWith(4242, false);
|
||||
|
||||
client.emit('packet', {
|
||||
seq: 2,
|
||||
error: 0,
|
||||
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(
|
||||
4242,
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -7,422 +7,507 @@ 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,
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
createLogger,
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function managerTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter(
|
||||
(entry) => entry.level === 'trace' && entry.scope === 'Hook',
|
||||
);
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Hook');
|
||||
}
|
||||
|
||||
function makeManager(opts: {
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
processes?: number[];
|
||||
onSessionsChanged?: () => void;
|
||||
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
processes?: number[];
|
||||
onSessionsChanged?: () => void;
|
||||
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 ?? (() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})));
|
||||
const unload = vi.fn();
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
// FakeClient — never connected; just needs to satisfy EventEmitter +
|
||||
// a minimal subset of QqHookClient for HookSession.tearDownClient().
|
||||
const makeClient = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { throw new Error('test: never really connect'); };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
onSessionsChanged: opts.onSessionsChanged,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
inject,
|
||||
pipeWatcher,
|
||||
setProcesses: (next: number[]) => { pids = next; },
|
||||
};
|
||||
let pids = opts.processes ?? [];
|
||||
const live = new Set<number>();
|
||||
const inject = vi.fn(
|
||||
opts.inject ??
|
||||
(async () => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
);
|
||||
const unload = vi.fn(async () => {});
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
// FakeClient — never connected; just needs to satisfy EventEmitter +
|
||||
// a minimal subset of QqHookClient for HookSession.tearDownClient().
|
||||
const makeClient = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
|
||||
(c as any).connectAll = async () => {
|
||||
throw new Error('test: never really connect');
|
||||
};
|
||||
|
||||
(c as any).close = () => {
|
||||
(c as any).isClosed = true;
|
||||
};
|
||||
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
onSessionsChanged: opts.onSessionsChanged,
|
||||
listProcesses: 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,
|
||||
inject,
|
||||
pipeWatcher,
|
||||
setProcesses: (next: number[]) => {
|
||||
pids = next;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
describe('HookManager runtime TRACE', () => {
|
||||
it('records discovery and process-gone facts while unchanged ticks stay silent', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
const sessionsChanged = vi.fn();
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: false,
|
||||
processes: [],
|
||||
onSessionsChanged: sessionsChanged,
|
||||
it('records discovery and process-gone facts while unchanged ticks stay silent', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
const sessionsChanged = vi.fn();
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: false,
|
||||
processes: [],
|
||||
onSessionsChanged: sessionsChanged,
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
const baseline = managerTrace(entries).length;
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
expect(managerTrace(entries)).toHaveLength(baseline);
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
|
||||
const facts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_manager_fact '),
|
||||
);
|
||||
expect(facts.map((entry) => entry.message)).toEqual([
|
||||
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
|
||||
'hook_manager_fact event=process_gone pid=4242 tracked=true',
|
||||
]);
|
||||
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
const baseline = managerTrace(entries).length;
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
expect(managerTrace(entries)).toHaveLength(baseline);
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
it('records bounded transient retries and recovery as separate attempts', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
})
|
||||
.mockImplementationOnce(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
}));
|
||||
|
||||
const facts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_manager_fact '),
|
||||
);
|
||||
expect(facts.map((entry) => entry.message)).toEqual([
|
||||
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
|
||||
'hook_manager_fact event=process_gone pid=4242 tracked=true',
|
||||
]);
|
||||
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
it('records bounded transient retries and recovery as separate attempts', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
})
|
||||
.mockImplementationOnce(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
}));
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/),
|
||||
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
|
||||
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
expect(attempts[2]!.req).toBe(attempts[3]!.req);
|
||||
expect(attempts[0]!.req).not.toBe(attempts[2]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
let resolveInjection!: (result: HookInjectResult) => void;
|
||||
const injection = new Promise<HookInjectResult>((resolve) => {
|
||||
resolveInjection = resolve;
|
||||
const attempts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/,
|
||||
),
|
||||
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
expect(attempts[2]!.req).toBe(attempts[3]!.req);
|
||||
expect(attempts[0]!.req).not.toBe(attempts[2]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: true,
|
||||
processes: [4242],
|
||||
inject: () => injection,
|
||||
|
||||
it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
let resolveInjection!: (result: HookInjectResult) => void;
|
||||
const injection = new Promise<HookInjectResult>((resolve) => {
|
||||
resolveInjection = resolve;
|
||||
});
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: true,
|
||||
processes: [4242],
|
||||
inject: () => injection,
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
const manualLoad = ctx.manager.loadProcess(4242);
|
||||
resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
|
||||
await manualLoad;
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
const manualLoad = ctx.manager.loadProcess(4242);
|
||||
resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
|
||||
await manualLoad;
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
it.each([
|
||||
{
|
||||
name: 'permanent failure',
|
||||
error: 'ptrace denied',
|
||||
ticks: 1,
|
||||
attempts: 1,
|
||||
reason: 'permanent_failure',
|
||||
},
|
||||
{
|
||||
name: 'retry exhaustion',
|
||||
error: 'target process does not map /lib/libc.so.6 while resolving mmap',
|
||||
ticks: 4,
|
||||
attempts: 3,
|
||||
reason: 'retry_exhausted',
|
||||
},
|
||||
])('records $name terminal', async ({ error, ticks, attempts, reason }) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error(error);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'permanent failure',
|
||||
error: 'ptrace denied',
|
||||
ticks: 1,
|
||||
attempts: 1,
|
||||
reason: 'permanent_failure',
|
||||
},
|
||||
{
|
||||
name: 'retry exhaustion',
|
||||
error: 'target process does not map /lib/libc.so.6 while resolving mmap',
|
||||
ticks: 4,
|
||||
attempts: 3,
|
||||
reason: 'retry_exhausted',
|
||||
},
|
||||
])('records $name terminal', async ({ error, ticks, attempts, reason }) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => { throw new Error(error); });
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
for (let tick = 0; tick < ticks; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
const starts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_start '),
|
||||
);
|
||||
const terminals = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_terminal '),
|
||||
);
|
||||
expect(starts).toHaveLength(attempts);
|
||||
expect(terminals).toHaveLength(attempts);
|
||||
expect(terminals.at(-1)!.message).toContain(`reason=${reason}`);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
for (let tick = 0; tick < ticks; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
|
||||
const starts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_start '),
|
||||
);
|
||||
const terminals = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_terminal '),
|
||||
);
|
||||
expect(starts).toHaveLength(attempts);
|
||||
expect(terminals).toHaveLength(attempts);
|
||||
expect(terminals.at(-1)!.message).toContain(`reason=${reason}`);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookManager.autoLoadOnDiscovery', () => {
|
||||
it('does NOT inject on process-discovered when flag is off', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
expect(ctx.inject).not.toHaveBeenCalled();
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('injects every newly-discovered PID when flag is on', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
// session.load() is queued via a per-session promise chain; flush twice
|
||||
// so the auto-load runs to completion before we assert.
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.inject).toHaveBeenCalledWith(4242);
|
||||
|
||||
// A second PID appearing mid-flight should also trigger an inject.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('swallows inject errors so the watcher keeps running', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Second PID should still be auto-loaded — the failure on 4242 must
|
||||
// not leak out of the listener and break the watcher's emit loop.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('retries a transient libc mapping failure on the next watcher tick', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
it('does NOT inject on process-discovered when flag is off', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
expect(ctx.inject).not.toHaveBeenCalled();
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
it('injects every newly-discovered PID when flag is on', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
// session.load() is queued via a per-session promise chain; flush twice
|
||||
// so the auto-load runs to completion before we assert.
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.inject).toHaveBeenCalledWith(4242);
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(4242);
|
||||
// A second PID appearing mid-flight should also trigger an inject.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('does not retry permanent auto-load errors', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => { throw new Error('ptrace denied'); });
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('stops retrying a transient libc mapping failure after three attempts', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
it('swallows inject errors so the watcher keeps running', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => {
|
||||
throw new Error('ptrace denied');
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
for (let tick = 0; tick < 4; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(3);
|
||||
// Second PID should still be auto-loaded — the failure on 4242 must
|
||||
// not leak out of the listener and break the watcher's emit loop.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('retries a transient libc mapping failure on the next watcher tick', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(4242);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('does not retry permanent auto-load errors', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error('ptrace denied');
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('stops retrying a transient libc mapping failure after three attempts', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
for (let tick = 0; tick < 4; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(3);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
// `shouldAutoLoadPid` reads /proc/<pid>/cmdline directly, so we point
|
||||
// it at a temporary directory that mimics the procfs layout. This lets
|
||||
// the tests run on macOS / CI without a live Linux QQ process.
|
||||
describe('shouldAutoLoadPid', () => {
|
||||
let tmpProc: string;
|
||||
const originalReadFileSync = fs.readFileSync;
|
||||
const log = createLogger('test');
|
||||
const originalPlatform = process.platform;
|
||||
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
let tmpProc: string;
|
||||
const originalReadFileSync = fs.readFileSync;
|
||||
const log = createLogger('test');
|
||||
const originalPlatform = process.platform;
|
||||
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((p: string, ...rest: unknown[]) => {
|
||||
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
|
||||
if (match) {
|
||||
return originalReadFileSync(path.join(tmpProc, match[1], 'cmdline'), ...(rest as [BufferEncoding]));
|
||||
}
|
||||
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
|
||||
}) as typeof fs.readFileSync;
|
||||
});
|
||||
beforeEach(() => {
|
||||
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((
|
||||
p: string,
|
||||
...rest: unknown[]
|
||||
) => {
|
||||
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
|
||||
|
||||
afterEach(() => {
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
|
||||
if (originalAutoLoadAll === undefined) delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
else process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
|
||||
fs.rmSync(tmpProc, { recursive: true, force: true });
|
||||
});
|
||||
if (match) {
|
||||
return originalReadFileSync(
|
||||
path.join(tmpProc, match[1], 'cmdline'),
|
||||
...(rest as [BufferEncoding]),
|
||||
);
|
||||
}
|
||||
|
||||
function writeCmdline(pid: number, args: string[]): void {
|
||||
const dir = path.join(tmpProc, String(pid));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
|
||||
}
|
||||
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
|
||||
}) as typeof fs.readFileSync;
|
||||
});
|
||||
|
||||
it('allows the QQ main process (no --type=)', () => {
|
||||
writeCmdline(50, ['qq', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(50, log)).toBe(true);
|
||||
});
|
||||
afterEach(() => {
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
|
||||
|
||||
it('rejects Electron zygotes', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(false);
|
||||
});
|
||||
if (originalAutoLoadAll === undefined) {
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
|
||||
}
|
||||
|
||||
it('rejects renderer/gpu/utility children', () => {
|
||||
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
|
||||
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
|
||||
writeCmdline(72, ['/opt/QQ/qq', '--type=utility', '--utility-sub-type=network.mojom.NetworkService']);
|
||||
expect(shouldAutoLoadPid(70, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(71, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(72, log)).toBe(false);
|
||||
});
|
||||
fs.rmSync(tmpProc, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
function writeCmdline(pid: number, args: string[]): void {
|
||||
const dir = path.join(tmpProc, String(pid));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
|
||||
}
|
||||
|
||||
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
||||
// No cmdline file needed — we return true before touching procfs.
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
it('allows the QQ main process (no --type=)', () => {
|
||||
writeCmdline(50, ['qq', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(50, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
|
||||
expect(shouldAutoLoadPid(99999, log)).toBe(true);
|
||||
});
|
||||
it('rejects Electron zygotes', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects renderer/gpu/utility children', () => {
|
||||
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
|
||||
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
|
||||
writeCmdline(72, [
|
||||
'/opt/QQ/qq',
|
||||
'--type=utility',
|
||||
'--utility-sub-type=network.mojom.NetworkService',
|
||||
]);
|
||||
expect(shouldAutoLoadPid(70, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(71, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(72, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
||||
// No cmdline file needed — we return true before touching procfs.
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
|
||||
expect(shouldAutoLoadPid(99999, log)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,60 +1,70 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { HookPacketClient } from '../src/hook-packet-client';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
type QqHookClient,
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
type QqHookClient,
|
||||
} from '../src/qq-hook-client';
|
||||
|
||||
function fakeClient(send: QqHookClient['send']): QqHookClient {
|
||||
return {
|
||||
isLoggedIn: true,
|
||||
send,
|
||||
} as unknown as QqHookClient;
|
||||
return {
|
||||
isLoggedIn: true,
|
||||
send,
|
||||
} as unknown as QqHookClient;
|
||||
}
|
||||
|
||||
describe('HookPacketClient outbound health', () => {
|
||||
it('reports native connection loss once and recovers after a successful request', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValueOnce(new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
1,
|
||||
))
|
||||
.mockRejectedValueOnce(new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
2,
|
||||
))
|
||||
.mockResolvedValueOnce({
|
||||
requestId: 3,
|
||||
error: 0,
|
||||
message: '',
|
||||
body: Buffer.from('ok'),
|
||||
});
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
it('reports native connection loss once and recovers after a successful request', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValueOnce(
|
||||
new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
1,
|
||||
),
|
||||
)
|
||||
.mockRejectedValueOnce(
|
||||
new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
2,
|
||||
),
|
||||
)
|
||||
.mockResolvedValueOnce({
|
||||
requestId: 3,
|
||||
error: 0,
|
||||
message: '',
|
||||
body: Buffer.from('ok'),
|
||||
});
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: false, gotResponse: false });
|
||||
await sender.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: true, gotResponse: true });
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
});
|
||||
await sender.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
});
|
||||
|
||||
expect(healthChanged.mock.calls).toEqual([[false], [true]]);
|
||||
});
|
||||
expect(healthChanged.mock.calls).toEqual([[false], [true]]);
|
||||
});
|
||||
|
||||
it('does not classify ordinary request rejection as connection loss', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi.fn<QqHookClient['send']>().mockRejectedValue(
|
||||
new HookPipeRequestError('This request is not valid.', -38, 1),
|
||||
);
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
it('does not classify ordinary request rejection as connection loss', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValue(new HookPipeRequestError('This request is not valid.', -38, 1));
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: false, gotResponse: false });
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
});
|
||||
|
||||
expect(healthChanged).not.toHaveBeenCalled();
|
||||
});
|
||||
expect(healthChanged).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -13,87 +13,102 @@ import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
async connectAll(_opts: { recv: boolean }) {
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
}
|
||||
getLoginState() { return { loggedIn: false, uin: '0', uinNumber: 0n }; }
|
||||
close() {
|
||||
if (this.isClosed) return;
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
async connectAll(_opts: { recv: boolean }) {
|
||||
if (this.isClosed) {
|
||||
throw new Error('client is closed');
|
||||
}
|
||||
}
|
||||
getLoginState() {
|
||||
return { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
}
|
||||
close() {
|
||||
if (this.isClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => {
|
||||
const PID = 61;
|
||||
const liveSet = new Set<number>([PID]);
|
||||
const clients: FakeClient[] = [];
|
||||
it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => {
|
||||
const PID = 61;
|
||||
const liveSet = new Set<number>([PID]);
|
||||
const clients: FakeClient[] = [];
|
||||
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
listLivePipes: async () => new Set(liveSet),
|
||||
intervalMs: 60_000, // manual ticks only
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: async () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
listLivePipes: async () => new Set(liveSet),
|
||||
intervalMs: 60_000, // manual ticks only
|
||||
});
|
||||
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(async () => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(async () => {}),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
autoLoadOnDiscovery: true,
|
||||
listProcesses: async () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
detectAccounts: async () => [],
|
||||
});
|
||||
|
||||
// Initial discovery + first connect.
|
||||
await pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Drive 50 pipe up/down cycles with the QQ process staying alive but
|
||||
// the pipe (= QQ control socket) bouncing every "tick".
|
||||
const CYCLES = 50;
|
||||
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
liveSet.delete(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
liveSet.add(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// The "QQ never logs in" hypothesis: BridgeManager should never have
|
||||
// been told about a login or a disconnect.
|
||||
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
|
||||
|
||||
// Hook layer should hold at most one live client.
|
||||
const alive = clients.filter((c) => !c.isClosed);
|
||||
expect(
|
||||
alive.length,
|
||||
`live clients after ${CYCLES} cycles: ${alive.length}`,
|
||||
).toBeLessThanOrEqual(1);
|
||||
|
||||
// Total clients minted = roughly one per up cycle. Sanity bound:
|
||||
// we must have actually exercised the reconnect path.
|
||||
expect(clients.length).toBeGreaterThan(1);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
autoLoadOnDiscovery: true,
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
});
|
||||
|
||||
// Initial discovery + first connect.
|
||||
await pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Drive 50 pipe up/down cycles with the QQ process staying alive but
|
||||
// the pipe (= QQ control socket) bouncing every "tick".
|
||||
const CYCLES = 50;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
liveSet.delete(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
liveSet.add(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// The "QQ never logs in" hypothesis: BridgeManager should never have
|
||||
// been told about a login or a disconnect.
|
||||
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
|
||||
|
||||
// Hook layer should hold at most one live client.
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
expect(alive.length, `live clients after ${CYCLES} cycles: ${alive.length}`).toBeLessThanOrEqual(1);
|
||||
|
||||
// Total clients minted = roughly one per up cycle. Sanity bound:
|
||||
// we must have actually exercised the reconnect path.
|
||||
expect(clients.length).toBeGreaterThan(1);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -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';
|
||||
@@ -24,100 +24,123 @@ import type { QqHookClient } from '../src/qq-hook-client';
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
|
||||
class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
}
|
||||
getLoginState() { return { ...this.loginState }; }
|
||||
close(): void {
|
||||
if (this.isClosed) return;
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
if (this.isClosed) {
|
||||
throw new Error('client is closed');
|
||||
}
|
||||
}
|
||||
getLoginState() {
|
||||
return { ...this.loginState };
|
||||
}
|
||||
close(): void {
|
||||
if (this.isClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
function totalListenerCount(emitter: EventEmitter): number {
|
||||
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
|
||||
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
|
||||
}
|
||||
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
detectLoginUin: async () => null,
|
||||
injector: {
|
||||
inject: vi.fn(async () => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(async () => {}),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
});
|
||||
onTestFinished(() => session.dispose());
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const CYCLES = 50;
|
||||
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
|
||||
const alive = clients.filter((c) => !c.isClosed);
|
||||
expect.soft(clients.length).toBeGreaterThan(1);
|
||||
expect(
|
||||
alive.length,
|
||||
`expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`,
|
||||
).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
it('drops all listeners from each torn-down client', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
detectLoginUin: async () => null,
|
||||
injector: {
|
||||
inject: vi.fn(async () => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(async () => {}),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
});
|
||||
onTestFinished(() => session.dispose());
|
||||
|
||||
const CYCLES = 50;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
expect.soft(clients.length).toBeGreaterThan(1);
|
||||
expect(alive.length, `expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`)
|
||||
.toBeLessThanOrEqual(1);
|
||||
});
|
||||
const CYCLES = 20;
|
||||
|
||||
it('drops all listeners from each torn-down client', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// Every client except the current one should have 0 listeners attached.
|
||||
// (HookSession.tearDownClient does client.removeAllListeners().)
|
||||
for (let i = 0; i < clients.length - 1; i++) {
|
||||
const lc = totalListenerCount(clients[i]);
|
||||
expect(
|
||||
lc,
|
||||
`client #${i} of ${clients.length} still has ${lc} listeners after teardown`,
|
||||
).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const CYCLES = 20;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// Every client except the current one should have 0 listeners attached.
|
||||
// (HookSession.tearDownClient does client.removeAllListeners().)
|
||||
for (let i = 0; i < clients.length - 1; i++) {
|
||||
const lc = totalListenerCount(clients[i]);
|
||||
expect(lc, `client #${i} of ${clients.length} still has ${lc} listeners after teardown`)
|
||||
.toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,66 +2,84 @@ import { describe, expect, it } from 'vitest';
|
||||
import { resolveHookRuntimeDir } from '../src/hook-runtime-dir';
|
||||
|
||||
function procReader(files: Record<string, string>) {
|
||||
return (file: string): string => {
|
||||
const value = files[file];
|
||||
if (value === undefined) throw new Error(`missing fixture: ${file}`);
|
||||
return value;
|
||||
};
|
||||
return (file: string): string => {
|
||||
const value = files[file];
|
||||
|
||||
if (value === undefined) {
|
||||
throw new Error(`missing fixture: ${file}`);
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
describe('resolveHookRuntimeDir — Linux target process ownership', () => {
|
||||
it('uses the QQ process runtime directory instead of the supervisor user directory', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0XDG_RUNTIME_DIR=/run/user/1000\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/run/user/1000');
|
||||
});
|
||||
it('uses the QQ process runtime directory instead of the supervisor user directory', () => {
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0XDG_RUNTIME_DIR=/run/user/1000\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
}),
|
||||
).toBe('/run/user/1000');
|
||||
});
|
||||
|
||||
it('falls back to the QQ process uid when its environment has no runtime directory', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/tmp/snowluma-1000');
|
||||
});
|
||||
it('falls back to the QQ process uid when its environment has no runtime directory', () => {
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
}),
|
||||
).toBe('/tmp/snowluma-1000');
|
||||
});
|
||||
|
||||
it('fails visibly when target ownership cannot be determined', () => {
|
||||
expect(() => resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => { throw new Error('permission denied'); },
|
||||
})).toThrow(/cannot resolve hook runtime directory.*permission denied/);
|
||||
});
|
||||
it('fails visibly when target ownership cannot be determined', () => {
|
||||
expect(() =>
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => {
|
||||
throw new Error('permission denied');
|
||||
},
|
||||
}),
|
||||
).toThrow(/cannot resolve hook runtime directory.*permission denied/);
|
||||
});
|
||||
|
||||
it('uses the current convention when the target disappears during discovery', () => {
|
||||
const gone = Object.assign(new Error('process disappeared'), { code: 'ENOENT' });
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => { throw gone; },
|
||||
})).toBe('/run/user/0');
|
||||
});
|
||||
it('uses the current convention when the target disappears during discovery', () => {
|
||||
const gone = Object.assign(new Error('process disappeared'), { code: 'ENOENT' });
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => {
|
||||
throw gone;
|
||||
},
|
||||
}),
|
||||
).toBe('/run/user/0');
|
||||
});
|
||||
|
||||
it('honours an explicit runtime directory inherited by the QQ process', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: {},
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0',
|
||||
'/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/srv/snowluma-hook');
|
||||
});
|
||||
it('honours an explicit runtime directory inherited by the QQ process', () => {
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: {},
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0',
|
||||
'/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
}),
|
||||
).toBe('/srv/snowluma-hook');
|
||||
});
|
||||
});
|
||||
+1270
-1053
File diff suppressed because it is too large.
Load diff
@@ -3,54 +3,66 @@ import { statusFor, type HookFlags } from '../src/hook-status';
|
||||
import type { HookProcessStatus } from '../src/types';
|
||||
|
||||
const F = (o: Partial<HookFlags>): HookFlags => ({
|
||||
injected: false, connected: false, loggedIn: false, wasLoggedIn: false, ...o,
|
||||
injected: false,
|
||||
connected: false,
|
||||
loggedIn: false,
|
||||
wasLoggedIn: false,
|
||||
...o,
|
||||
});
|
||||
|
||||
describe('statusFor — settled HookProcessStatus derivation', () => {
|
||||
it('not injected → available (regardless of other flags)', () => {
|
||||
expect(statusFor(F({ injected: false }))).toBe('available');
|
||||
// !injected dominates: stale connected/loggedIn bits must not leak through.
|
||||
expect(statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true }))).toBe('available');
|
||||
});
|
||||
it('not injected → available (regardless of other flags)', () => {
|
||||
expect(statusFor(F({ injected: false }))).toBe('available');
|
||||
// !injected dominates: stale connected/loggedIn bits must not leak through.
|
||||
expect(
|
||||
statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true })),
|
||||
).toBe('available');
|
||||
});
|
||||
|
||||
it('injected, connected, loggedIn → online', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online');
|
||||
});
|
||||
it('injected, connected, loggedIn → online', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online');
|
||||
});
|
||||
|
||||
it('injected, connected, not loggedIn → loaded', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded');
|
||||
});
|
||||
it('injected, connected, not loggedIn → loaded', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded');
|
||||
});
|
||||
|
||||
it('injected, not connected, had logged in → disconnected', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe('disconnected');
|
||||
});
|
||||
it('injected, not connected, had logged in → disconnected', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe(
|
||||
'disconnected',
|
||||
);
|
||||
});
|
||||
|
||||
it('injected, not connected, never logged in → connecting', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe('connecting');
|
||||
});
|
||||
it('injected, not connected, never logged in → connecting', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe(
|
||||
'connecting',
|
||||
);
|
||||
});
|
||||
|
||||
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
|
||||
const base = { injected: true, connected: false, loggedIn: false };
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected');
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting');
|
||||
});
|
||||
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
|
||||
const base = { injected: true, connected: false, loggedIn: false };
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected');
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting');
|
||||
});
|
||||
|
||||
it('covers exactly the five settled states across the flag space', () => {
|
||||
const seen = new Set<HookProcessStatus>();
|
||||
for (const injected of [false, true]) {
|
||||
for (const connected of [false, true]) {
|
||||
for (const loggedIn of [false, true]) {
|
||||
for (const wasLoggedIn of [false, true]) {
|
||||
seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn }));
|
||||
}
|
||||
it('covers exactly the five settled states across the flag space', () => {
|
||||
const seen = new Set<HookProcessStatus>();
|
||||
|
||||
for (const injected of [false, true]) {
|
||||
for (const connected of [false, true]) {
|
||||
for (const loggedIn of [false, true]) {
|
||||
for (const wasLoggedIn of [false, true]) {
|
||||
seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect([...seen].sort()).toEqual(
|
||||
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
|
||||
);
|
||||
// The two out-of-band states are never produced by the pure derivation.
|
||||
expect(seen.has('loading')).toBe(false);
|
||||
expect(seen.has('error')).toBe(false);
|
||||
});
|
||||
|
||||
expect([...seen].sort()).toEqual(
|
||||
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
|
||||
);
|
||||
// The two out-of-band states are never produced by the pure derivation.
|
||||
expect(seen.has('loading')).toBe(false);
|
||||
expect(seen.has('error')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -3,400 +3,424 @@ import { fileURLToPath } from 'url';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { existsSyncMock, listPidsMock } = vi.hoisted(() => ({
|
||||
existsSyncMock: vi.fn<(target: string) => boolean>(() => false),
|
||||
listPidsMock: vi.fn(() => new Set<number>()),
|
||||
existsSyncMock: vi.fn<(target: string) => boolean>(() => false),
|
||||
listPidsMock: vi.fn(() => new Set<number>()),
|
||||
}));
|
||||
|
||||
vi.mock('fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('fs')>();
|
||||
return {
|
||||
...actual,
|
||||
existsSync: (target: Parameters<typeof actual.existsSync>[0]) =>
|
||||
existsSyncMock(String(target)),
|
||||
};
|
||||
const actual = await importOriginal<typeof import('fs')>();
|
||||
return {
|
||||
...actual,
|
||||
existsSync: (target: Parameters<typeof actual.existsSync>[0]) =>
|
||||
existsSyncMock(String(target)),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../src/qq-hook-client', () => ({
|
||||
listSnowlumaPipePidsSync: listPidsMock,
|
||||
listSnowlumaPipePidsSync: listPidsMock,
|
||||
}));
|
||||
|
||||
const INJECTOR_DIR = path.dirname(fileURLToPath(new URL('../src/injector.ts', import.meta.url)));
|
||||
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;
|
||||
|
||||
const HANDLE = {
|
||||
base: 0x7fff0000n,
|
||||
entry: 0x7fff1234n,
|
||||
exceptionTable: 0x7fff5678n,
|
||||
size: 8192,
|
||||
base: 0x7fff0000n,
|
||||
entry: 0x7fff1234n,
|
||||
exceptionTable: 0x7fff5678n,
|
||||
size: 8192,
|
||||
};
|
||||
|
||||
function setPlatform(platform: NodeJS.Platform, arch: string): void {
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: arch, configurable: true });
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: arch, configurable: true });
|
||||
}
|
||||
|
||||
function restorePlatform(): void {
|
||||
Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
|
||||
Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
|
||||
}
|
||||
|
||||
function nativeSearchDirs(cwd = process.cwd()): string[] {
|
||||
return [
|
||||
path.resolve(INJECTOR_DIR, 'native'),
|
||||
path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(cwd, 'dist', 'native'),
|
||||
path.resolve(cwd, 'packages', 'runtime', 'native'),
|
||||
];
|
||||
function nativeSearchDirs(): string[] {
|
||||
return [
|
||||
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 {
|
||||
const allowed = new Set(paths);
|
||||
existsSyncMock.mockImplementation((target) => allowed.has(target));
|
||||
const allowed = new Set(paths);
|
||||
existsSyncMock.mockImplementation((target) => allowed.has(target));
|
||||
}
|
||||
|
||||
function fakeAddon(overrides: {
|
||||
getAllMainProcess?: number[];
|
||||
loadModuleManual?: (pid: number, dylibPath: string) => unknown;
|
||||
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
|
||||
} = {}) {
|
||||
return {
|
||||
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []),
|
||||
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
|
||||
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)),
|
||||
};
|
||||
function fakeAddon(
|
||||
overrides: {
|
||||
getAllMainProcessAsync?: number[];
|
||||
loadModuleManualAsync?: (pid: number, dylibPath: string) => Promise<typeof HANDLE>;
|
||||
unloadModuleManualAsync?: (pid: number, handle: typeof HANDLE) => Promise<void>;
|
||||
} = {},
|
||||
) {
|
||||
return {
|
||||
getAllMainProcessAsync: vi.fn(async () => overrides.getAllMainProcessAsync ?? []),
|
||||
loadModuleManualAsync: vi.fn(overrides.loadModuleManualAsync ?? (async () => HANDLE)),
|
||||
unloadModuleManualAsync: vi.fn(
|
||||
overrides.unloadModuleManualAsync ?? (async () => undefined),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function installDlopen(addon: object) {
|
||||
return vi.spyOn(process, 'dlopen').mockImplementation((mod) => {
|
||||
(mod as { exports: object }).exports = addon;
|
||||
});
|
||||
return vi.spyOn(process, 'dlopen').mockImplementation((mod) => {
|
||||
(mod as { exports: object }).exports = addon;
|
||||
});
|
||||
}
|
||||
|
||||
async function loadInjector() {
|
||||
return import('../src/injector');
|
||||
return import('../src/injector');
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
existsSyncMock.mockReset();
|
||||
existsSyncMock.mockReturnValue(false);
|
||||
listPidsMock.mockReset();
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
vi.resetModules();
|
||||
existsSyncMock.mockReset();
|
||||
existsSyncMock.mockReturnValue(false);
|
||||
listPidsMock.mockReset();
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
restorePlatform();
|
||||
vi.restoreAllMocks();
|
||||
restorePlatform();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('resolveHookNativePath', () => {
|
||||
it('returns null after probing every search directory', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return false;
|
||||
it('returns null after probing every search directory', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return false;
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBeNull();
|
||||
expect(probed).toEqual([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.node', 1),
|
||||
]);
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBeNull();
|
||||
expect(probed).toEqual([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.node', 1),
|
||||
nativeCandidate('snowluma-linux-x64.node', 2),
|
||||
nativeCandidate('snowluma-linux-x64.node', 3),
|
||||
]);
|
||||
});
|
||||
it('returns the first existing candidate and stops scanning', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const winner = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
const later = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return target === winner || target === later;
|
||||
});
|
||||
|
||||
it('returns the first existing candidate and stops scanning', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const winner = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
const later = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return target === winner || target === later;
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
expect(probed).toEqual([winner]);
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
expect(probed).toEqual([winner]);
|
||||
});
|
||||
it('skips missing earlier directories for the injectable .so', async () => {
|
||||
setPlatform('linux', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-linux-arm64.so', 1);
|
||||
allowExisting([winner]);
|
||||
|
||||
it('skips missing earlier directories for the injectable .so', async () => {
|
||||
setPlatform('linux', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-linux-arm64.so', 2);
|
||||
allowExisting([winner]);
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('so')).toBe(winner);
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('so')).toBe(winner);
|
||||
});
|
||||
it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const winner = nativeCandidate('snowluma-win32-x64.dll', 1);
|
||||
allowExisting([winner]);
|
||||
|
||||
it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const winner = nativeCandidate('snowluma-win32-x64.dll', 3);
|
||||
allowExisting([winner]);
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('dll')).toBe(winner);
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('dll')).toBe(winner);
|
||||
});
|
||||
it('uses the generic platform-arch name on win32 arm64', async () => {
|
||||
setPlatform('win32', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-win32-arm64.node', 1);
|
||||
allowExisting([winner]);
|
||||
|
||||
it('uses the generic platform-arch name on win32 arm64', async () => {
|
||||
setPlatform('win32', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-win32-arm64.node', 1);
|
||||
allowExisting([winner]);
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
it('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(
|
||||
'/tmp/sl-injector-cwd',
|
||||
'dist',
|
||||
'native',
|
||||
'snowluma-darwin-arm64.node',
|
||||
);
|
||||
allowExisting([winner]);
|
||||
|
||||
it('re-reads process.cwd() for the dist/native fallback', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
|
||||
const winner = path.join('/tmp/sl-injector-cwd', 'dist', 'native', 'snowluma-darwin-arm64.node');
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getNativeHookAddon / getNativeHookLoadError', () => {
|
||||
it('starts with a null load error before any probe', async () => {
|
||||
const { getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null and records a missing-binary error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const dlopen = vi.spyOn(process, 'dlopen');
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('dlopens the resolved .node once and caches the addon', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
const addon = fakeAddon();
|
||||
const dlopen = installDlopen(addon);
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
const first = getNativeHookAddon();
|
||||
const second = getNativeHookAddon();
|
||||
|
||||
expect(first).toBe(addon);
|
||||
expect(second).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
expect(dlopen).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen.mock.calls[0]![1]).toBe(nodePath);
|
||||
});
|
||||
|
||||
it('stores Error.message when process.dlopen throws', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw new Error('not a valid Node addon');
|
||||
it('starts with a null load error before any probe', async () => {
|
||||
const { getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('not a valid Node addon');
|
||||
});
|
||||
it('returns null and records a missing-binary error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const dlopen = vi.spyOn(process, 'dlopen');
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
|
||||
it('stringifies a non-Error dlopen failure', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw 42;
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('42');
|
||||
});
|
||||
it('dlopens the resolved .node once and caches the addon', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
const addon = fakeAddon();
|
||||
const dlopen = installDlopen(addon);
|
||||
|
||||
it('retries after a failed load when a binary later appears', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
const first = getNativeHookAddon();
|
||||
const second = getNativeHookAddon();
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
expect(first).toBe(addon);
|
||||
expect(second).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
expect(dlopen).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen.mock.calls[0]![1]).toBe(nodePath);
|
||||
});
|
||||
|
||||
allowExisting([nodePath]);
|
||||
expect(getNativeHookAddon()).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
it('stores Error.message when process.dlopen throws', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw new Error('not a valid Node addon');
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('not a valid Node addon');
|
||||
});
|
||||
|
||||
it('stringifies a non-Error dlopen failure', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw 42;
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('42');
|
||||
});
|
||||
|
||||
it('retries after a failed load when a binary later appears', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
|
||||
allowExisting([nodePath]);
|
||||
expect(getNativeHookAddon()).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('listHookProcesses', () => {
|
||||
it('on darwin maps sorted pipe pids without opening the native addon', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set([42, 7, 15]));
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] }));
|
||||
it('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();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 7, name: 'qq', path: '' },
|
||||
{ pid: 15, name: 'qq', path: '' },
|
||||
{ pid: 42, name: 'qq', path: '' },
|
||||
]);
|
||||
expect(listPidsMock).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
await expect(listHookProcesses()).rejects.toThrow('getAllMainProcessAsync');
|
||||
expect(getAllMainProcess).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('on darwin returns an empty list when no control sockets exist', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
it('on darwin 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({ getAllMainProcessAsync: [99] }));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
});
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(await listHookProcesses()).toEqual([
|
||||
{ pid: 7, name: 'qq', path: '' },
|
||||
{ pid: 15, name: 'qq', path: '' },
|
||||
{ pid: 42, name: 'qq', path: '' },
|
||||
]);
|
||||
expect(listPidsMock).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('on non-darwin returns [] when the addon cannot be loaded', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
it('on darwin returns an empty list when no control sockets exist', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
});
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(await listHookProcesses()).toEqual([]);
|
||||
});
|
||||
|
||||
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
installDlopen(fakeAddon({
|
||||
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
|
||||
}));
|
||||
it('reports a missing addon instead of an empty process set', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 2, name: 'qq', path: '' },
|
||||
{ pid: 8, name: 'qq', path: '' },
|
||||
]);
|
||||
});
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
await expect(listHookProcesses()).rejects.toThrow(
|
||||
'No hook native addon found for linux-x64',
|
||||
);
|
||||
});
|
||||
|
||||
it('on win32 names processes QQ.exe', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
|
||||
installDlopen(fakeAddon({ getAllMainProcess: [9] }));
|
||||
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
installDlopen(
|
||||
fakeAddon({
|
||||
getAllMainProcessAsync: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
|
||||
}),
|
||||
);
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 9, name: 'QQ.exe', path: '' },
|
||||
]);
|
||||
});
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(await listHookProcesses()).toEqual([
|
||||
{ pid: 2, name: 'qq', path: '' },
|
||||
{ pid: 8, name: 'qq', path: '' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('on win32 names processes QQ.exe', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
|
||||
installDlopen(fakeAddon({ getAllMainProcessAsync: [9] }));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(await listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('injectHookProcess', () => {
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow('No hook native addon found for linux-x64');
|
||||
});
|
||||
|
||||
it('throws when the addon exists but the injectable is missing', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
installDlopen(fakeAddon());
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64');
|
||||
});
|
||||
|
||||
it('awaits a thenable loadModuleManual handle', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
const soPath = nativeCandidate('snowluma-linux-x64.so', 0);
|
||||
allowExisting([nodePath, soPath]);
|
||||
const addon = fakeAddon({
|
||||
loadModuleManual: () => Promise.resolve(HANDLE),
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow(
|
||||
'No hook native addon found for linux-x64',
|
||||
);
|
||||
});
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
it('throws when the addon exists but the injectable is missing', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
installDlopen(fakeAddon());
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64');
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledTimes(1);
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath);
|
||||
});
|
||||
|
||||
it('accepts a synchronous loadModuleManual return value', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2);
|
||||
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3);
|
||||
allowExisting([nodePath, soPath]);
|
||||
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
|
||||
installDlopen(addon);
|
||||
it('awaits 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({
|
||||
loadModuleManualAsync: () => Promise.resolve(HANDLE),
|
||||
});
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(77)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
});
|
||||
expect(addon.loadModuleManualAsync).toHaveBeenCalledTimes(1);
|
||||
expect(addon.loadModuleManualAsync).toHaveBeenCalledWith(4242, soPath);
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath);
|
||||
});
|
||||
|
||||
it('injects snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-win32-x64.node', 0);
|
||||
const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0);
|
||||
allowExisting([nodePath, dllPath]);
|
||||
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
|
||||
installDlopen(addon);
|
||||
it('injects snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-win32-x64.node', 0);
|
||||
const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0);
|
||||
allowExisting([nodePath, dllPath]);
|
||||
const addon = fakeAddon({ loadModuleManualAsync: async () => HANDLE });
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(5150)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(5150)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
});
|
||||
expect(addon.loadModuleManualAsync).toHaveBeenCalledWith(5150, dllPath);
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath);
|
||||
});
|
||||
|
||||
it('propagates a rejected loadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.so', 0),
|
||||
]);
|
||||
installDlopen(fakeAddon({
|
||||
loadModuleManual: () => Promise.reject(new Error('map failed')),
|
||||
}));
|
||||
it('propagates a rejected loadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.so', 0),
|
||||
]);
|
||||
installDlopen(
|
||||
fakeAddon({
|
||||
loadModuleManualAsync: () => Promise.reject(new Error('map failed')),
|
||||
}),
|
||||
);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(7)).rejects.toThrow('map failed');
|
||||
});
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(7)).rejects.toThrow('map failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('unloadHookProcess', () => {
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
expect(() => unloadHookProcess(4242, HANDLE)).toThrow('No hook native addon found for linux-x64');
|
||||
});
|
||||
it('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('forwards pid and handle to unloadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
await expect(unloadHookProcess(4242, HANDLE)).rejects.toThrow(
|
||||
'No hook native addon found for linux-x64',
|
||||
);
|
||||
});
|
||||
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
expect(unloadHookProcess(4242, HANDLE)).toBeUndefined();
|
||||
expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1);
|
||||
expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE);
|
||||
});
|
||||
it('forwards pid and handle to unloadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
await expect(unloadHookProcess(4242, HANDLE)).resolves.toBeUndefined();
|
||||
expect(addon.unloadModuleManualAsync).toHaveBeenCalledTimes(1);
|
||||
expect(addon.unloadModuleManualAsync).toHaveBeenCalledWith(4242, HANDLE);
|
||||
});
|
||||
});
|
||||
@@ -6,25 +6,25 @@ const PACKET = 'SNOWLUMA_PACKET_TIMEOUT_MS';
|
||||
const ACK = 'SNOWLUMA_HOOK_ACK_TIMEOUT_MS';
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env[PACKET];
|
||||
delete process.env[ACK];
|
||||
delete process.env[PACKET];
|
||||
delete process.env[ACK];
|
||||
});
|
||||
|
||||
describe('packet and hook ack timeouts', () => {
|
||||
it('keeps the 15 second packet default', () => {
|
||||
expect(packetTimeoutMs({})).toBe(15_000);
|
||||
});
|
||||
it('keeps the 15 second packet default', () => {
|
||||
expect(packetTimeoutMs({})).toBe(15_000);
|
||||
});
|
||||
|
||||
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
|
||||
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
|
||||
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
|
||||
});
|
||||
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
|
||||
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
|
||||
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
|
||||
});
|
||||
|
||||
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
|
||||
process.env[ACK] = '1200';
|
||||
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
|
||||
expect(client.defaultAckTimeoutMs).toBe(1200);
|
||||
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
|
||||
expect(explicit.defaultAckTimeoutMs).toBe(50);
|
||||
});
|
||||
});
|
||||
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
|
||||
process.env[ACK] = '1200';
|
||||
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
|
||||
expect(client.defaultAckTimeoutMs).toBe(1200);
|
||||
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
|
||||
expect(explicit.defaultAckTimeoutMs).toBe(50);
|
||||
});
|
||||
});
|
||||
@@ -1,284 +1,476 @@
|
||||
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';
|
||||
|
||||
function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<number> }) {
|
||||
let processes = initial.processes;
|
||||
let live = initial.live;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
// Defensively copy so the watcher can't mutate the test's reference.
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
|
||||
});
|
||||
return {
|
||||
watcher,
|
||||
setProcesses: (p: HookProcessBaseInfo[]) => { processes = p; },
|
||||
setLive: (s: Set<number>) => { live = s; },
|
||||
};
|
||||
let processes = initial.processes;
|
||||
let live = initial.live;
|
||||
const watcher = new PipeWatcher({
|
||||
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
|
||||
});
|
||||
return {
|
||||
watcher,
|
||||
setProcesses: (p: HookProcessBaseInfo[]) => {
|
||||
processes = p;
|
||||
},
|
||||
setLive: (s: Set<number>) => {
|
||||
live = s;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type EventRow = [string, unknown];
|
||||
|
||||
function captureEvents(watcher: PipeWatcher): EventRow[] {
|
||||
const events: EventRow[] = [];
|
||||
watcher.on('process-discovered', info => events.push(['discovered', (info as HookProcessBaseInfo).pid]));
|
||||
watcher.on('process-gone', pid => events.push(['gone', pid]));
|
||||
watcher.on('pipe-up', pid => events.push(['up', pid]));
|
||||
watcher.on('pipe-down', pid => events.push(['down', pid]));
|
||||
return events;
|
||||
const events: EventRow[] = [];
|
||||
watcher.on('process-discovered', (info) =>
|
||||
events.push(['discovered', (info as HookProcessBaseInfo).pid]),
|
||||
);
|
||||
watcher.on('process-gone', (pid) => events.push(['gone', pid]));
|
||||
watcher.on('pipe-up', (pid) => events.push(['up', pid]));
|
||||
watcher.on('pipe-down', (pid) => events.push(['down', pid]));
|
||||
return events;
|
||||
}
|
||||
|
||||
describe('PipeWatcher', () => {
|
||||
it('passes the current process snapshot to pipe discovery', async () => {
|
||||
const processes = [
|
||||
{ pid: 1234, name: 'qq', path: '/opt/QQ/qq' },
|
||||
{ pid: 5678, name: 'qq', path: '/opt/QQ/qq' },
|
||||
];
|
||||
let observed: readonly HookProcessBaseInfo[] | undefined;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
listLivePipes: async current => {
|
||||
observed = current;
|
||||
return new Set();
|
||||
},
|
||||
intervalMs: 60_000,
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
|
||||
expect(observed).toEqual(processes);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
expect(events).toEqual([
|
||||
['discovered', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(true);
|
||||
expect(ctx.watcher.isProcessAlive(1234)).toBe(true);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('pipe-down emitted when a previously-live pipe disappears', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['down', 1234]]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setProcesses([]);
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('ignores live pipes whose process is not running', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [],
|
||||
live: new Set([9999]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
expect(ctx.watcher.isPipeLive(9999)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234], ['down', 1234]]);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234], ['down', 1234], ['up', 1234]]);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('does not double-emit on idempotent ticks (no state change)', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits "tick" after every poll', async () => {
|
||||
const ctx = setupWatcher({ processes: [], live: new Set() });
|
||||
let ticks = 0;
|
||||
ctx.watcher.on('tick', () => { ticks++; });
|
||||
|
||||
await ctx.watcher.start();
|
||||
expect(ticks).toBe(1);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
expect(ticks).toBe(2);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('wake() pulls the next tick forward', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
// Wait on 'tick' rather than guessing how many event-loop turns
|
||||
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
|
||||
const nextTick = new Promise<void>(resolve => ctx.watcher.once('tick', () => resolve()));
|
||||
ctx.setLive(new Set([1234]));
|
||||
ctx.watcher.wake();
|
||||
await nextTick;
|
||||
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('survives a throwing listProcesses without crashing the watcher', async () => {
|
||||
let processes: HookProcessBaseInfo[] = [];
|
||||
let live = new Set<number>();
|
||||
let shouldThrow = true;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => {
|
||||
if (shouldThrow) throw new Error('boom');
|
||||
return processes;
|
||||
},
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
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();
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
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;
|
||||
}
|
||||
|
||||
shouldThrow = false;
|
||||
processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
live = new Set([1234]);
|
||||
const events = captureEvents(watcher);
|
||||
await watcher.tickNow();
|
||||
return processes;
|
||||
});
|
||||
const listLivePipes = vi.fn(async () => {
|
||||
if (stage === 'pipes') {
|
||||
entered();
|
||||
await gate;
|
||||
}
|
||||
|
||||
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
|
||||
watcher.stop();
|
||||
});
|
||||
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('preserves live sessions when pipe discovery temporarily fails', async () => {
|
||||
let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
let failPipeDiscovery = false;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
listLivePipes: async () => {
|
||||
if (failPipeDiscovery) throw new Error('permission denied');
|
||||
return new Set([1234]);
|
||||
},
|
||||
intervalMs: 60_000,
|
||||
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();
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
const events = captureEvents(watcher);
|
||||
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,
|
||||
});
|
||||
|
||||
failPipeDiscovery = true;
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
processes = [];
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
expect(watcher.isPipeLive(1234)).toBe(false);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => {
|
||||
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
let live = new Set<number>([1234]);
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => result,
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
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();
|
||||
});
|
||||
|
||||
const events = captureEvents(watcher);
|
||||
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();
|
||||
});
|
||||
|
||||
// Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ
|
||||
// hot-update). Prior process + pipe state MUST be preserved — no teardown.
|
||||
result = null;
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
it('passes the current process snapshot to pipe discovery', async () => {
|
||||
const processes = [
|
||||
{ pid: 1234, name: 'qq', path: '/opt/QQ/qq' },
|
||||
{ pid: 5678, name: 'qq', path: '/opt/QQ/qq' },
|
||||
];
|
||||
let observed: readonly HookProcessBaseInfo[] | undefined;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: async () => processes,
|
||||
listLivePipes: async (current) => {
|
||||
observed = current;
|
||||
return new Set();
|
||||
},
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
// Enumeration recovers with the same set → still no churn.
|
||||
result = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
await watcher.start();
|
||||
|
||||
// A REAL disappearance (empty list, not null) still fires the teardown.
|
||||
result = [];
|
||||
live = new Set();
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
|
||||
watcher.stop();
|
||||
});
|
||||
expect(observed).toEqual(processes);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
expect(events).toEqual([
|
||||
['discovered', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(true);
|
||||
expect(ctx.watcher.isProcessAlive(1234)).toBe(true);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('pipe-down emitted when a previously-live pipe disappears', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['down', 1234]]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setProcesses([]);
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('ignores live pipes whose process is not running', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [],
|
||||
live: new Set([9999]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
expect(ctx.watcher.isPipeLive(9999)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([
|
||||
['up', 1234],
|
||||
['down', 1234],
|
||||
]);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([
|
||||
['up', 1234],
|
||||
['down', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('does not double-emit on idempotent ticks (no state change)', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits "tick" after every poll', async () => {
|
||||
const ctx = setupWatcher({ processes: [], live: new Set() });
|
||||
let ticks = 0;
|
||||
ctx.watcher.on('tick', () => {
|
||||
ticks++;
|
||||
});
|
||||
|
||||
await ctx.watcher.start();
|
||||
expect(ticks).toBe(1);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
expect(ticks).toBe(2);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('wake() pulls the next tick forward', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
// Wait on 'tick' rather than guessing how many event-loop turns
|
||||
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
|
||||
const nextTick = new Promise<void>((resolve) => ctx.watcher.once('tick', () => resolve()));
|
||||
ctx.setLive(new Set([1234]));
|
||||
ctx.watcher.wake();
|
||||
await nextTick;
|
||||
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('survives a throwing listProcesses without crashing the watcher', async () => {
|
||||
let processes: HookProcessBaseInfo[] = [];
|
||||
let live = new Set<number>();
|
||||
let shouldThrow = true;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: async () => {
|
||||
if (shouldThrow) {
|
||||
throw new Error('boom');
|
||||
}
|
||||
|
||||
return processes;
|
||||
},
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
|
||||
shouldThrow = false;
|
||||
processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
live = new Set([1234]);
|
||||
const events = captureEvents(watcher);
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([
|
||||
['discovered', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('preserves live sessions when pipe discovery temporarily fails', async () => {
|
||||
let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
let failPipeDiscovery = false;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: async () => processes,
|
||||
listLivePipes: async () => {
|
||||
if (failPipeDiscovery) {
|
||||
throw new Error('permission denied');
|
||||
}
|
||||
|
||||
return new Set([1234]);
|
||||
},
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
const events = captureEvents(watcher);
|
||||
|
||||
failPipeDiscovery = true;
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
processes = [];
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
expect(watcher.isPipeLive(1234)).toBe(false);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => {
|
||||
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
let live = new Set<number>([1234]);
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: async () => result,
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
const events = captureEvents(watcher);
|
||||
|
||||
// Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ
|
||||
// hot-update). Prior process + pipe state MUST be preserved — no teardown.
|
||||
result = null;
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
// Enumeration recovers with the same set → still no churn.
|
||||
result = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
|
||||
// A REAL disappearance (empty list, not null) still fires the teardown.
|
||||
result = [];
|
||||
live = new Set();
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
watcher.stop();
|
||||
});
|
||||
});
|
||||
@@ -1,55 +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 };
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => { throw new Error('boom'); },
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toBeNull();
|
||||
en.dispose();
|
||||
it('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();
|
||||
});
|
||||
});
|
||||
|
||||
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.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');
|
||||
}
|
||||
|
||||
// First call spawns the worker; the fatal message drains it to UNKNOWN.
|
||||
const first = await en.enumerate();
|
||||
expect(first).toBeNull();
|
||||
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();
|
||||
},
|
||||
);
|
||||
|
||||
// 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('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();
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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: [] });
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,695 +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,
|
||||
});
|
||||
expect(warnings).toEqual([]);
|
||||
} 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();
|
||||
});
|
||||
});
|
||||
@@ -1,63 +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();
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
@@ -1,13 +1,29 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.14.22",
|
||||
"version": "2.0.1",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -5,35 +5,40 @@ import { translations } from '@zxcvbn-ts/language-en';
|
||||
export const ACCESS_TOKEN_MIN_LENGTH = 16;
|
||||
export const ACCESS_TOKEN_MIN_SCORE = 3;
|
||||
|
||||
export type AccessTokenAssessmentReason =
|
||||
| 'empty'
|
||||
| 'too-short'
|
||||
| 'guessable'
|
||||
| 'acceptable';
|
||||
export type AccessTokenAssessmentReason = 'empty' | 'too-short' | 'guessable' | 'acceptable';
|
||||
|
||||
export interface AccessTokenAssessment {
|
||||
acceptable: boolean;
|
||||
reason: AccessTokenAssessmentReason;
|
||||
score: number;
|
||||
acceptable: boolean;
|
||||
reason: AccessTokenAssessmentReason;
|
||||
score: number;
|
||||
}
|
||||
|
||||
const checker = new ZxcvbnFactory({
|
||||
translations,
|
||||
graphs: adjacencyGraphs,
|
||||
dictionary,
|
||||
translations,
|
||||
graphs: adjacencyGraphs,
|
||||
dictionary,
|
||||
});
|
||||
|
||||
function normalizeUserInputs(values: readonly (string | number)[]): Array<string | number> {
|
||||
const unique = new Set<string | number>(['SnowLuma', 'OneBot']);
|
||||
for (const value of values) {
|
||||
if (typeof value === 'number') {
|
||||
if (Number.isFinite(value)) unique.add(value);
|
||||
continue;
|
||||
const unique = new Set<string | number>(['SnowLuma', 'OneBot']);
|
||||
|
||||
for (const value of values) {
|
||||
if (typeof value === 'number') {
|
||||
if (Number.isFinite(value)) {
|
||||
unique.add(value);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
const trimmed = value.trim();
|
||||
|
||||
if (trimmed) {
|
||||
unique.add(trimmed.slice(0, 256));
|
||||
}
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (trimmed) unique.add(trimmed.slice(0, 256));
|
||||
}
|
||||
return [...unique].slice(0, 24);
|
||||
|
||||
return [...unique].slice(0, 24);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,17 +47,22 @@ function normalizeUserInputs(values: readonly (string | number)[]): Array<string
|
||||
* trust context; an empty value is never considered strong here.
|
||||
*/
|
||||
export function assessAccessToken(
|
||||
token: string,
|
||||
userInputs: readonly (string | number)[] = [],
|
||||
token: string,
|
||||
userInputs: readonly (string | number)[] = [],
|
||||
): AccessTokenAssessment {
|
||||
if (!token) return { acceptable: false, reason: 'empty', score: 0 };
|
||||
if (token.length < ACCESS_TOKEN_MIN_LENGTH) {
|
||||
return { acceptable: false, reason: 'too-short', score: 0 };
|
||||
}
|
||||
if (!token) {
|
||||
return { acceptable: false, reason: 'empty', score: 0 };
|
||||
}
|
||||
|
||||
const score = checker.check(token, normalizeUserInputs(userInputs)).score;
|
||||
if (score < ACCESS_TOKEN_MIN_SCORE) {
|
||||
return { acceptable: false, reason: 'guessable', score };
|
||||
}
|
||||
return { acceptable: true, reason: 'acceptable', score };
|
||||
if (token.length < ACCESS_TOKEN_MIN_LENGTH) {
|
||||
return { acceptable: false, reason: 'too-short', score: 0 };
|
||||
}
|
||||
|
||||
const score = checker.check(token, normalizeUserInputs(userInputs)).score;
|
||||
|
||||
if (score < ACCESS_TOKEN_MIN_SCORE) {
|
||||
return { acceptable: false, reason: 'guessable', score };
|
||||
}
|
||||
|
||||
return { acceptable: true, reason: 'acceptable', score };
|
||||
}
|
||||
@@ -7,24 +7,28 @@
|
||||
|
||||
/** True only for a plain, non-null, non-array object. */
|
||||
export function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/** The value when it is a real boolean, else the fallback. Strings/numbers
|
||||
* are NOT coerced — `'true'` and `1` both yield the fallback. */
|
||||
export function boolOr(value: unknown, fallback: boolean): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
/** A finite number (numeric strings coerced) clamped to `[min, max]`, else
|
||||
* the fallback. Fractional precision is preserved — use `clampInt` to floor. */
|
||||
export function clampNum(value: unknown, min: number, max: number, fallback: number): number {
|
||||
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
return Math.min(max, Math.max(min, n));
|
||||
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
|
||||
|
||||
if (!Number.isFinite(n)) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return Math.min(max, Math.max(min, n));
|
||||
}
|
||||
|
||||
/** `clampNum` truncated toward zero — clamp first, then drop the fraction. */
|
||||
export function clampInt(value: unknown, min: number, max: number, fallback: number): number {
|
||||
return Math.trunc(clampNum(value, min, max, fallback));
|
||||
return Math.trunc(clampNum(value, min, max, fallback));
|
||||
}
|
||||
@@ -12,16 +12,21 @@
|
||||
* shape that was previously hand-rolled at each such call site.
|
||||
*/
|
||||
export async function mapWithConcurrency<T, R>(
|
||||
items: readonly T[],
|
||||
concurrency: number,
|
||||
fn: (item: T, index: number) => Promise<R>,
|
||||
items: readonly T[],
|
||||
concurrency: number,
|
||||
fn: (item: T, index: number) => Promise<R>,
|
||||
): Promise<R[]> {
|
||||
const limit = Math.max(1, Math.trunc(concurrency));
|
||||
const results = new Array<R>(items.length);
|
||||
for (let i = 0; i < items.length; i += limit) {
|
||||
const batch = items.slice(i, i + limit);
|
||||
const settled = await Promise.all(batch.map((item, j) => fn(item, i + j)));
|
||||
for (let j = 0; j < settled.length; j++) results[i + j] = settled[j]!;
|
||||
}
|
||||
return results;
|
||||
const limit = Math.max(1, Math.trunc(concurrency));
|
||||
const results = new Array<R>(items.length);
|
||||
|
||||
for (let i = 0; i < items.length; i += limit) {
|
||||
const batch = items.slice(i, i + limit);
|
||||
const settled = await Promise.all(batch.map((item, j) => fn(item, i + j)));
|
||||
|
||||
for (let j = 0; j < settled.length; j++) {
|
||||
results[i + j] = settled[j]!;
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
+19
-13
@@ -11,18 +11,24 @@ const MAX_POSITIVE_INT = 2_147_483_647;
|
||||
* value is ignored, with a warning, and also returns `fallback`.
|
||||
*/
|
||||
export function positiveIntEnv(
|
||||
name: string,
|
||||
fallback: number,
|
||||
options?: { max?: number; env?: NodeJS.ProcessEnv },
|
||||
name: string,
|
||||
fallback: number,
|
||||
options?: { max?: number; env?: NodeJS.ProcessEnv },
|
||||
): number {
|
||||
const max = options?.max ?? MAX_POSITIVE_INT;
|
||||
const raw = (options?.env ?? process.env)[name];
|
||||
if (typeof raw !== 'string' || !raw.trim()) return fallback;
|
||||
const value = raw.trim();
|
||||
const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN;
|
||||
if (!Number.isSafeInteger(parsed) || parsed > max) {
|
||||
log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max);
|
||||
return fallback;
|
||||
}
|
||||
return parsed;
|
||||
const max = options?.max ?? MAX_POSITIVE_INT;
|
||||
const raw = (options?.env ?? process.env)[name];
|
||||
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const value = raw.trim();
|
||||
const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN;
|
||||
|
||||
if (!Number.isSafeInteger(parsed) || parsed > max) {
|
||||
log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
+16
-24
@@ -1,35 +1,27 @@
|
||||
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 {
|
||||
const limit = Math.max(0, Math.min(maxBytes, data.length));
|
||||
const head = toHex(data.subarray(0, limit));
|
||||
return data.length > limit ? `${head}...` : head;
|
||||
const limit = Math.max(0, Math.min(maxBytes, data.length));
|
||||
const head = toHex(data.subarray(0, limit));
|
||||
return data.length > limit ? `${head}...` : head;
|
||||
}
|
||||
|
||||
export function fromHex(hex: string): Buffer {
|
||||
if (hex.length % 2 !== 0) throw new Error('Invalid hex string length');
|
||||
const buf = Buffer.alloc(hex.length / 2);
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return buf;
|
||||
if (hex.length % 2 !== 0) {
|
||||
throw new Error('Invalid hex string length');
|
||||
}
|
||||
|
||||
const buf = Buffer.alloc(hex.length / 2);
|
||||
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
|
||||
return buf;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
|
||||
export interface JsonObject {
|
||||
[key: string]: JsonValue;
|
||||
[key: string]: JsonValue;
|
||||
}
|
||||
export type JsonArray = JsonValue[];
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,41 +6,70 @@ const C1_OSC = 0x9d;
|
||||
const C1_STRING_STARTERS = new Set([0x90, 0x98, 0x9e, 0x9f]);
|
||||
|
||||
function skipCsi(line: string, start: number): number {
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (code >= 0x40 && code <= 0x7e) return i + 1;
|
||||
}
|
||||
return line.length;
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
|
||||
if (code >= 0x40 && code <= 0x7e) {
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return line.length;
|
||||
}
|
||||
|
||||
function skipControlString(line: string, start: number, allowBell: boolean): number {
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (allowBell && code === BEL) return i + 1;
|
||||
if (code === C1_ST) return i + 1;
|
||||
if (code === ESC && line.charCodeAt(i + 1) === 0x5c) return i + 2;
|
||||
}
|
||||
return line.length;
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
|
||||
if (allowBell && code === BEL) {
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
if (code === C1_ST) {
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
if (code === ESC && line.charCodeAt(i + 1) === 0x5c) {
|
||||
return i + 2;
|
||||
}
|
||||
}
|
||||
|
||||
return line.length;
|
||||
}
|
||||
|
||||
function skipEscSequence(line: string, start: number): number {
|
||||
if (start >= line.length) return line.length;
|
||||
if (start >= line.length) {
|
||||
return line.length;
|
||||
}
|
||||
|
||||
const first = line.charCodeAt(start);
|
||||
if (first === 0x5b) return skipCsi(line, start + 1);
|
||||
if (first === 0x5d) return skipControlString(line, start + 1, true);
|
||||
if (first === 0x50 || first === 0x58 || first === 0x5e || first === 0x5f) {
|
||||
return skipControlString(line, start + 1, false);
|
||||
}
|
||||
const first = line.charCodeAt(start);
|
||||
|
||||
let i = start;
|
||||
while (i < line.length) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (code < 0x20 || code > 0x2f) break;
|
||||
i += 1;
|
||||
}
|
||||
const final = line.charCodeAt(i);
|
||||
return final >= 0x30 && final <= 0x7e ? i + 1 : start;
|
||||
if (first === 0x5b) {
|
||||
return skipCsi(line, start + 1);
|
||||
}
|
||||
|
||||
if (first === 0x5d) {
|
||||
return skipControlString(line, start + 1, true);
|
||||
}
|
||||
|
||||
if (first === 0x50 || first === 0x58 || first === 0x5e || first === 0x5f) {
|
||||
return skipControlString(line, start + 1, false);
|
||||
}
|
||||
|
||||
let i = start;
|
||||
|
||||
while (i < line.length) {
|
||||
const code = line.charCodeAt(i);
|
||||
|
||||
if (code < 0x20 || code > 0x2f) {
|
||||
break;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
const final = line.charCodeAt(i);
|
||||
return final >= 0x30 && final <= 0x7e ? i + 1 : start;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,29 +82,34 @@ function skipEscSequence(line: string, start: number): number {
|
||||
* invisible payload into persisted or downloaded logs.
|
||||
*/
|
||||
export function sanitizeLogLine(line: string): string {
|
||||
let plain = '';
|
||||
for (let i = 0; i < line.length;) {
|
||||
const code = line.charCodeAt(i);
|
||||
let plain = '';
|
||||
|
||||
if (code === ESC) {
|
||||
i = skipEscSequence(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
if (code === C1_CSI) {
|
||||
i = skipCsi(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
|
||||
i = skipControlString(line, i + 1, code === C1_OSC);
|
||||
continue;
|
||||
}
|
||||
if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) {
|
||||
i += 1;
|
||||
continue;
|
||||
for (let i = 0; i < line.length;) {
|
||||
const code = line.charCodeAt(i);
|
||||
|
||||
if (code === ESC) {
|
||||
i = skipEscSequence(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (code === C1_CSI) {
|
||||
i = skipCsi(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
|
||||
i = skipControlString(line, i + 1, code === C1_OSC);
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
plain += line[i];
|
||||
i += 1;
|
||||
}
|
||||
|
||||
plain += line[i];
|
||||
i += 1;
|
||||
}
|
||||
return plain;
|
||||
return plain;
|
||||
}
|
||||
+308
-238
@@ -1,54 +1,67 @@
|
||||
const MAX_FIELD = 40;
|
||||
const MAX_TOTAL = 200;
|
||||
const SENSITIVE_SEGMENTS = new Set([
|
||||
'authorization',
|
||||
'cookie',
|
||||
'credential',
|
||||
'credentials',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
'authorization',
|
||||
'cookie',
|
||||
'credential',
|
||||
'credentials',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
]);
|
||||
|
||||
function isSensitiveKey(key: string): boolean {
|
||||
const segments = key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
const segments = key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
|
||||
return segments.some((segment, index) => {
|
||||
if (SENSITIVE_SEGMENTS.has(segment)) return true;
|
||||
const next = segments[index + 1];
|
||||
return next === 'key' && (
|
||||
segment === 'api'
|
||||
|| segment === 'private'
|
||||
|| segment === 'session'
|
||||
);
|
||||
});
|
||||
return segments.some((segment, index) => {
|
||||
if (SENSITIVE_SEGMENTS.has(segment)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const next = segments[index + 1];
|
||||
return (
|
||||
next === 'key' && (segment === 'api' || segment === 'private' || segment === 'session')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function valueRepr(v: unknown, key?: string): string {
|
||||
if (key !== undefined && isSensitiveKey(key)) return '"***"';
|
||||
if (v === null) return 'null';
|
||||
if (v === undefined) return 'undefined';
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(v);
|
||||
case 'object':
|
||||
if (Array.isArray(v)) return `[len=${v.length}]`;
|
||||
return '{...}';
|
||||
default:
|
||||
return typeof v;
|
||||
}
|
||||
if (key !== undefined && isSensitiveKey(key)) {
|
||||
return '"***"';
|
||||
}
|
||||
|
||||
if (v === null) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
if (v === undefined) {
|
||||
return 'undefined';
|
||||
}
|
||||
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(v);
|
||||
case 'object':
|
||||
if (Array.isArray(v)) {
|
||||
return `[len=${v.length}]`;
|
||||
}
|
||||
|
||||
return '{...}';
|
||||
default:
|
||||
return typeof v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,218 +73,265 @@ function valueRepr(v: unknown, key?: string): string {
|
||||
* replaced with `...` so the next field doesn't get half-rendered.
|
||||
*/
|
||||
export function summarizeParams(params: unknown): string {
|
||||
if (params === null || params === undefined) return '{}';
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL
|
||||
? `${s.slice(0, MAX_TOTAL - 3)}...`
|
||||
: s;
|
||||
}
|
||||
if (Array.isArray(params)) return `[len=${params.length}]`;
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v, k)}`;
|
||||
const separatorLength = out.length > 0 ? 1 : 0;
|
||||
if (total + separatorLength + entry.length > MAX_TOTAL) {
|
||||
if (out.length === 0) {
|
||||
return `${entry.slice(0, MAX_TOTAL - 3)}...`;
|
||||
}
|
||||
|
||||
const rendered = out.join(' ');
|
||||
return rendered.length + 4 <= MAX_TOTAL
|
||||
? `${rendered} ...`
|
||||
: `${rendered.slice(0, MAX_TOTAL - 3)}...`;
|
||||
if (params === null || params === undefined) {
|
||||
return '{}';
|
||||
}
|
||||
out.push(entry);
|
||||
total += separatorLength + entry.length;
|
||||
}
|
||||
return out.join(' ');
|
||||
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL - 3)}...` : s;
|
||||
}
|
||||
|
||||
if (Array.isArray(params)) {
|
||||
return `[len=${params.length}]`;
|
||||
}
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v, k)}`;
|
||||
const separatorLength = out.length > 0 ? 1 : 0;
|
||||
|
||||
if (total + separatorLength + entry.length > MAX_TOTAL) {
|
||||
if (out.length === 0) {
|
||||
return `${entry.slice(0, MAX_TOTAL - 3)}...`;
|
||||
}
|
||||
|
||||
const rendered = out.join(' ');
|
||||
return rendered.length + 4 <= MAX_TOTAL
|
||||
? `${rendered} ...`
|
||||
: `${rendered.slice(0, MAX_TOTAL - 3)}...`;
|
||||
}
|
||||
|
||||
out.push(entry);
|
||||
total += separatorLength + entry.length;
|
||||
}
|
||||
|
||||
return out.join(' ');
|
||||
}
|
||||
|
||||
const ASSIGNMENT_START = /(^|[^A-Za-z0-9_-])(["']?)([-_]*(?=[A-Za-z0-9_.-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9_.-]*)\2(\s*[:=]\s*)/gi;
|
||||
const ASSIGNMENT_START =
|
||||
/(^|[^A-Za-z0-9_-])(["']?)([-_]*(?=[A-Za-z0-9_.-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9_.-]*)\2(\s*[:=]\s*)/gi;
|
||||
const AUTHORIZATION_BOUNDARY_SEGMENTS = new Set([
|
||||
'authorization',
|
||||
'cookie',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
'authorization',
|
||||
'cookie',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
]);
|
||||
|
||||
function keySegments(key: string): string[] {
|
||||
return key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
return key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
}
|
||||
|
||||
function isKeyKind(key: string, kind: 'authorization' | 'cookie'): boolean {
|
||||
return keySegments(key).includes(kind);
|
||||
return keySegments(key).includes(kind);
|
||||
}
|
||||
|
||||
function isAuthorizationBoundaryKey(key: string): boolean {
|
||||
const segments = keySegments(key);
|
||||
return segments.some((segment, index) => {
|
||||
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) return true;
|
||||
const next = segments[index + 1];
|
||||
return next === 'key' && (
|
||||
segment === 'api'
|
||||
|| segment === 'private'
|
||||
|| segment === 'session'
|
||||
);
|
||||
});
|
||||
const segments = keySegments(key);
|
||||
return segments.some((segment, index) => {
|
||||
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const next = segments[index + 1];
|
||||
return (
|
||||
next === 'key' && (segment === 'api' || segment === 'private' || segment === 'session')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function quotedValueEnd(message: string, start: number): number | undefined {
|
||||
const quote = message[start];
|
||||
if (quote !== '"' && quote !== "'") return undefined;
|
||||
const quote = message[start];
|
||||
|
||||
for (let index = start + 1; index < message.length; index += 1) {
|
||||
if (message[index] === '\\') {
|
||||
index += 1;
|
||||
} else if (message[index] === quote) {
|
||||
return index + 1;
|
||||
if (quote !== '"' && quote !== "'") {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return message.length;
|
||||
|
||||
for (let index = start + 1; index < message.length; index += 1) {
|
||||
if (message[index] === '\\') {
|
||||
index += 1;
|
||||
} else if (message[index] === quote) {
|
||||
return index + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return message.length;
|
||||
}
|
||||
|
||||
function cookieValueEnd(message: string, start: number): number {
|
||||
const initialQuotedEnd = quotedValueEnd(message, start);
|
||||
let end: number;
|
||||
if (initialQuotedEnd !== undefined) {
|
||||
end = initialQuotedEnd;
|
||||
} else {
|
||||
end = start;
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
}
|
||||
const initialQuotedEnd = quotedValueEnd(message, start);
|
||||
let end: number;
|
||||
|
||||
while (end < message.length) {
|
||||
let semicolon: number = end;
|
||||
while (message[semicolon] === ' ' || message[semicolon] === '\t') {
|
||||
semicolon += 1;
|
||||
}
|
||||
if (message[semicolon] !== ';') break;
|
||||
if (initialQuotedEnd !== undefined) {
|
||||
end = initialQuotedEnd;
|
||||
} else {
|
||||
end = start;
|
||||
|
||||
let nameStart = semicolon + 1;
|
||||
while (message[nameStart] === ' ' || message[nameStart] === '\t') {
|
||||
nameStart += 1;
|
||||
}
|
||||
let nameEnd = nameStart;
|
||||
while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) nameEnd += 1;
|
||||
if (nameEnd === nameStart) break;
|
||||
|
||||
end = nameEnd;
|
||||
if (message[end] !== '=') continue;
|
||||
|
||||
const attribute = message.slice(nameStart, nameEnd).toLowerCase();
|
||||
const valueStart = end + 1;
|
||||
const quotedEnd = quotedValueEnd(message, valueStart);
|
||||
if (quotedEnd !== undefined) {
|
||||
end = quotedEnd;
|
||||
continue;
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (attribute !== 'expires') {
|
||||
end = valueStart;
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
continue;
|
||||
while (end < message.length) {
|
||||
let semicolon: number = end;
|
||||
|
||||
while (message[semicolon] === ' ' || message[semicolon] === '\t') {
|
||||
semicolon += 1;
|
||||
}
|
||||
|
||||
if (message[semicolon] !== ';') {
|
||||
break;
|
||||
}
|
||||
|
||||
let nameStart = semicolon + 1;
|
||||
|
||||
while (message[nameStart] === ' ' || message[nameStart] === '\t') {
|
||||
nameStart += 1;
|
||||
}
|
||||
|
||||
let nameEnd = nameStart;
|
||||
|
||||
while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) {
|
||||
nameEnd += 1;
|
||||
}
|
||||
|
||||
if (nameEnd === nameStart) {
|
||||
break;
|
||||
}
|
||||
|
||||
end = nameEnd;
|
||||
|
||||
if (message[end] !== '=') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const attribute = message.slice(nameStart, nameEnd).toLowerCase();
|
||||
const valueStart = end + 1;
|
||||
const quotedEnd = quotedValueEnd(message, valueStart);
|
||||
|
||||
if (quotedEnd !== undefined) {
|
||||
end = quotedEnd;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attribute !== 'expires') {
|
||||
end = valueStart;
|
||||
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
end = valueStart;
|
||||
|
||||
while (end < message.length && !/[;}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
assignments.lastIndex = valueStart;
|
||||
const nextField = assignments.exec(message);
|
||||
|
||||
if (nextField && nextField.index < end) {
|
||||
end = nextField.index;
|
||||
}
|
||||
}
|
||||
|
||||
end = valueStart;
|
||||
while (end < message.length && !/[;}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
assignments.lastIndex = valueStart;
|
||||
const nextField = assignments.exec(message);
|
||||
if (nextField && nextField.index < end) end = nextField.index;
|
||||
}
|
||||
return end;
|
||||
return end;
|
||||
}
|
||||
|
||||
function genericValueEnd(message: string, start: number): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
if (quotedEnd !== undefined) return quotedEnd;
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
|
||||
let end = start;
|
||||
while (end < message.length && !/[\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
return end;
|
||||
if (quotedEnd !== undefined) {
|
||||
return quotedEnd;
|
||||
}
|
||||
|
||||
let end = start;
|
||||
|
||||
while (end < message.length && !/[\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
return end;
|
||||
}
|
||||
|
||||
function authorizationValueEnd(
|
||||
message: string,
|
||||
start: number,
|
||||
query: boolean,
|
||||
): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
if (quotedEnd !== undefined) return quotedEnd;
|
||||
function authorizationValueEnd(message: string, start: number, query: boolean): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
|
||||
if (query) {
|
||||
const queryEnd = message.indexOf('&', start);
|
||||
return queryEnd >= 0 ? queryEnd : message.length;
|
||||
}
|
||||
|
||||
let end = message.length;
|
||||
const structural = message.slice(start).search(/[\r\n}\]]/);
|
||||
if (structural >= 0) end = start + structural;
|
||||
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
const remaining = message.slice(start, end);
|
||||
for (let match = assignments.exec(remaining); match; match = assignments.exec(remaining)) {
|
||||
if (isAuthorizationBoundaryKey(match[3]!)) {
|
||||
end = start + match.index;
|
||||
break;
|
||||
if (quotedEnd !== undefined) {
|
||||
return quotedEnd;
|
||||
}
|
||||
}
|
||||
return end;
|
||||
|
||||
if (query) {
|
||||
const queryEnd = message.indexOf('&', start);
|
||||
return queryEnd >= 0 ? queryEnd : message.length;
|
||||
}
|
||||
|
||||
let end = message.length;
|
||||
const structural = message.slice(start).search(/[\r\n}\]]/);
|
||||
|
||||
if (structural >= 0) {
|
||||
end = start + structural;
|
||||
}
|
||||
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
const remaining = message.slice(start, end);
|
||||
|
||||
for (let match = assignments.exec(remaining); match; match = assignments.exec(remaining)) {
|
||||
if (isAuthorizationBoundaryKey(match[3]!)) {
|
||||
end = start + match.index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return end;
|
||||
}
|
||||
|
||||
/** Redact explicit authentication assignments in ordinary formatted logs. */
|
||||
export function redactLogMessage(message: string): string {
|
||||
let out = '';
|
||||
let cursor = 0;
|
||||
ASSIGNMENT_START.lastIndex = 0;
|
||||
let out = '';
|
||||
let cursor = 0;
|
||||
ASSIGNMENT_START.lastIndex = 0;
|
||||
|
||||
for (let match = ASSIGNMENT_START.exec(message); match; match = ASSIGNMENT_START.exec(message)) {
|
||||
const key = match[3]!;
|
||||
if (!isSensitiveKey(key)) {
|
||||
ASSIGNMENT_START.lastIndex = Math.max(
|
||||
match.index + 1,
|
||||
ASSIGNMENT_START.lastIndex - 1,
|
||||
);
|
||||
continue;
|
||||
for (
|
||||
let match = ASSIGNMENT_START.exec(message);
|
||||
match;
|
||||
match = ASSIGNMENT_START.exec(message)
|
||||
) {
|
||||
const key = match[3]!;
|
||||
|
||||
if (!isSensitiveKey(key)) {
|
||||
ASSIGNMENT_START.lastIndex = Math.max(match.index + 1, ASSIGNMENT_START.lastIndex - 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
const valueStart = ASSIGNMENT_START.lastIndex;
|
||||
const valueEnd = isKeyKind(key, 'authorization')
|
||||
? authorizationValueEnd(message, valueStart, match[1] === '?' || match[1] === '&')
|
||||
: isKeyKind(key, 'cookie')
|
||||
? cookieValueEnd(message, valueStart)
|
||||
: genericValueEnd(message, valueStart);
|
||||
|
||||
out += message.slice(cursor, valueStart) + '***';
|
||||
cursor = valueEnd;
|
||||
ASSIGNMENT_START.lastIndex = valueEnd;
|
||||
}
|
||||
|
||||
const valueStart = ASSIGNMENT_START.lastIndex;
|
||||
const valueEnd = isKeyKind(key, 'authorization')
|
||||
? authorizationValueEnd(
|
||||
message,
|
||||
valueStart,
|
||||
match[1] === '?' || match[1] === '&',
|
||||
)
|
||||
: isKeyKind(key, 'cookie')
|
||||
? cookieValueEnd(message, valueStart)
|
||||
: genericValueEnd(message, valueStart);
|
||||
|
||||
out += message.slice(cursor, valueStart) + '***';
|
||||
cursor = valueEnd;
|
||||
ASSIGNMENT_START.lastIndex = valueEnd;
|
||||
}
|
||||
|
||||
return out + message.slice(cursor);
|
||||
return out + message.slice(cursor);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -280,34 +340,44 @@ export function redactLogMessage(message: string): string {
|
||||
* unredacted so a reproduction contains the complete business input.
|
||||
*/
|
||||
export function renderParamsVerbose(params: unknown): string {
|
||||
const seen = new WeakSet<object>();
|
||||
const seen = new WeakSet<object>();
|
||||
|
||||
const walk = (value: unknown): string => {
|
||||
if (value === null) return 'null';
|
||||
if (value === undefined) return 'undefined';
|
||||
const walk = (value: unknown): string => {
|
||||
if (value === null) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
switch (typeof value) {
|
||||
case 'string':
|
||||
return JSON.stringify(value);
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(value);
|
||||
case 'object': {
|
||||
if (seen.has(value as object)) return '"[circular]"';
|
||||
seen.add(value as object);
|
||||
const out = Array.isArray(value)
|
||||
? `[${value.map((item) => walk(item)).join(',')}]`
|
||||
: `{${Object.entries(value as Record<string, unknown>)
|
||||
.map(([key, item]) => `${key}:${walk(item)}`)
|
||||
.join(',')}}`;
|
||||
seen.delete(value as object);
|
||||
return out;
|
||||
}
|
||||
default:
|
||||
return typeof value;
|
||||
}
|
||||
};
|
||||
if (value === undefined) {
|
||||
return 'undefined';
|
||||
}
|
||||
|
||||
return walk(params);
|
||||
switch (typeof value) {
|
||||
case 'string':
|
||||
return JSON.stringify(value);
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(value);
|
||||
|
||||
case 'object': {
|
||||
if (seen.has(value as object)) {
|
||||
return '"[circular]"';
|
||||
}
|
||||
|
||||
seen.add(value as object);
|
||||
const out = Array.isArray(value)
|
||||
? `[${value.map((item) => walk(item)).join(',')}]`
|
||||
: `{${Object.entries(value as Record<string, unknown>)
|
||||
.map(([key, item]) => `${key}:${walk(item)}`)
|
||||
.join(',')}}`;
|
||||
seen.delete(value as object);
|
||||
return out;
|
||||
}
|
||||
|
||||
default:
|
||||
return typeof value;
|
||||
}
|
||||
};
|
||||
|
||||
return walk(params);
|
||||
}
|
||||
+293
-244
@@ -3,64 +3,64 @@ import { getFileTransport } from './log-file-transport';
|
||||
import { redactLogMessage } from './log-summary';
|
||||
import { sanitizeLogLine } from './log-sanitize';
|
||||
import {
|
||||
currentRequestId,
|
||||
nextRequestId,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
currentRequestId,
|
||||
nextRequestId,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
} from './request-context';
|
||||
|
||||
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
type FileLogLevel = Exclude<LogLevel, 'trace'>;
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
/** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */
|
||||
req?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
id: number;
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
/** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */
|
||||
req?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
|
||||
interface LogOptions {
|
||||
scope: string;
|
||||
uin?: number;
|
||||
/** Free-form meta carried across `.child(...)` calls. Currently only
|
||||
* `uin` is rendered, but the bag is preserved for future fields
|
||||
* (requestId / traceId / etc.). */
|
||||
meta?: Record<string, unknown>;
|
||||
scope: string;
|
||||
uin?: number;
|
||||
/** Free-form meta carried across `.child(...)` calls. Currently only
|
||||
* `uin` is rendered, but the bag is preserved for future fields
|
||||
* (requestId / traceId / etc.). */
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
warn: 30,
|
||||
error: 40,
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
warn: 30,
|
||||
error: 40,
|
||||
};
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
warn: 'WARN',
|
||||
error: 'ERROR',
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
warn: 'WARN',
|
||||
error: 'ERROR',
|
||||
};
|
||||
|
||||
const COLOR_CODE: Record<LogLevel, number> = {
|
||||
trace: 90,
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
warn: 33,
|
||||
error: 31,
|
||||
trace: 90,
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
warn: 33,
|
||||
error: 31,
|
||||
};
|
||||
|
||||
const COLOR_SCOPE = 35;
|
||||
@@ -70,9 +70,10 @@ const MAX_LOG_ENTRIES = 1000;
|
||||
|
||||
/** Trace ring cap — env-tunable since trace is the high-volume stream. */
|
||||
function resolveTraceBufferMax(): number {
|
||||
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
|
||||
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
|
||||
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
|
||||
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
|
||||
}
|
||||
|
||||
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
|
||||
/**
|
||||
@@ -80,32 +81,40 @@ const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
* so the high-throughput trace stream never pays an O(n) shift per overflow.
|
||||
*/
|
||||
class RingBuffer<T> {
|
||||
private readonly buf: (T | undefined)[];
|
||||
private start = 0;
|
||||
private count = 0;
|
||||
constructor(private readonly cap: number) {
|
||||
this.buf = new Array<T | undefined>(cap);
|
||||
}
|
||||
push(item: T): void {
|
||||
const end = (this.start + this.count) % this.cap;
|
||||
this.buf[end] = item;
|
||||
if (this.count < this.cap) this.count += 1;
|
||||
else this.start = (this.start + 1) % this.cap; // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!;
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
return this.recent(this.count);
|
||||
}
|
||||
get size(): number {
|
||||
return this.count;
|
||||
}
|
||||
private readonly buf: (T | undefined)[];
|
||||
private start = 0;
|
||||
private count = 0;
|
||||
constructor(private readonly cap: number) {
|
||||
this.buf = new Array<T | undefined>(cap);
|
||||
}
|
||||
push(item: T): void {
|
||||
const end = (this.start + this.count) % this.cap;
|
||||
this.buf[end] = item;
|
||||
|
||||
if (this.count < this.cap) {
|
||||
this.count += 1;
|
||||
} else {
|
||||
this.start = (this.start + 1) % this.cap;
|
||||
} // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
|
||||
for (let i = 0; i < take; i += 1) {
|
||||
out[i] = this.buf[(first + i) % this.cap]!;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
return this.recent(this.count);
|
||||
}
|
||||
get size(): number {
|
||||
return this.count;
|
||||
}
|
||||
}
|
||||
|
||||
const logRing = new RingBuffer<LogEntry>(MAX_LOG_ENTRIES);
|
||||
@@ -114,25 +123,44 @@ const logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
return raw;
|
||||
}
|
||||
return 'info';
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
|
||||
if (
|
||||
raw === 'trace' ||
|
||||
raw === 'debug' ||
|
||||
raw === 'info' ||
|
||||
raw === 'success' ||
|
||||
raw === 'warn' ||
|
||||
raw === 'error'
|
||||
) {
|
||||
return raw;
|
||||
}
|
||||
|
||||
return 'info';
|
||||
}
|
||||
|
||||
function resolveFileMinLevel(): FileLogLevel {
|
||||
const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
if (raw === undefined || raw.trim() === '') return 'debug';
|
||||
const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === 'debug' || normalized === 'info' || normalized === 'success' ||
|
||||
normalized === 'warn' || normalized === 'error') {
|
||||
return normalized;
|
||||
}
|
||||
throw new TypeError(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
if (raw === undefined || raw.trim() === '') {
|
||||
return 'debug';
|
||||
}
|
||||
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
|
||||
if (
|
||||
normalized === 'debug' ||
|
||||
normalized === 'info' ||
|
||||
normalized === 'success' ||
|
||||
normalized === 'warn' ||
|
||||
normalized === 'error'
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
throw new TypeError(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
}
|
||||
|
||||
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
|
||||
@@ -145,141 +173,158 @@ let currentLevel: LogLevel = resolveMinLevel();
|
||||
const currentFileLevel: FileLogLevel = resolveFileMinLevel();
|
||||
|
||||
function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
function shouldLogToFile(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentFileLevel];
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentFileLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
export const LOG_LEVELS: readonly LogLevel[] = [
|
||||
'trace',
|
||||
'debug',
|
||||
'info',
|
||||
'success',
|
||||
'warn',
|
||||
'error',
|
||||
];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
return currentLevel;
|
||||
}
|
||||
|
||||
|
||||
// Change the console / subscriber level at runtime.
|
||||
// Invalid input is a no-op (returns false).
|
||||
// Does not affect the file transport log level.
|
||||
|
||||
export function setLogLevel(level: string): boolean {
|
||||
const lower = String(level).toLowerCase();
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
|
||||
currentLevel = lower as LogLevel;
|
||||
return true;
|
||||
const lower = String(level).toLowerCase();
|
||||
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
currentLevel = lower as LogLevel;
|
||||
return true;
|
||||
}
|
||||
|
||||
function useColor(): boolean {
|
||||
if (process.env.NO_COLOR === '1') return false;
|
||||
return Boolean(process.stdout.isTTY);
|
||||
if (process.env.NO_COLOR === '1') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Boolean(process.stdout.isTTY);
|
||||
}
|
||||
|
||||
function ansi(code: number, text: string): string {
|
||||
return `\x1b[${code}m${text}${COLOR_RESET}`;
|
||||
return `\x1b[${code}m${text}${COLOR_RESET}`;
|
||||
}
|
||||
|
||||
function currentTime(): string {
|
||||
const d = new Date();
|
||||
const hh = String(d.getHours()).padStart(2, '0');
|
||||
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||
const ss = String(d.getSeconds()).padStart(2, '0');
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
const d = new Date();
|
||||
const hh = String(d.getHours()).padStart(2, '0');
|
||||
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||
const ss = String(d.getSeconds()).padStart(2, '0');
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function render(level: LogLevel, options: LogOptions, message: string, reqId?: number): string {
|
||||
const ts = currentTime();
|
||||
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
|
||||
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
|
||||
const reqTag = reqId !== undefined ? `[req#${reqId}]` : '';
|
||||
const ts = currentTime();
|
||||
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
|
||||
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
|
||||
const reqTag = reqId !== undefined ? `[req#${reqId}]` : '';
|
||||
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
|
||||
}
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
const cLabel = ansi(COLOR_CODE[level], label);
|
||||
// Pad first, then color only the visible tag so escape codes don't eat
|
||||
// into the alignment width.
|
||||
const cUin = uinTag
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
const cLabel = ansi(COLOR_CODE[level], label);
|
||||
// Pad first, then color only the visible tag so escape codes don't eat
|
||||
// into the alignment width.
|
||||
const cUin = uinTag
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
|
||||
}
|
||||
|
||||
function emit(
|
||||
level: LogLevel,
|
||||
options: LogOptions,
|
||||
args: unknown[],
|
||||
): void {
|
||||
// Console / subscriber and file filters are independent. If no destination
|
||||
// accepts the record, stop before formatting or building a LogEntry.
|
||||
const passesConsole = shouldLog(level);
|
||||
const passesFile = level !== 'trace'
|
||||
&& shouldLogToFile(level);
|
||||
if (!passesConsole && !passesFile) return;
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
// Console / subscriber and file filters are independent. If no destination
|
||||
// accepts the record, stop before formatting or building a LogEntry.
|
||||
const passesConsole = shouldLog(level);
|
||||
const passesFile = level !== 'trace' && shouldLogToFile(level);
|
||||
|
||||
// `trace` is the high-volume full-chain diagnostic stream, intentionally
|
||||
// excluded from disk to avoid I/O saturation. When console is not dialed
|
||||
// to trace, the early return below skips format/render/disk entirely.
|
||||
// Set SNOWLUMA_LOG_LEVEL=trace to inspect trace output in console/memory;
|
||||
// trace never reaches disk regardless.
|
||||
if (level === 'trace' && !passesConsole) return;
|
||||
|
||||
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
|
||||
// (and its expensive deep render) only runs now that trace is confirmed live.
|
||||
let realArgs = args;
|
||||
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
|
||||
realArgs = (args[0] as () => unknown[])();
|
||||
}
|
||||
|
||||
const reqId = currentRequestId();
|
||||
const formattedMessage = format(...realArgs);
|
||||
const message = level === 'trace'
|
||||
? formattedMessage
|
||||
: redactLogMessage(formattedMessage);
|
||||
const line = render(level, options, message, reqId);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line: sanitizeLogLine(line),
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
for (const subscriber of logSubscribers) subscriber(entry);
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
|
||||
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const consoleLine = line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n';
|
||||
try {
|
||||
stream.write(consoleLine);
|
||||
} catch {
|
||||
// A full Docker json-file log volume can make stdout/stderr throw.
|
||||
// Logging must not take down message handling or the WebUI.
|
||||
if (!passesConsole && !passesFile) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL,
|
||||
// default debug). `trace` is memory / WebUI only (omitted here to avoid huge
|
||||
// on-disk volume). ANSI stripping happens inside the transport. UIN routes
|
||||
// the line to its per-account sub-file in addition to the shared one.
|
||||
if (passesFile) {
|
||||
getFileTransport().write(line, options.uin);
|
||||
}
|
||||
// `trace` is the high-volume full-chain diagnostic stream, intentionally
|
||||
// excluded from disk to avoid I/O saturation. When console is not dialed
|
||||
// to trace, the early return below skips format/render/disk entirely.
|
||||
// Set SNOWLUMA_LOG_LEVEL=trace to inspect trace output in console/memory;
|
||||
// trace never reaches disk regardless.
|
||||
if (level === 'trace' && !passesConsole) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
|
||||
// (and its expensive deep render) only runs now that trace is confirmed live.
|
||||
let realArgs = args;
|
||||
|
||||
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
|
||||
realArgs = (args[0] as () => unknown[])();
|
||||
}
|
||||
|
||||
const reqId = currentRequestId();
|
||||
const formattedMessage = format(...realArgs);
|
||||
const message = level === 'trace' ? formattedMessage : redactLogMessage(formattedMessage);
|
||||
const line = render(level, options, message, reqId);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line: sanitizeLogLine(line),
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
|
||||
for (const subscriber of logSubscribers) {
|
||||
subscriber(entry);
|
||||
}
|
||||
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
|
||||
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const consoleLine = line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n';
|
||||
|
||||
try {
|
||||
stream.write(consoleLine);
|
||||
} catch {
|
||||
// A full Docker json-file log volume can make stdout/stderr throw.
|
||||
// Logging must not take down message handling or the WebUI.
|
||||
}
|
||||
}
|
||||
|
||||
// File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL,
|
||||
// default debug). `trace` is memory / WebUI only (omitted here to avoid huge
|
||||
// on-disk volume). ANSI stripping happens inside the transport. UIN routes
|
||||
// the line to its per-account sub-file in addition to the shared one.
|
||||
if (passesFile) {
|
||||
getFileTransport().write(line, options.uin);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -289,97 +334,101 @@ function emit(
|
||||
* has finalized the write.
|
||||
*/
|
||||
export function closeLogger(): Promise<void> {
|
||||
return getFileTransport().close();
|
||||
return getFileTransport().close();
|
||||
}
|
||||
|
||||
function mergeLogRings(): LogEntry[] {
|
||||
return traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
return traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
}
|
||||
|
||||
export function getLogSnapshot(): LogEntry[] {
|
||||
return mergeLogRings();
|
||||
return mergeLogRings();
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.trunc(limit));
|
||||
return mergeLogRings().slice(-n);
|
||||
const n = Math.max(1, Math.trunc(limit));
|
||||
return mergeLogRings().slice(-n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
logSubscribers.add(callback);
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
logSubscribers.add(callback);
|
||||
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
/**
|
||||
* High-volume, memory-only diagnostic level (never written to disk). Pass a
|
||||
* lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the
|
||||
* arguments (and any costly rendering) are built only when trace is active.
|
||||
* A plain `trace('msg', x)` works too but evaluates its args eagerly.
|
||||
*/
|
||||
trace: (...args: unknown[]) => void;
|
||||
debug: (...args: unknown[]) => void;
|
||||
info: (...args: unknown[]) => void;
|
||||
success: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Derive a new logger that inherits this one's scope and carries
|
||||
* additional metadata. Currently `uin` is the only key with rendering
|
||||
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
|
||||
* other keys are preserved on the options bag for forward compat.
|
||||
*/
|
||||
child: (meta: { uin?: number;[k: string]: unknown }) => Logger;
|
||||
/**
|
||||
* High-volume, memory-only diagnostic level (never written to disk). Pass a
|
||||
* lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the
|
||||
* arguments (and any costly rendering) are built only when trace is active.
|
||||
* A plain `trace('msg', x)` works too but evaluates its args eagerly.
|
||||
*/
|
||||
trace: (...args: unknown[]) => void;
|
||||
debug: (...args: unknown[]) => void;
|
||||
info: (...args: unknown[]) => void;
|
||||
success: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Derive a new logger that inherits this one's scope and carries
|
||||
* additional metadata. Currently `uin` is the only key with rendering
|
||||
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
|
||||
* other keys are preserved on the options bag for forward compat.
|
||||
*/
|
||||
child: (meta: { uin?: number; [k: string]: unknown }) => Logger;
|
||||
}
|
||||
|
||||
function makeLogger(opts: LogOptions): Logger {
|
||||
return {
|
||||
trace: (...args: unknown[]) => emit('trace', opts, args),
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
warn: (...args: unknown[]) => emit('warn', opts, args),
|
||||
error: (...args: unknown[]) => emit('error', opts, args),
|
||||
child: (meta) => {
|
||||
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
|
||||
return makeLogger({
|
||||
scope: opts.scope,
|
||||
uin: nextUin,
|
||||
meta: { ...(opts.meta ?? {}), ...meta },
|
||||
});
|
||||
},
|
||||
};
|
||||
return {
|
||||
trace: (...args: unknown[]) => emit('trace', opts, args),
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
warn: (...args: unknown[]) => emit('warn', opts, args),
|
||||
error: (...args: unknown[]) => emit('error', opts, args),
|
||||
child: (meta) => {
|
||||
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
|
||||
return makeLogger({
|
||||
scope: opts.scope,
|
||||
uin: nextUin,
|
||||
meta: { ...(opts.meta ?? {}), ...meta },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createLogger(scope: string): Logger {
|
||||
return makeLogger({ scope });
|
||||
return makeLogger({ scope });
|
||||
}
|
||||
|
||||
export function renderTraceBytes(body: Uint8Array): string {
|
||||
return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('hex');
|
||||
return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('hex');
|
||||
}
|
||||
|
||||
export function runWithTraceRequest<T>(fn: () => T): T {
|
||||
if (currentRequestId() !== undefined || currentLevel !== 'trace') return fn();
|
||||
return runWithRequestId(nextRequestId(), fn);
|
||||
if (currentRequestId() !== undefined || currentLevel !== 'trace') {
|
||||
return fn();
|
||||
}
|
||||
|
||||
return runWithRequestId(nextRequestId(), fn);
|
||||
}
|
||||
|
||||
export function logInitialWebuiCredentials(password: string): void {
|
||||
// This is deliberately not a LogEntry: application logs can be retained on
|
||||
// disk, exported through WebUI, and delivered to subscribers. First-run
|
||||
// credentials must only cross the process terminal boundary.
|
||||
const line = render(
|
||||
'info',
|
||||
{ scope: 'WebUI' },
|
||||
format('initial credentials: user=admin password=%s', password),
|
||||
);
|
||||
// Keep the same terminal control-character policy as regular console logs.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
process.stdout.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
// This is deliberately not a LogEntry: application logs can be retained on
|
||||
// disk, exported through WebUI, and delivered to subscribers. First-run
|
||||
// credentials must only cross the process terminal boundary.
|
||||
const line = render(
|
||||
'info',
|
||||
{ scope: 'WebUI' },
|
||||
format('initial credentials: user=admin password=%s', password),
|
||||
);
|
||||
// Keep the same terminal control-character policy as regular console logs.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
process.stdout.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
// Request-correlation primitives remain available for callers that already own
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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}`;
|
||||
@@ -1,11 +1,11 @@
|
||||
export interface SendPacketResult {
|
||||
success: boolean;
|
||||
gotResponse: boolean;
|
||||
errorCode: number;
|
||||
errorMessage: string;
|
||||
responseData: Buffer | null;
|
||||
success: boolean;
|
||||
gotResponse: boolean;
|
||||
errorCode: number;
|
||||
errorMessage: string;
|
||||
responseData: Buffer | null;
|
||||
}
|
||||
|
||||
export interface PacketSender {
|
||||
sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise<SendPacketResult>;
|
||||
sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise<SendPacketResult>;
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
export interface PacketInfo {
|
||||
pid: number;
|
||||
uin: string;
|
||||
packetType?: number;
|
||||
serviceCmd: string;
|
||||
seqId: number;
|
||||
retCode: number;
|
||||
fromClient: boolean;
|
||||
body: Uint8Array;
|
||||
pid: number;
|
||||
uin: string;
|
||||
packetType?: number;
|
||||
serviceCmd: string;
|
||||
seqId: number;
|
||||
retCode: number;
|
||||
fromClient: boolean;
|
||||
body: Uint8Array;
|
||||
}
|
||||
export type PacketSink = (packet: PacketInfo) => void;
|
||||
@@ -1,7 +1,7 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
|
||||
interface RequestStore {
|
||||
id: number;
|
||||
id: number;
|
||||
}
|
||||
|
||||
const storage = new AsyncLocalStorage<RequestStore | undefined>();
|
||||
@@ -13,9 +13,13 @@ let counter = 0;
|
||||
* unambiguous.
|
||||
*/
|
||||
export function nextRequestId(): number {
|
||||
counter = (counter + 1) >>> 0;
|
||||
if (counter === 0) counter = 1;
|
||||
return counter;
|
||||
counter = (counter + 1) >>> 0;
|
||||
|
||||
if (counter === 0) {
|
||||
counter = 1;
|
||||
}
|
||||
|
||||
return counter;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -26,15 +30,15 @@ export function nextRequestId(): number {
|
||||
* journey (entry → outbound packets → exit) under one `[req#N]` tag.
|
||||
*/
|
||||
export function runWithRequestId<T>(id: number, fn: () => T): T {
|
||||
return storage.run({ id }, fn);
|
||||
return storage.run({ id }, fn);
|
||||
}
|
||||
|
||||
/** Run `fn` without inheriting an ambient request id. */
|
||||
export function runWithoutRequestContext<T>(fn: () => T): T {
|
||||
return storage.run(undefined, fn);
|
||||
return storage.run(undefined, fn);
|
||||
}
|
||||
|
||||
/** The request id bound to the current async context, or undefined outside one. */
|
||||
export function currentRequestId(): number | undefined {
|
||||
return storage.getStore()?.id;
|
||||
return storage.getStore()?.id;
|
||||
}
|
||||
+296
-203
@@ -1,27 +1,28 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { isObject } from './coerce';
|
||||
|
||||
export interface RuntimeConfig {
|
||||
webuiPort?: number;
|
||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
* Defaults to false; the Docker image flips it on in supervisord.conf. */
|
||||
hookAutoLoad?: boolean;
|
||||
/** WebUI listener bind address. '127.0.0.1' = localhost-only (default),
|
||||
* '0.0.0.0' = all IPv4 interfaces. Listener-level: change needs a restart. */
|
||||
webuiHost?: string;
|
||||
/** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this
|
||||
* only flips serving on/off. Listener-level: change needs a restart. */
|
||||
webuiTls?: { enabled?: boolean };
|
||||
/** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY),
|
||||
* consumed by the WebUI's client-ip resolver. '' = trust nobody. */
|
||||
trustProxy?: string;
|
||||
/** Aggregate cap for every managed file below the log root. */
|
||||
logMaxTotalMb?: number;
|
||||
/** Calendar-day retention. Zero disables date-based deletion. */
|
||||
logRetainDays?: number;
|
||||
/** Duplicate UIN-scoped lines into logs/<uin>/ in addition to the shared log. */
|
||||
logPerUin?: boolean;
|
||||
webuiPort?: number;
|
||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
* Defaults to false; the Docker image flips it on in supervisord.conf. */
|
||||
hookAutoLoad?: boolean;
|
||||
/** WebUI listener bind address. '127.0.0.1' = localhost-only (default),
|
||||
* '0.0.0.0' = all IPv4 interfaces. Listener-level: change needs a restart. */
|
||||
webuiHost?: string;
|
||||
/** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this
|
||||
* only flips serving on/off. Listener-level: change needs a restart. */
|
||||
webuiTls?: { enabled?: boolean };
|
||||
/** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY),
|
||||
* consumed by the WebUI's client-ip resolver. '' = trust nobody. */
|
||||
trustProxy?: string;
|
||||
/** Aggregate cap for every managed file below the log root. */
|
||||
logMaxTotalMb?: number;
|
||||
/** Calendar-day retention. Zero disables date-based deletion. */
|
||||
logRetainDays?: number;
|
||||
/** Duplicate UIN-scoped lines into logs/<uin>/ in addition to the shared log. */
|
||||
logPerUin?: boolean;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
@@ -33,38 +34,38 @@ export const DEFAULT_LOG_MAX_TOTAL_MB = 1024;
|
||||
export const DEFAULT_LOG_RETAIN_DAYS = 7;
|
||||
export const DEFAULT_LOG_PER_UIN = false;
|
||||
export const MAX_LOG_TOTAL_MB = Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024));
|
||||
export const MAX_LOG_RETAIN_DAYS = Math.floor(
|
||||
Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000),
|
||||
);
|
||||
export const MAX_LOG_RETAIN_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000));
|
||||
|
||||
/**
|
||||
* Pure on-disk-object → typed config normalization (defaults + validation,
|
||||
* no fs / no env). Exported for testing; `loadRuntimeConfig` wraps it.
|
||||
*/
|
||||
export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
const obj = isObject(parsed) ? parsed : {};
|
||||
return {
|
||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||
webuiHost: normalizeHost(obj.webuiHost),
|
||||
webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false },
|
||||
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
|
||||
logMaxTotalMb: normalizeRequiredInteger(
|
||||
obj.logMaxTotalMb,
|
||||
DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'logMaxTotalMb',
|
||||
),
|
||||
logRetainDays: normalizeRequiredInteger(
|
||||
obj.logRetainDays,
|
||||
DEFAULT_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'logRetainDays',
|
||||
),
|
||||
logPerUin: normalizeRequiredBool(obj.logPerUin, DEFAULT_LOG_PER_UIN, 'logPerUin'),
|
||||
};
|
||||
const obj = isObject(parsed) ? parsed : {};
|
||||
return {
|
||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||
webuiHost: normalizeHost(obj.webuiHost),
|
||||
webuiTls: {
|
||||
enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false,
|
||||
},
|
||||
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
|
||||
logMaxTotalMb: normalizeRequiredInteger(
|
||||
obj.logMaxTotalMb,
|
||||
DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'logMaxTotalMb',
|
||||
),
|
||||
logRetainDays: normalizeRequiredInteger(
|
||||
obj.logRetainDays,
|
||||
DEFAULT_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'logRetainDays',
|
||||
),
|
||||
logPerUin: normalizeRequiredBool(obj.logPerUin, DEFAULT_LOG_PER_UIN, 'logPerUin'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,61 +74,79 @@ export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
* rewriting the file). Absent vars produce no key.
|
||||
*/
|
||||
export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<RuntimeConfig> {
|
||||
const out: Partial<RuntimeConfig> = {};
|
||||
const out: Partial<RuntimeConfig> = {};
|
||||
|
||||
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
|
||||
if (port !== undefined) out.webuiPort = port;
|
||||
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
|
||||
|
||||
const host = env.SNOWLUMA_WEBUI_HOST;
|
||||
if (typeof host === 'string' && host.trim()) out.webuiHost = host.trim();
|
||||
if (port !== undefined) {
|
||||
out.webuiPort = port;
|
||||
}
|
||||
|
||||
// Present-but-"0"/"off" is a deliberate override (trust nobody), distinct
|
||||
// from "absent" — so gate on key presence, not truthiness.
|
||||
const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY;
|
||||
if (typeof tp === 'string') out.trustProxy = tp;
|
||||
const host = env.SNOWLUMA_WEBUI_HOST;
|
||||
|
||||
const logMaxTotalMb = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'SNOWLUMA_LOG_MAX_TOTAL_MB',
|
||||
);
|
||||
if (logMaxTotalMb !== undefined) out.logMaxTotalMb = logMaxTotalMb;
|
||||
if (typeof host === 'string' && host.trim()) {
|
||||
out.webuiHost = host.trim();
|
||||
}
|
||||
|
||||
const logRetainDays = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
);
|
||||
if (logRetainDays !== undefined) out.logRetainDays = logRetainDays;
|
||||
// Present-but-"0"/"off" is a deliberate override (trust nobody), distinct
|
||||
// from "absent" — so gate on key presence, not truthiness.
|
||||
const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY;
|
||||
|
||||
const logPerUin = parseRequiredBoolEnv(
|
||||
env.SNOWLUMA_LOG_PER_UIN,
|
||||
'SNOWLUMA_LOG_PER_UIN',
|
||||
);
|
||||
if (logPerUin !== undefined) out.logPerUin = logPerUin;
|
||||
if (typeof tp === 'string') {
|
||||
out.trustProxy = tp;
|
||||
}
|
||||
|
||||
const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS');
|
||||
if (webuiTls !== undefined) out.webuiTls = { enabled: webuiTls };
|
||||
const logMaxTotalMb = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'SNOWLUMA_LOG_MAX_TOTAL_MB',
|
||||
);
|
||||
|
||||
return out;
|
||||
if (logMaxTotalMb !== undefined) {
|
||||
out.logMaxTotalMb = logMaxTotalMb;
|
||||
}
|
||||
|
||||
const logRetainDays = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
);
|
||||
|
||||
if (logRetainDays !== undefined) {
|
||||
out.logRetainDays = logRetainDays;
|
||||
}
|
||||
|
||||
const logPerUin = parseRequiredBoolEnv(env.SNOWLUMA_LOG_PER_UIN, 'SNOWLUMA_LOG_PER_UIN');
|
||||
|
||||
if (logPerUin !== undefined) {
|
||||
out.logPerUin = logPerUin;
|
||||
}
|
||||
|
||||
const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS');
|
||||
|
||||
if (webuiTls !== undefined) {
|
||||
out.webuiTls = { enabled: webuiTls };
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
|
||||
const parsed = tryLoadRuntimeConfig();
|
||||
const normalized = normalizeRuntimeConfig(parsed ?? {});
|
||||
const parsed = tryLoadRuntimeConfig();
|
||||
const normalized = normalizeRuntimeConfig(parsed ?? {});
|
||||
|
||||
// Persist when the file is absent or when normalization changed/backfilled
|
||||
// anything (e.g. an older runtime.json lacking webuiHost/webuiTls).
|
||||
if (parsed === null || !sameRuntimeConfig(parsed, normalized)) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
// Persist when the file is absent or when normalization changed/backfilled
|
||||
// anything (e.g. an older runtime.json lacking webuiHost/webuiTls).
|
||||
if (parsed === null || !sameRuntimeConfig(parsed, normalized)) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
|
||||
// Env overrides apply in-memory only — never written back to disk.
|
||||
return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) };
|
||||
// Env overrides apply in-memory only — never written back to disk.
|
||||
return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -135,7 +154,7 @@ export function loadRuntimeConfig(): RuntimeConfig {
|
||||
* settings panel's GET — shows what's actually saved/editable on disk.
|
||||
*/
|
||||
export function readRuntimeConfig(): RuntimeConfig {
|
||||
return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -144,165 +163,239 @@ export function readRuntimeConfig(): RuntimeConfig {
|
||||
* into runtime.json. Returns the new persisted config (without env overrides).
|
||||
*/
|
||||
export function updateRuntimeConfig(patch: Partial<RuntimeConfig>): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
const onDisk = normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
const next = normalizeRuntimeConfig({ ...onDisk, ...patch });
|
||||
saveRuntimeConfig(next);
|
||||
return next;
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
const onDisk = normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
const next = normalizeRuntimeConfig({ ...onDisk, ...patch });
|
||||
saveRuntimeConfig(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): Record<string, unknown> | null {
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`;
|
||||
try {
|
||||
fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH);
|
||||
} catch (error) {
|
||||
const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`;
|
||||
|
||||
try {
|
||||
fs.unlinkSync(temporaryPath);
|
||||
} catch (cleanupError) {
|
||||
if (!isErrnoCode(cleanupError, 'ENOENT')) {
|
||||
throw new AggregateError(
|
||||
[error, cleanupError],
|
||||
'failed to persist runtime config and remove its temporary file',
|
||||
);
|
||||
}
|
||||
fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH);
|
||||
} catch (error) {
|
||||
try {
|
||||
fs.unlinkSync(temporaryPath);
|
||||
} catch (cleanupError) {
|
||||
if (!isErrnoCode(cleanupError, 'ENOENT')) {
|
||||
throw new AggregateError(
|
||||
[error, cleanupError],
|
||||
'failed to persist runtime config and remove its temporary file',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when the raw on-disk object already matches the normalized config
|
||||
* on every known field (so we can skip a needless rewrite). */
|
||||
function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): boolean {
|
||||
const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined;
|
||||
return (
|
||||
parsed.webuiPort === n.webuiPort
|
||||
&& parsed.hookAutoLoad === n.hookAutoLoad
|
||||
&& parsed.webuiHost === n.webuiHost
|
||||
&& parsedTls === n.webuiTls?.enabled
|
||||
&& parsed.trustProxy === n.trustProxy
|
||||
&& parsed.logMaxTotalMb === n.logMaxTotalMb
|
||||
&& parsed.logRetainDays === n.logRetainDays
|
||||
&& parsed.logPerUin === n.logPerUin
|
||||
);
|
||||
const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined;
|
||||
return (
|
||||
parsed.webuiPort === n.webuiPort &&
|
||||
parsed.hookAutoLoad === n.hookAutoLoad &&
|
||||
parsed.webuiHost === n.webuiHost &&
|
||||
parsedTls === n.webuiTls?.enabled &&
|
||||
parsed.trustProxy === n.trustProxy &&
|
||||
parsed.logMaxTotalMb === n.logMaxTotalMb &&
|
||||
parsed.logRetainDays === n.logRetainDays &&
|
||||
parsed.logPerUin === n.logPerUin
|
||||
);
|
||||
}
|
||||
|
||||
function parsePortString(raw: unknown): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
return port;
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const n = Number(raw.trim());
|
||||
|
||||
if (!Number.isFinite(n)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const port = Math.trunc(n);
|
||||
|
||||
if (port <= 0 || port > 65535) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
function normalizeHost(value: unknown): string {
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
return DEFAULT_WEBUI_HOST;
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
return DEFAULT_WEBUI_HOST;
|
||||
}
|
||||
|
||||
function normalizePort(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const n = Math.trunc(value);
|
||||
if (n > 0 && n <= 65535) return n;
|
||||
return fallback;
|
||||
}
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
if (Number.isFinite(n)) {
|
||||
const port = Math.trunc(n);
|
||||
if (port > 0 && port <= 65535) return port;
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const n = Math.trunc(value);
|
||||
|
||||
if (n > 0 && n <= 65535) {
|
||||
return n;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
|
||||
if (Number.isFinite(n)) {
|
||||
const port = Math.trunc(n);
|
||||
|
||||
if (port > 0 && port <= 65535) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function normalizeRequiredInteger(
|
||||
value: unknown,
|
||||
fallback: number,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
value: unknown,
|
||||
fallback: number,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
): number {
|
||||
if (value === undefined) return fallback;
|
||||
const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
|
||||
if (
|
||||
typeof n === 'number'
|
||||
&& Number.isSafeInteger(n)
|
||||
&& n >= min
|
||||
&& n <= max
|
||||
) {
|
||||
return n;
|
||||
}
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
if (value === undefined) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
|
||||
|
||||
if (typeof n === 'number' && Number.isSafeInteger(n) && n >= min && n <= max) {
|
||||
return n;
|
||||
}
|
||||
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
}
|
||||
|
||||
function normalizeRequiredBool(
|
||||
value: unknown,
|
||||
fallback: boolean,
|
||||
field: string,
|
||||
): boolean {
|
||||
if (value === undefined) return fallback;
|
||||
const parsed = parseBoolValue(value);
|
||||
if (parsed !== undefined) return parsed;
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
function normalizeRequiredBool(value: unknown, fallback: boolean, field: string): boolean {
|
||||
if (value === undefined) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const parsed = parseBoolValue(value);
|
||||
|
||||
if (parsed !== undefined) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
}
|
||||
|
||||
function normalizeBool(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'number') return value !== 0;
|
||||
if (typeof value === 'string') {
|
||||
const v = value.trim().toLowerCase();
|
||||
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;
|
||||
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') return false;
|
||||
}
|
||||
return fallback;
|
||||
if (typeof value === 'boolean') {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
return value !== 0;
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const v = value.trim().toLowerCase();
|
||||
|
||||
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function parseRequiredIntegerEnv(
|
||||
raw: unknown,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
raw: unknown,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (Number.isSafeInteger(n) && n >= min && n <= max) return n;
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const n = Number(raw.trim());
|
||||
|
||||
if (Number.isSafeInteger(n) && n >= min && n <= max) {
|
||||
return n;
|
||||
}
|
||||
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
}
|
||||
|
||||
function parseRequiredBoolEnv(raw: unknown, field: string): boolean | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const parsed = parseBoolValue(raw);
|
||||
if (parsed !== undefined) return parsed;
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const parsed = parseBoolValue(raw);
|
||||
|
||||
if (parsed !== undefined) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
}
|
||||
|
||||
function parseBoolValue(raw: unknown): boolean | undefined {
|
||||
if (typeof raw === 'boolean') return raw;
|
||||
if (raw === 1) return true;
|
||||
if (raw === 0) return false;
|
||||
if (typeof raw !== 'string') return undefined;
|
||||
const value = raw.trim().toLowerCase();
|
||||
if (value === 'true' || value === '1' || value === 'yes' || value === 'on') return true;
|
||||
if (value === 'false' || value === '0' || value === 'no' || value === 'off') return false;
|
||||
return undefined;
|
||||
}
|
||||
if (typeof raw === 'boolean') {
|
||||
return raw;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
if (raw === 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (raw === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof raw !== 'string') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const value = raw.trim().toLowerCase();
|
||||
|
||||
if (value === 'true' || value === '1' || value === 'yes' || value === 'on') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value === 'false' || value === '0' || value === 'no' || value === 'off') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isErrnoCode(error: unknown, code: string): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === code;
|
||||
return error instanceof Error && 'code' in error && error.code === code;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1,93 +1,94 @@
|
||||
/**
|
||||
* 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. */
|
||||
ttlMs: number;
|
||||
/** Load the value for a key. Rejections propagate and are never cached. */
|
||||
load: (key: K) => Promise<V>;
|
||||
/**
|
||||
* Decide whether a resolved value should be cached. Default: always.
|
||||
* Return `false` to leave an entry uncached (e.g. an error-shaped result the
|
||||
* next call should retry) while still de-duping concurrent in-flight callers.
|
||||
*/
|
||||
shouldCache?: (value: V) => boolean;
|
||||
/** Clock, injectable for tests. Defaults to `Date.now`. */
|
||||
now?: () => number;
|
||||
/** Freshness window in ms. A cached entry older than this is reloaded. */
|
||||
ttlMs: number;
|
||||
/** Load the value for a key. Rejections propagate and are never cached. */
|
||||
load: (key: K) => Promise<V>;
|
||||
/**
|
||||
* Decide whether a resolved value should be cached. Default: always.
|
||||
* Return `false` to leave an entry uncached (e.g. an error-shaped result the
|
||||
* next call should retry) while still de-duping concurrent in-flight callers.
|
||||
*/
|
||||
shouldCache?: (value: V) => boolean;
|
||||
/** Clock, injectable for tests. Defaults to `Date.now`. */
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export class SingleFlightCache<K, V> {
|
||||
private readonly ttlMs: number;
|
||||
private readonly load: (key: K) => Promise<V>;
|
||||
private readonly shouldCache: (value: V) => boolean;
|
||||
private readonly now: () => number;
|
||||
private readonly fresh = new Map<K, { at: number; value: V }>();
|
||||
private readonly inflight = new Map<K, Promise<V>>();
|
||||
private readonly ttlMs: number;
|
||||
private readonly load: (key: K) => Promise<V>;
|
||||
private readonly shouldCache: (value: V) => boolean;
|
||||
private readonly now: () => number;
|
||||
private readonly fresh = new Map<K, { at: number; value: V }>();
|
||||
private readonly inflight = new Map<K, Promise<V>>();
|
||||
|
||||
constructor(opts: SingleFlightCacheOptions<K, V>) {
|
||||
this.ttlMs = opts.ttlMs;
|
||||
this.load = opts.load;
|
||||
this.shouldCache = opts.shouldCache ?? (() => true);
|
||||
this.now = opts.now ?? Date.now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value for `key`.
|
||||
*
|
||||
* - Returns a fresh cached value when the last load was within `ttlMs`.
|
||||
* - Otherwise de-dupes concurrent callers onto a single `load()` and caches
|
||||
* the result (subject to `shouldCache`). A rejected `load` propagates to
|
||||
* every joined caller, clears the in-flight slot, and is not cached.
|
||||
* - `force` bypasses the freshness check but still joins an in-flight load
|
||||
* rather than starting a second one.
|
||||
*/
|
||||
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
|
||||
if (!opts.force) {
|
||||
const hit = this.fresh.get(key);
|
||||
if (hit && this.now() - hit.at < this.ttlMs) return Promise.resolve(hit.value);
|
||||
constructor(opts: SingleFlightCacheOptions<K, V>) {
|
||||
this.ttlMs = opts.ttlMs;
|
||||
this.load = opts.load;
|
||||
this.shouldCache = opts.shouldCache ?? (() => true);
|
||||
this.now = opts.now ?? Date.now;
|
||||
}
|
||||
const existing = this.inflight.get(key);
|
||||
if (existing) return existing;
|
||||
const task = (async () => {
|
||||
try {
|
||||
const value = await this.load(key);
|
||||
if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value });
|
||||
return value;
|
||||
} finally {
|
||||
|
||||
/**
|
||||
* Get the value for `key`.
|
||||
*
|
||||
* - Returns a fresh cached value when the last load was within `ttlMs`.
|
||||
* - Otherwise de-dupes concurrent callers onto a single `load()` and caches
|
||||
* the result (subject to `shouldCache`). A rejected `load` propagates to
|
||||
* every joined caller, clears the in-flight slot, and is not cached.
|
||||
* - `force` bypasses the freshness check but still joins an in-flight load
|
||||
* rather than starting a second one.
|
||||
*/
|
||||
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
|
||||
if (!opts.force) {
|
||||
const hit = this.fresh.get(key);
|
||||
|
||||
if (hit && this.now() - hit.at < this.ttlMs) {
|
||||
return Promise.resolve(hit.value);
|
||||
}
|
||||
}
|
||||
|
||||
const existing = this.inflight.get(key);
|
||||
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const load = async (): Promise<V> => {
|
||||
const value = await this.load(key);
|
||||
|
||||
if (this.inflight.get(key) === task && this.shouldCache(value)) {
|
||||
this.fresh.set(key, { at: this.now(), value });
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
|
||||
const task = load().finally(() => {
|
||||
if (this.inflight.get(key) === task) {
|
||||
this.inflight.delete(key);
|
||||
}
|
||||
});
|
||||
this.inflight.set(key, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
/** Detach the entry and its pending load; existing callers still settle. */
|
||||
invalidate(key: K): void {
|
||||
this.fresh.delete(key);
|
||||
this.inflight.delete(key);
|
||||
}
|
||||
})();
|
||||
this.inflight.set(key, task);
|
||||
return task;
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop a cached entry. Does not abort an in-flight load. */
|
||||
invalidate(key: K): void {
|
||||
this.fresh.delete(key);
|
||||
}
|
||||
|
||||
/** Drop all cached entries. Does not abort in-flight loads. */
|
||||
clear(): void {
|
||||
this.fresh.clear();
|
||||
}
|
||||
/** Detach all entries and pending loads without aborting existing callers. */
|
||||
clear(): void {
|
||||
this.fresh.clear();
|
||||
this.inflight.clear();
|
||||
}
|
||||
}
|
||||
|
||||
export function createSingleFlightCache<K, V>(
|
||||
opts: SingleFlightCacheOptions<K, V>,
|
||||
opts: SingleFlightCacheOptions<K, V>,
|
||||
): SingleFlightCache<K, V> {
|
||||
return new SingleFlightCache(opts);
|
||||
return new SingleFlightCache(opts);
|
||||
}
|
||||
@@ -7,5 +7,5 @@
|
||||
// Callers rely on a `true` result guaranteeing a BigInt()-safe pure-digit
|
||||
// string. Keep that contract if the pattern ever changes.
|
||||
export function isRealUin(uin: string): boolean {
|
||||
return /^\d{5,10}$/.test(uin);
|
||||
return /^\d{5,10}$/.test(uin);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import manifest from '../../../package.json' with { type: 'json' };
|
||||
|
||||
export const APP_VERSION = manifest.version;
|
||||
@@ -1,28 +1,32 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
ACCESS_TOKEN_MIN_LENGTH,
|
||||
ACCESS_TOKEN_MIN_SCORE,
|
||||
assessAccessToken,
|
||||
ACCESS_TOKEN_MIN_LENGTH,
|
||||
ACCESS_TOKEN_MIN_SCORE,
|
||||
assessAccessToken,
|
||||
} from '../src/access-token';
|
||||
|
||||
describe('access token strength', () => {
|
||||
it('requires the configured minimum length', () => {
|
||||
expect(assessAccessToken('a'.repeat(ACCESS_TOKEN_MIN_LENGTH - 1))).toMatchObject({
|
||||
acceptable: false,
|
||||
reason: 'too-short',
|
||||
it('requires the configured minimum length', () => {
|
||||
expect(assessAccessToken('a'.repeat(ACCESS_TOKEN_MIN_LENGTH - 1))).toMatchObject({
|
||||
acceptable: false,
|
||||
reason: 'too-short',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('scores system and user-specific words as guessable', () => {
|
||||
expect(assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001']))
|
||||
.toMatchObject({ acceptable: false, reason: 'guessable' });
|
||||
});
|
||||
it('scores system and user-specific words as guessable', () => {
|
||||
expect(
|
||||
assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001']),
|
||||
).toMatchObject({
|
||||
acceptable: false,
|
||||
reason: 'guessable',
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts a sufficiently long, hard-to-guess token', () => {
|
||||
const result = assessAccessToken('E5xqVb7_9pLt2QwR4M8kZ1nY', ['SnowLuma', 'OneBot']);
|
||||
it('accepts a sufficiently long, hard-to-guess token', () => {
|
||||
const result = assessAccessToken('E5xqVb7_9pLt2QwR4M8kZ1nY', ['SnowLuma', 'OneBot']);
|
||||
|
||||
expect(result.acceptable).toBe(true);
|
||||
expect(result.reason).toBe('acceptable');
|
||||
expect(result.score).toBeGreaterThanOrEqual(ACCESS_TOKEN_MIN_SCORE);
|
||||
});
|
||||
expect(result.acceptable).toBe(true);
|
||||
expect(result.reason).toBe('acceptable');
|
||||
expect(result.score).toBeGreaterThanOrEqual(ACCESS_TOKEN_MIN_SCORE);
|
||||
});
|
||||
});
|
||||
@@ -2,77 +2,77 @@ import { describe, it, expect } from 'vitest';
|
||||
import { isObject, boolOr, clampNum, clampInt } from '../src/coerce';
|
||||
|
||||
describe('isObject', () => {
|
||||
it('is true only for plain non-null non-array objects', () => {
|
||||
expect(isObject({})).toBe(true);
|
||||
expect(isObject({ a: 1 })).toBe(true);
|
||||
expect(isObject(null)).toBe(false);
|
||||
expect(isObject([])).toBe(false);
|
||||
expect(isObject('x')).toBe(false);
|
||||
expect(isObject(42)).toBe(false);
|
||||
expect(isObject(undefined)).toBe(false);
|
||||
});
|
||||
it('is true only for plain non-null non-array objects', () => {
|
||||
expect(isObject({})).toBe(true);
|
||||
expect(isObject({ a: 1 })).toBe(true);
|
||||
expect(isObject(null)).toBe(false);
|
||||
expect(isObject([])).toBe(false);
|
||||
expect(isObject('x')).toBe(false);
|
||||
expect(isObject(42)).toBe(false);
|
||||
expect(isObject(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('boolOr', () => {
|
||||
it('returns the value only when it is a real boolean, else the fallback', () => {
|
||||
expect(boolOr(true, false)).toBe(true);
|
||||
expect(boolOr(false, true)).toBe(false);
|
||||
expect(boolOr('true', false)).toBe(false); // strings are NOT coerced
|
||||
expect(boolOr(1, false)).toBe(false);
|
||||
expect(boolOr(undefined, true)).toBe(true);
|
||||
expect(boolOr(null, true)).toBe(true);
|
||||
});
|
||||
it('returns the value only when it is a real boolean, else the fallback', () => {
|
||||
expect(boolOr(true, false)).toBe(true);
|
||||
expect(boolOr(false, true)).toBe(false);
|
||||
expect(boolOr('true', false)).toBe(false); // strings are NOT coerced
|
||||
expect(boolOr(1, false)).toBe(false);
|
||||
expect(boolOr(undefined, true)).toBe(true);
|
||||
expect(boolOr(null, true)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clampNum', () => {
|
||||
it('passes finite numbers through, clamped to [min,max]', () => {
|
||||
expect(clampNum(5, 0, 10, -1)).toBe(5);
|
||||
expect(clampNum(-3, 0, 10, -1)).toBe(0); // below min
|
||||
expect(clampNum(99, 0, 10, -1)).toBe(10); // above max
|
||||
});
|
||||
it('passes finite numbers through, clamped to [min,max]', () => {
|
||||
expect(clampNum(5, 0, 10, -1)).toBe(5);
|
||||
expect(clampNum(-3, 0, 10, -1)).toBe(0); // below min
|
||||
expect(clampNum(99, 0, 10, -1)).toBe(10); // above max
|
||||
});
|
||||
|
||||
it('coerces numeric strings', () => {
|
||||
expect(clampNum('7', 0, 10, -1)).toBe(7);
|
||||
expect(clampNum('7.5', 0, 10, -1)).toBe(7.5); // NOT truncated (that is clampInt)
|
||||
});
|
||||
it('coerces numeric strings', () => {
|
||||
expect(clampNum('7', 0, 10, -1)).toBe(7);
|
||||
expect(clampNum('7.5', 0, 10, -1)).toBe(7.5); // NOT truncated (that is clampInt)
|
||||
});
|
||||
|
||||
it('falls back on non-finite / non-numeric input', () => {
|
||||
expect(clampNum('abc', 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(NaN, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(Infinity, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(undefined, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(null, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum({}, 0, 10, 3)).toBe(3);
|
||||
});
|
||||
it('falls back on non-finite / non-numeric input', () => {
|
||||
expect(clampNum('abc', 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(NaN, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(Infinity, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(undefined, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(null, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum({}, 0, 10, 3)).toBe(3);
|
||||
});
|
||||
|
||||
it('preserves fractional precision within bounds', () => {
|
||||
expect(clampNum(0.42, 0, 1, 0)).toBe(0.42);
|
||||
});
|
||||
it('preserves fractional precision within bounds', () => {
|
||||
expect(clampNum(0.42, 0, 1, 0)).toBe(0.42);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clampInt', () => {
|
||||
it('is clampNum truncated toward zero', () => {
|
||||
expect(clampInt(7.9, 0, 10, -1)).toBe(7);
|
||||
expect(clampInt('7.9', 0, 10, -1)).toBe(7);
|
||||
expect(clampInt(5, 0, 10, -1)).toBe(5);
|
||||
});
|
||||
it('is clampNum truncated toward zero', () => {
|
||||
expect(clampInt(7.9, 0, 10, -1)).toBe(7);
|
||||
expect(clampInt('7.9', 0, 10, -1)).toBe(7);
|
||||
expect(clampInt(5, 0, 10, -1)).toBe(5);
|
||||
});
|
||||
|
||||
it('clamps before truncating', () => {
|
||||
expect(clampInt(99.9, 0, 10, -1)).toBe(10);
|
||||
expect(clampInt(-3.5, 0, 10, -1)).toBe(0);
|
||||
});
|
||||
it('clamps before truncating', () => {
|
||||
expect(clampInt(99.9, 0, 10, -1)).toBe(10);
|
||||
expect(clampInt(-3.5, 0, 10, -1)).toBe(0);
|
||||
});
|
||||
|
||||
it('clamp-then-trunc ordering: a fractional lower bound is crossed by the clamp, not the trunc', () => {
|
||||
// Distinguishes clamp→trunc (this contract) from trunc→clamp: input 2.4
|
||||
// with min 2.5 → clamp lifts to 2.5, then trunc → 2. A trunc-first impl
|
||||
// would floor to 2 then clamp up to 2.5. Pins the order for the shared
|
||||
// primitive (future callers may use fractional bounds).
|
||||
expect(clampInt(2.4, 2.5, 10, 0)).toBe(2);
|
||||
});
|
||||
it('clamp-then-trunc ordering: a fractional lower bound is crossed by the clamp, not the trunc', () => {
|
||||
// Distinguishes clamp→trunc (this contract) from trunc→clamp: input 2.4
|
||||
// with min 2.5 → clamp lifts to 2.5, then trunc → 2. A trunc-first impl
|
||||
// would floor to 2 then clamp up to 2.5. Pins the order for the shared
|
||||
// primitive (future callers may use fractional bounds).
|
||||
expect(clampInt(2.4, 2.5, 10, 0)).toBe(2);
|
||||
});
|
||||
|
||||
it('falls back on non-finite input', () => {
|
||||
expect(clampInt('abc', 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(NaN, 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(undefined, 0, 10, 4)).toBe(4);
|
||||
});
|
||||
it('falls back on non-finite input', () => {
|
||||
expect(clampInt('abc', 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(NaN, 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(undefined, 0, 10, 4)).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -4,65 +4,78 @@ import { mapWithConcurrency } from '../src/concurrency';
|
||||
const tick = () => new Promise<void>((r) => setTimeout(r, 0));
|
||||
|
||||
describe('mapWithConcurrency', () => {
|
||||
it('returns results in input order', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10);
|
||||
expect(out).toEqual([10, 20, 30, 40, 50]);
|
||||
});
|
||||
|
||||
it('passes the absolute index (across batch boundaries)', async () => {
|
||||
const seen: Array<[number, number]> = [];
|
||||
await mapWithConcurrency(['a', 'b', 'c', 'd', 'e'], 2, async (item, i) => {
|
||||
seen.push([i, item.charCodeAt(0)]);
|
||||
return i;
|
||||
it('returns results in input order', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10);
|
||||
expect(out).toEqual([10, 20, 30, 40, 50]);
|
||||
});
|
||||
expect(seen.map(([i]) => i).sort((x, y) => x - y)).toEqual([0, 1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it('never runs more than `concurrency` at once (batched), and serializes across batches', async () => {
|
||||
let inFlight = 0;
|
||||
let peak = 0;
|
||||
const order: number[] = [];
|
||||
await mapWithConcurrency([0, 1, 2, 3, 4, 5, 6], 3, async (n) => {
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
order.push(n);
|
||||
inFlight--;
|
||||
return n;
|
||||
it('passes the absolute index (across batch boundaries)', async () => {
|
||||
const seen: Array<[number, number]> = [];
|
||||
await mapWithConcurrency(['a', 'b', 'c', 'd', 'e'], 2, async (item, i) => {
|
||||
seen.push([i, item.charCodeAt(0)]);
|
||||
return i;
|
||||
});
|
||||
expect(seen.map(([i]) => i).sort((x, y) => x - y)).toEqual([0, 1, 2, 3, 4]);
|
||||
});
|
||||
expect(peak).toBeLessThanOrEqual(3);
|
||||
// batched: first 3 (0,1,2) settle before the next batch (3,4,5) starts.
|
||||
expect(order.slice(0, 3).sort((a, b) => a - b)).toEqual([0, 1, 2]);
|
||||
expect(order.slice(3, 6).sort((a, b) => a - b)).toEqual([3, 4, 5]);
|
||||
expect(order[6]).toBe(6);
|
||||
});
|
||||
|
||||
it('handles a length not divisible by concurrency (short final batch)', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 3, async (n) => n);
|
||||
expect(out).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it('runs everything in one batch when concurrency >= length', async () => {
|
||||
let peak = 0, inFlight = 0;
|
||||
const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => {
|
||||
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
|
||||
it('never runs more than `concurrency` at once (batched), and serializes across batches', async () => {
|
||||
let inFlight = 0;
|
||||
let peak = 0;
|
||||
const order: number[] = [];
|
||||
await mapWithConcurrency([0, 1, 2, 3, 4, 5, 6], 3, async (n) => {
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
order.push(n);
|
||||
inFlight--;
|
||||
return n;
|
||||
});
|
||||
expect(peak).toBeLessThanOrEqual(3);
|
||||
// batched: first 3 (0,1,2) settle before the next batch (3,4,5) starts.
|
||||
expect(order.slice(0, 3).sort((a, b) => a - b)).toEqual([0, 1, 2]);
|
||||
expect(order.slice(3, 6).sort((a, b) => a - b)).toEqual([3, 4, 5]);
|
||||
expect(order[6]).toBe(6);
|
||||
});
|
||||
expect(out).toEqual([1, 2, 3]);
|
||||
expect(peak).toBe(3);
|
||||
});
|
||||
|
||||
it('returns [] for an empty input without calling fn', async () => {
|
||||
let called = 0;
|
||||
const out = await mapWithConcurrency([], 4, async (n) => { called++; return n; });
|
||||
expect(out).toEqual([]);
|
||||
expect(called).toBe(0);
|
||||
});
|
||||
it('handles a length not divisible by concurrency (short final batch)', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 3, async (n) => n);
|
||||
expect(out).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it('treats concurrency < 1 as 1 (fully serial)', async () => {
|
||||
let peak = 0, inFlight = 0;
|
||||
await mapWithConcurrency([1, 2, 3], 0, async (n) => {
|
||||
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
|
||||
it('runs everything in one batch when concurrency >= length', async () => {
|
||||
let peak = 0,
|
||||
inFlight = 0;
|
||||
const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => {
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
inFlight--;
|
||||
return n;
|
||||
});
|
||||
expect(out).toEqual([1, 2, 3]);
|
||||
expect(peak).toBe(3);
|
||||
});
|
||||
|
||||
it('returns [] for an empty input without calling fn', async () => {
|
||||
let called = 0;
|
||||
const out = await mapWithConcurrency([], 4, async (n) => {
|
||||
called++;
|
||||
return n;
|
||||
});
|
||||
expect(out).toEqual([]);
|
||||
expect(called).toBe(0);
|
||||
});
|
||||
|
||||
it('treats concurrency < 1 as 1 (fully serial)', async () => {
|
||||
let peak = 0,
|
||||
inFlight = 0;
|
||||
await mapWithConcurrency([1, 2, 3], 0, async (n) => {
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
inFlight--;
|
||||
return n;
|
||||
});
|
||||
expect(peak).toBe(1);
|
||||
});
|
||||
expect(peak).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -2,25 +2,33 @@ import { describe, expect, it } from 'vitest';
|
||||
import { positiveIntEnv } from '../src/env';
|
||||
|
||||
describe('positiveIntEnv', () => {
|
||||
it('returns the fallback when the variable is absent or blank', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(15);
|
||||
});
|
||||
it('returns the fallback when the variable is absent or blank', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(
|
||||
15,
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a positive integer and honors the max', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } })).toBe(2500);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: '80' },
|
||||
})).toBe(80);
|
||||
});
|
||||
it('reads a positive integer and honors the max', () => {
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } }),
|
||||
).toBe(2500);
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: '80' },
|
||||
}),
|
||||
).toBe(80);
|
||||
});
|
||||
|
||||
it('ignores zero, negatives, fractions, and values above the max', () => {
|
||||
for (const raw of ['0', '-5', '1.5', 'nope', '70000']) {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: raw },
|
||||
})).toBe(15);
|
||||
}
|
||||
});
|
||||
it('ignores zero, negatives, fractions, and values above the max', () => {
|
||||
for (const raw of ['0', '-5', '1.5', 'nope', '70000']) {
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: raw },
|
||||
}),
|
||||
).toBe(15);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,25 +2,31 @@ import { describe, expect, it } from 'vitest';
|
||||
import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex';
|
||||
|
||||
describe('hex', () => {
|
||||
it('toHex / toHexUpper render bytes as zero-padded hex', () => {
|
||||
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
|
||||
expect(toHex(b)).toBe('000fa0ff');
|
||||
expect(toHexUpper(b)).toBe('000FA0FF');
|
||||
expect(toHex(Uint8Array.of())).toBe('');
|
||||
});
|
||||
it('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('hexPreview appends "..." only past maxBytes', () => {
|
||||
const b = Uint8Array.from([1, 2, 3, 4, 5]);
|
||||
expect(hexPreview(b)).toBe('0102030405'); // under the default 64-byte cap
|
||||
expect(hexPreview(b, 5)).toBe('0102030405'); // exactly at the cap → no ellipsis
|
||||
expect(hexPreview(b, 2)).toBe('0102...'); // truncated
|
||||
expect(hexPreview(b, 0)).toBe('...'); // nothing shown, but bytes remain
|
||||
});
|
||||
it('toHex / toHexUpper render bytes as zero-padded hex', () => {
|
||||
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
|
||||
expect(toHex(b)).toBe('000fa0ff');
|
||||
expect(toHexUpper(b)).toBe('000FA0FF');
|
||||
expect(toHex(Uint8Array.of())).toBe('');
|
||||
});
|
||||
|
||||
it('fromHex round-trips toHex and rejects odd-length input', () => {
|
||||
const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]);
|
||||
expect(fromHex(toHex(b)).equals(b)).toBe(true);
|
||||
expect(toHex(fromHex('00ffa0'))).toBe('00ffa0');
|
||||
expect(() => fromHex('abc')).toThrow();
|
||||
});
|
||||
it('hexPreview appends "..." only past maxBytes', () => {
|
||||
const b = Uint8Array.from([1, 2, 3, 4, 5]);
|
||||
expect(hexPreview(b)).toBe('0102030405'); // under the default 64-byte cap
|
||||
expect(hexPreview(b, 5)).toBe('0102030405'); // exactly at the cap → no ellipsis
|
||||
expect(hexPreview(b, 2)).toBe('0102...'); // truncated
|
||||
expect(hexPreview(b, 0)).toBe('...'); // nothing shown, but bytes remain
|
||||
});
|
||||
|
||||
it('fromHex round-trips toHex and rejects odd-length input', () => {
|
||||
const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]);
|
||||
expect(fromHex(toHex(b)).equals(b)).toBe(true);
|
||||
expect(toHex(fromHex('00ffa0'))).toBe('00ffa0');
|
||||
expect(() => fromHex('abc')).toThrow();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,25 +2,25 @@ import { describe, expect, it } from 'vitest';
|
||||
import { sanitizeLogLine } from '../src/log-sanitize';
|
||||
|
||||
describe('sanitizeLogLine', () => {
|
||||
it('removes SGR styling in seven-bit and eight-bit forms', () => {
|
||||
expect(sanitizeLogLine('\x1b[31mred\x1b[0m / \u009b32mgreen\u009b0m')).toBe('red / green');
|
||||
});
|
||||
it('removes SGR styling in seven-bit and eight-bit forms', () => {
|
||||
expect(sanitizeLogLine('\x1b[31mred\x1b[0m / \u009b32mgreen\u009b0m')).toBe('red / green');
|
||||
});
|
||||
|
||||
it('removes OSC hyperlinks without removing their visible label', () => {
|
||||
expect(
|
||||
sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07'),
|
||||
).toBe('visible');
|
||||
});
|
||||
it('removes OSC hyperlinks without removing their visible label', () => {
|
||||
expect(sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07')).toBe(
|
||||
'visible',
|
||||
);
|
||||
});
|
||||
|
||||
it('removes terminal control-string payloads', () => {
|
||||
expect(sanitizeLogLine('before\x1bPprivate payload\x1b\\after')).toBe('beforeafter');
|
||||
});
|
||||
it('removes terminal control-string payloads', () => {
|
||||
expect(sanitizeLogLine('before\x1bPprivate payload\x1b\\after')).toBe('beforeafter');
|
||||
});
|
||||
|
||||
it('preserves tabs and newlines while removing other controls', () => {
|
||||
expect(sanitizeLogLine('one\ttwo\nthree\r\x00')).toBe('one\ttwo\nthree');
|
||||
});
|
||||
it('preserves tabs and newlines while removing other controls', () => {
|
||||
expect(sanitizeLogLine('one\ttwo\nthree\r\x00')).toBe('one\ttwo\nthree');
|
||||
});
|
||||
|
||||
it('does not leak unterminated terminal strings', () => {
|
||||
expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible');
|
||||
});
|
||||
it('does not leak unterminated terminal strings', () => {
|
||||
expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible');
|
||||
});
|
||||
});
|
||||
@@ -1,234 +1,230 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
redactLogMessage,
|
||||
renderParamsVerbose,
|
||||
summarizeParams,
|
||||
} from '../src/log-summary';
|
||||
import { redactLogMessage, renderParamsVerbose, summarizeParams } from '../src/log-summary';
|
||||
|
||||
describe('summarizeParams', () => {
|
||||
it('renders null/undefined as {}', () => {
|
||||
expect(summarizeParams(null)).toBe('{}');
|
||||
expect(summarizeParams(undefined)).toBe('{}');
|
||||
});
|
||||
|
||||
it('renders a top-level non-object via String() WITHOUT quotes', () => {
|
||||
// The reported change-request: a top-level primitive is NOT JSON-quoted.
|
||||
expect(summarizeParams('hello')).toBe('hello');
|
||||
expect(summarizeParams(123)).toBe('123');
|
||||
});
|
||||
|
||||
it('collapses a top-level array to [len=N]', () => {
|
||||
expect(summarizeParams([1, 2, 3])).toBe('[len=3]');
|
||||
});
|
||||
|
||||
it('quotes string fields, collapses nested values, truncates long strings', () => {
|
||||
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] }))
|
||||
.toBe('a=1 b="x" c={...} e=[len=2]');
|
||||
expect(summarizeParams({ s: 'x'.repeat(50) }))
|
||||
.toBe(`s="${'x'.repeat(40)}..."`);
|
||||
});
|
||||
|
||||
it('redacts authentication fields without exposing their values', () => {
|
||||
const out = summarizeParams({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
Authorization: 'Bearer authorization-value',
|
||||
user_password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
group_id: 12345,
|
||||
it('renders null/undefined as {}', () => {
|
||||
expect(summarizeParams(null)).toBe('{}');
|
||||
expect(summarizeParams(undefined)).toBe('{}');
|
||||
});
|
||||
|
||||
expect(out).toContain('token="***"');
|
||||
expect(out).toContain('Cookie="***"');
|
||||
expect(out).toContain('Authorization="***"');
|
||||
expect(out).toContain('user_password="***"');
|
||||
expect(out).toContain('apiKey="***"');
|
||||
expect(out).toContain('group_id=12345');
|
||||
expect(out).not.toMatch(
|
||||
/token-value|cookie-value|authorization-value|password-value|key-value/,
|
||||
);
|
||||
});
|
||||
it('renders a top-level non-object via String() WITHOUT quotes', () => {
|
||||
// The reported change-request: a top-level primitive is NOT JSON-quoted.
|
||||
expect(summarizeParams('hello')).toBe('hello');
|
||||
expect(summarizeParams(123)).toBe('123');
|
||||
});
|
||||
|
||||
it('does not treat sensitive substrings inside ordinary keys as credentials', () => {
|
||||
expect(summarizeParams({
|
||||
retoken: 'visible',
|
||||
cookietown: 'visible',
|
||||
myauthorization: 'visible',
|
||||
})).toBe(
|
||||
'retoken="visible" cookietown="visible" myauthorization="visible"',
|
||||
);
|
||||
});
|
||||
it('collapses a top-level array to [len=N]', () => {
|
||||
expect(summarizeParams([1, 2, 3])).toBe('[len=3]');
|
||||
});
|
||||
|
||||
it('caps total output and appends "..." on overflow', () => {
|
||||
const big: Record<string, number> = {};
|
||||
for (let i = 0; i < 60; i++) big['key' + i] = i;
|
||||
const out = summarizeParams(big);
|
||||
expect(out.startsWith('key0=0')).toBe(true);
|
||||
expect(out.endsWith('...')).toBe(true);
|
||||
expect(out.length).toBeLessThanOrEqual(200);
|
||||
});
|
||||
it('quotes string fields, collapses nested values, truncates long strings', () => {
|
||||
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] })).toBe(
|
||||
'a=1 b="x" c={...} e=[len=2]',
|
||||
);
|
||||
expect(summarizeParams({ s: 'x'.repeat(50) })).toBe(`s="${'x'.repeat(40)}..."`);
|
||||
});
|
||||
|
||||
it('caps a single oversized first key and top-level primitive', () => {
|
||||
const oversizedKey = 'k'.repeat(300);
|
||||
it('redacts authentication fields without exposing their values', () => {
|
||||
const out = summarizeParams({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
Authorization: 'Bearer authorization-value',
|
||||
user_password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
group_id: 12345,
|
||||
});
|
||||
|
||||
const objectOut = summarizeParams({ [oversizedKey]: 'value' });
|
||||
const primitiveOut = summarizeParams('x'.repeat(300));
|
||||
expect(out).toContain('token="***"');
|
||||
expect(out).toContain('Cookie="***"');
|
||||
expect(out).toContain('Authorization="***"');
|
||||
expect(out).toContain('user_password="***"');
|
||||
expect(out).toContain('apiKey="***"');
|
||||
expect(out).toContain('group_id=12345');
|
||||
expect(out).not.toMatch(
|
||||
/token-value|cookie-value|authorization-value|password-value|key-value/,
|
||||
);
|
||||
});
|
||||
|
||||
expect(objectOut).toHaveLength(200);
|
||||
expect(objectOut.endsWith('...')).toBe(true);
|
||||
expect(primitiveOut).toHaveLength(200);
|
||||
expect(primitiveOut.endsWith('...')).toBe(true);
|
||||
});
|
||||
it('does not treat sensitive substrings inside ordinary keys as credentials', () => {
|
||||
expect(
|
||||
summarizeParams({
|
||||
retoken: 'visible',
|
||||
cookietown: 'visible',
|
||||
myauthorization: 'visible',
|
||||
}),
|
||||
).toBe('retoken="visible" cookietown="visible" myauthorization="visible"');
|
||||
});
|
||||
|
||||
it('caps total output and appends "..." on overflow', () => {
|
||||
const big: Record<string, number> = {};
|
||||
|
||||
for (let i = 0; i < 60; i++) {
|
||||
big['key' + i] = i;
|
||||
}
|
||||
|
||||
const out = summarizeParams(big);
|
||||
expect(out.startsWith('key0=0')).toBe(true);
|
||||
expect(out.endsWith('...')).toBe(true);
|
||||
expect(out.length).toBeLessThanOrEqual(200);
|
||||
});
|
||||
|
||||
it('caps a single oversized first key and top-level primitive', () => {
|
||||
const oversizedKey = 'k'.repeat(300);
|
||||
|
||||
const objectOut = summarizeParams({ [oversizedKey]: 'value' });
|
||||
const primitiveOut = summarizeParams('x'.repeat(300));
|
||||
|
||||
expect(objectOut).toHaveLength(200);
|
||||
expect(objectOut.endsWith('...')).toBe(true);
|
||||
expect(primitiveOut).toHaveLength(200);
|
||||
expect(primitiveOut.endsWith('...')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('redactLogMessage', () => {
|
||||
it('redacts explicit authentication assignments without changing prose', () => {
|
||||
const out = redactLogMessage(
|
||||
'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required',
|
||||
);
|
||||
it('redacts explicit authentication assignments without changing prose', () => {
|
||||
const out = redactLogMessage(
|
||||
'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required',
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
'password=*** Authorization: *** cookie=*** password change required',
|
||||
);
|
||||
});
|
||||
expect(out).toBe('password=*** Authorization: *** cookie=*** password change required');
|
||||
});
|
||||
|
||||
it('redacts quoted object keys, Basic auth, and complete Cookie values', () => {
|
||||
const out = redactLogMessage(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
const expires = redactLogMessage(
|
||||
'Cookie=session=expires-secret; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Path=/; HttpOnly safe=visible',
|
||||
);
|
||||
it('redacts quoted object keys, Basic auth, and complete Cookie values', () => {
|
||||
const out = redactLogMessage(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
const expires = redactLogMessage(
|
||||
'Cookie=session=expires-secret; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Path=/; HttpOnly safe=visible',
|
||||
);
|
||||
|
||||
expect(out).toContain('json={"authorization":***}');
|
||||
expect(out).toContain("object={ 'api-key': *** }");
|
||||
expect(out).toContain('Authorization: *** Cookie=***');
|
||||
expect(expires).toBe('Cookie=*** safe=visible');
|
||||
expect(out).not.toMatch(/json-auth|api-secret|header-auth|cookie-secret|Path=|HttpOnly/);
|
||||
expect(expires).not.toMatch(/expires-secret|Expires|21 Oct|Path=|HttpOnly/);
|
||||
});
|
||||
expect(out).toContain('json={"authorization":***}');
|
||||
expect(out).toContain("object={ 'api-key': *** }");
|
||||
expect(out).toContain('Authorization: *** Cookie=***');
|
||||
expect(expires).toBe('Cookie=*** safe=visible');
|
||||
expect(out).not.toMatch(/json-auth|api-secret|header-auth|cookie-secret|Path=|HttpOnly/);
|
||||
expect(expires).not.toMatch(/expires-secret|Expires|21 Oct|Path=|HttpOnly/);
|
||||
});
|
||||
|
||||
it('redacts complete multi-parameter Authorization values', () => {
|
||||
const out = redactLogMessage(
|
||||
'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n'
|
||||
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, '
|
||||
+ 'SignedHeaders=host;x-date, Signature=aws-secret\n'
|
||||
+ 'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/',
|
||||
);
|
||||
it('redacts complete multi-parameter Authorization values', () => {
|
||||
const out = redactLogMessage(
|
||||
'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n' +
|
||||
'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, ' +
|
||||
'SignedHeaders=host;x-date, Signature=aws-secret\n' +
|
||||
'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/',
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
'Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***',
|
||||
);
|
||||
expect(out).not.toMatch(
|
||||
/alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/,
|
||||
);
|
||||
});
|
||||
expect(out).toBe('Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***');
|
||||
expect(out).not.toMatch(
|
||||
/alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/,
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts camelCase authentication keys without matching larger words', () => {
|
||||
const out = redactLogMessage(
|
||||
`authToken=auth-secret idToken=id-secret clientSecret=client-secret {"userPassword":"password-secret"}`,
|
||||
);
|
||||
it('redacts camelCase authentication keys without matching larger words', () => {
|
||||
const out = redactLogMessage(
|
||||
`authToken=auth-secret idToken=id-secret clientSecret=client-secret {"userPassword":"password-secret"}`,
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
`authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`,
|
||||
);
|
||||
expect(out).not.toMatch(
|
||||
/auth-secret|id-secret|client-secret|password-secret/,
|
||||
);
|
||||
expect(redactLogMessage(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
)).toBe('retoken=value cookietown=value myauthorization=value');
|
||||
});
|
||||
expect(out).toBe(`authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`);
|
||||
expect(out).not.toMatch(/auth-secret|id-secret|client-secret|password-secret/);
|
||||
expect(redactLogMessage('retoken=value cookietown=value myauthorization=value')).toBe(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts leading separator and numeric authentication keys without matching larger words', () => {
|
||||
expect(redactLogMessage(
|
||||
'_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible',
|
||||
)).toBe('_token=*** --password=*** 2faToken=*** retoken=visible');
|
||||
});
|
||||
it('redacts leading separator and numeric authentication keys without matching larger words', () => {
|
||||
expect(
|
||||
redactLogMessage(
|
||||
'_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible',
|
||||
),
|
||||
).toBe('_token=*** --password=*** 2faToken=*** retoken=visible');
|
||||
});
|
||||
|
||||
it('redacts nested assignments inside non-sensitive wrapper values', () => {
|
||||
expect(redactLogMessage(
|
||||
'params=authToken=auth-secret params=cookie="cookie-secret"',
|
||||
)).toBe('params=authToken=*** params=cookie=***');
|
||||
});
|
||||
it('redacts nested assignments inside non-sensitive wrapper values', () => {
|
||||
expect(redactLogMessage('params=authToken=auth-secret params=cookie="cookie-secret"')).toBe(
|
||||
'params=authToken=*** params=cookie=***',
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts the entire Authorization value when it starts with a marker', () => {
|
||||
expect(redactLogMessage('Authorization: *** secret-value'))
|
||||
.toBe('Authorization: ***');
|
||||
});
|
||||
it('redacts the entire Authorization value when it starts with a marker', () => {
|
||||
expect(redactLogMessage('Authorization: *** secret-value')).toBe('Authorization: ***');
|
||||
});
|
||||
|
||||
it('redacts property paths and URL query authentication values', () => {
|
||||
const out = redactLogMessage(
|
||||
'headers.authorization=Basic dXNlcjpwYXNz '
|
||||
+ 'request.token=plain-token '
|
||||
+ 'GET /callback?access_token=query-secret&x=1 '
|
||||
+ 'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
it('redacts property paths and URL query authentication values', () => {
|
||||
const out = redactLogMessage(
|
||||
'headers.authorization=Basic dXNlcjpwYXNz ' +
|
||||
'request.token=plain-token ' +
|
||||
'GET /callback?access_token=query-secret&x=1 ' +
|
||||
'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
|
||||
expect(out).toContain('headers.authorization=***');
|
||||
expect(out).toContain('request.token=***');
|
||||
expect(out).toContain('/callback?access_token=***&x=1');
|
||||
expect(out).toContain('https://host/?api_key=***');
|
||||
expect(out).not.toMatch(/dXNlcjpwYXNz|plain-token|query-secret|url-secret/);
|
||||
});
|
||||
expect(out).toContain('headers.authorization=***');
|
||||
expect(out).toContain('request.token=***');
|
||||
expect(out).toContain('/callback?access_token=***&x=1');
|
||||
expect(out).toContain('https://host/?api_key=***');
|
||||
expect(out).not.toMatch(/dXNlcjpwYXNz|plain-token|query-secret|url-secret/);
|
||||
});
|
||||
|
||||
it('redacts prefixed authentication keys without matching larger words', () => {
|
||||
const redacted = redactLogMessage(
|
||||
'x-api-key=api-secret user_password=password-secret '
|
||||
+ 'headers.authorization=Basic auth-secret '
|
||||
+ 'x-cookie="session=cookie-secret"; Path=/; HttpOnly',
|
||||
);
|
||||
it('redacts prefixed authentication keys without matching larger words', () => {
|
||||
const redacted = redactLogMessage(
|
||||
'x-api-key=api-secret user_password=password-secret ' +
|
||||
'headers.authorization=Basic auth-secret ' +
|
||||
'x-cookie="session=cookie-secret"; Path=/; HttpOnly',
|
||||
);
|
||||
|
||||
expect(redacted).toContain('x-api-key=***');
|
||||
expect(redacted).toContain('user_password=***');
|
||||
expect(redacted).toContain('headers.authorization=***');
|
||||
expect(redacted).toContain('x-cookie=***');
|
||||
expect(redacted).not.toMatch(/api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/);
|
||||
expect(redactLogMessage(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
)).toBe('retoken=value cookietown=value myauthorization=value');
|
||||
});
|
||||
expect(redacted).toContain('x-api-key=***');
|
||||
expect(redacted).toContain('user_password=***');
|
||||
expect(redacted).toContain('headers.authorization=***');
|
||||
expect(redacted).toContain('x-cookie=***');
|
||||
expect(redacted).not.toMatch(
|
||||
/api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/,
|
||||
);
|
||||
expect(redactLogMessage('retoken=value cookietown=value myauthorization=value')).toBe(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderParamsVerbose', () => {
|
||||
it('keeps authentication fields unredacted for complete TRACE diagnostics', () => {
|
||||
const out = renderParamsVerbose({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
it('keeps authentication fields unredacted for complete TRACE diagnostics', () => {
|
||||
const out = renderParamsVerbose({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
});
|
||||
|
||||
expect(out).toContain('token:"token-value"');
|
||||
expect(out).toContain('Cookie:"cookie-value"');
|
||||
expect(out).toContain('password:"password-value"');
|
||||
expect(out).toContain('apiKey:"key-value"');
|
||||
expect(out).not.toContain('"***"');
|
||||
});
|
||||
|
||||
expect(out).toContain('token:"token-value"');
|
||||
expect(out).toContain('Cookie:"cookie-value"');
|
||||
expect(out).toContain('password:"password-value"');
|
||||
expect(out).toContain('apiKey:"key-value"');
|
||||
expect(out).not.toContain('"***"');
|
||||
});
|
||||
it('does not truncate TRACE values or their enclosing object', () => {
|
||||
const unicodeValue = '雪'.repeat(800);
|
||||
const out = renderParamsVerbose({ blob: unicodeValue, tail: 'complete' });
|
||||
|
||||
it('does not truncate TRACE values or their enclosing object', () => {
|
||||
const unicodeValue = '雪'.repeat(800);
|
||||
const out = renderParamsVerbose({ blob: unicodeValue, tail: 'complete' });
|
||||
expect(out).toContain(`blob:${JSON.stringify(unicodeValue)}`);
|
||||
expect(out).toContain('tail:"complete"');
|
||||
expect(out).not.toMatch(/…<\d+B>|\.\.\./);
|
||||
});
|
||||
|
||||
expect(out).toContain(`blob:${JSON.stringify(unicodeValue)}`);
|
||||
expect(out).toContain('tail:"complete"');
|
||||
expect(out).not.toMatch(/…<\d+B>|\.\.\./);
|
||||
});
|
||||
it('guards against circular references', () => {
|
||||
const o: Record<string, unknown> = { a: 1 };
|
||||
o.self = o;
|
||||
expect(renderParamsVerbose(o)).toContain('"[circular]"');
|
||||
});
|
||||
|
||||
it('guards against circular references', () => {
|
||||
const o: Record<string, unknown> = { a: 1 };
|
||||
o.self = o;
|
||||
expect(renderParamsVerbose(o)).toContain('"[circular]"');
|
||||
});
|
||||
it('renders shared non-cyclic references in every branch', () => {
|
||||
const shared = { value: 1 };
|
||||
|
||||
it('renders shared non-cyclic references in every branch', () => {
|
||||
const shared = { value: 1 };
|
||||
expect(renderParamsVerbose({ left: shared, right: shared })).toBe(
|
||||
'{left:{value:1},right:{value:1}}',
|
||||
);
|
||||
});
|
||||
|
||||
expect(renderParamsVerbose({ left: shared, right: shared }))
|
||||
.toBe('{left:{value:1},right:{value:1}}');
|
||||
});
|
||||
|
||||
it('renders nested structure with primitives intact', () => {
|
||||
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
|
||||
});
|
||||
it('renders nested structure with primitives intact', () => {
|
||||
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
|
||||
});
|
||||
});
|
||||
@@ -1,83 +1,84 @@
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { externalFileLevel, externalLogLevel, fileWriteSpy } = vi.hoisted(() => {
|
||||
const savedFileLevel = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
return {
|
||||
externalFileLevel: savedFileLevel,
|
||||
externalLogLevel: savedLogLevel,
|
||||
fileWriteSpy: vi.fn(),
|
||||
};
|
||||
const savedFileLevel = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
return {
|
||||
externalFileLevel: savedFileLevel,
|
||||
externalLogLevel: savedLogLevel,
|
||||
fileWriteSpy: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
// Capture file transport writes via a spy so tests can assert on what reaches
|
||||
// the file.
|
||||
vi.mock('../src/log-file-transport', () => ({
|
||||
getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }),
|
||||
getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }),
|
||||
}));
|
||||
|
||||
import {
|
||||
createLogger,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '../src/logger';
|
||||
import { createLogger, subscribeLogs, type LogEntry } from '../src/logger';
|
||||
|
||||
// Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp
|
||||
// shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored
|
||||
// render path did `' '.repeat(slot - tagLen)` → RangeError: Invalid count value
|
||||
// → uncaughtException. The padding must clamp at zero.
|
||||
describe('logger UIN slot padding', () => {
|
||||
let prevTTY: boolean | undefined;
|
||||
let prevNoColor: string | undefined;
|
||||
let prevTTY: boolean | undefined;
|
||||
let prevNoColor: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
prevTTY = process.stdout.isTTY;
|
||||
prevNoColor = process.env.NO_COLOR;
|
||||
// Force the colored render path (the only one that used .repeat()).
|
||||
(process.stdout as unknown as { isTTY: boolean }).isTTY = true;
|
||||
delete process.env.NO_COLOR;
|
||||
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
|
||||
if (prevNoColor === undefined) delete process.env.NO_COLOR;
|
||||
else process.env.NO_COLOR = prevNoColor;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('does not throw when the UIN tag exceeds the slot width', () => {
|
||||
const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars
|
||||
expect(() => log.info('phantom account line')).not.toThrow();
|
||||
expect(() => log.error('phantom error line')).not.toThrow();
|
||||
});
|
||||
|
||||
it('still renders a normal-width UIN and a no-UIN logger', () => {
|
||||
expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow();
|
||||
expect(() => createLogger('Test').info('no uin')).not.toThrow();
|
||||
});
|
||||
|
||||
it('does not throw when the console stream cannot accept the line', () => {
|
||||
vi.mocked(process.stderr.write).mockImplementation(() => {
|
||||
throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' });
|
||||
beforeEach(() => {
|
||||
prevTTY = process.stdout.isTTY;
|
||||
prevNoColor = process.env.NO_COLOR;
|
||||
// Force the colored render path (the only one that used .repeat()).
|
||||
(process.stdout as unknown as { isTTY: boolean }).isTTY = true;
|
||||
delete process.env.NO_COLOR;
|
||||
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
});
|
||||
expect(() => createLogger('Test').error('disk is full')).not.toThrow();
|
||||
});
|
||||
|
||||
it('keeps structured subscriber lines plain while terminal output stays colored', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => captured.push(entry));
|
||||
afterEach(() => {
|
||||
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
|
||||
|
||||
createLogger('WebUI.Export').info('download me');
|
||||
unsubscribe();
|
||||
if (prevNoColor === undefined) {
|
||||
delete process.env.NO_COLOR;
|
||||
} else {
|
||||
process.env.NO_COLOR = prevNoColor;
|
||||
}
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(captured[0]!.line).toMatch(/INFO\s+\[WebUI\.Export\] download me$/);
|
||||
expect(process.stdout.write).toHaveBeenCalledWith(expect.stringContaining('\x1b['));
|
||||
});
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('does not throw when the UIN tag exceeds the slot width', () => {
|
||||
const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars
|
||||
expect(() => log.info('phantom account line')).not.toThrow();
|
||||
expect(() => log.error('phantom error line')).not.toThrow();
|
||||
});
|
||||
|
||||
it('still renders a normal-width UIN and a no-UIN logger', () => {
|
||||
expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow();
|
||||
expect(() => createLogger('Test').info('no uin')).not.toThrow();
|
||||
});
|
||||
|
||||
it('does not throw when the console stream cannot accept the line', () => {
|
||||
vi.mocked(process.stderr.write).mockImplementation(() => {
|
||||
throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' });
|
||||
});
|
||||
expect(() => createLogger('Test').error('disk is full')).not.toThrow();
|
||||
});
|
||||
|
||||
it('keeps structured subscriber lines plain while terminal output stays colored', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => captured.push(entry));
|
||||
|
||||
createLogger('WebUI.Export').info('download me');
|
||||
unsubscribe();
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(captured[0]!.line).toMatch(/INFO\s+\[WebUI\.Export\] download me$/);
|
||||
expect(process.stdout.write).toHaveBeenCalledWith(expect.stringContaining('\x1b['));
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Independent file-level filtering ─────────────────────────────────────
|
||||
@@ -85,237 +86,253 @@ describe('logger UIN slot padding', () => {
|
||||
const SAVED_FILE_LEVEL = externalFileLevel;
|
||||
|
||||
async function loadLoggerForFileLevel(level?: string) {
|
||||
if (level === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_FILE_LEVEL = level;
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
return import('../src/logger');
|
||||
if (level === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = level;
|
||||
}
|
||||
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
return import('../src/logger');
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
if (SAVED_FILE_LEVEL === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
}
|
||||
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
if (externalLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel;
|
||||
if (SAVED_FILE_LEVEL === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
}
|
||||
|
||||
if (externalLogLevel === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel;
|
||||
}
|
||||
});
|
||||
|
||||
describe('file output gating', () => {
|
||||
const cases = [
|
||||
{ level: undefined, expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'debug', expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'info', expected: ['info', 'success', 'warn', 'error'] },
|
||||
{ level: 'success', expected: ['success', 'warn', 'error'] },
|
||||
{ level: 'warn', expected: ['warn', 'error'] },
|
||||
{ level: 'error', expected: ['error'] },
|
||||
] as const;
|
||||
const cases = [
|
||||
{ level: undefined, expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'debug', expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'info', expected: ['info', 'success', 'warn', 'error'] },
|
||||
{ level: 'success', expected: ['success', 'warn', 'error'] },
|
||||
{ level: 'warn', expected: ['warn', 'error'] },
|
||||
{ level: 'error', expected: ['error'] },
|
||||
] as const;
|
||||
|
||||
for (const testCase of cases) {
|
||||
it(`writes exactly the enabled levels for ${testCase.level ?? 'the default'}`, async () => {
|
||||
const fresh = await loadLoggerForFileLevel(testCase.level);
|
||||
const log = fresh.createLogger('Test');
|
||||
for (const testCase of cases) {
|
||||
it(`writes exactly the enabled levels for ${testCase.level ?? 'the default'}`, async () => {
|
||||
const fresh = await loadLoggerForFileLevel(testCase.level);
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
fresh.setLogLevel('trace');
|
||||
log.trace('trace');
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
log.success('success');
|
||||
log.warn('warn');
|
||||
log.error('error');
|
||||
fresh.setLogLevel('trace');
|
||||
log.trace('trace');
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
log.success('success');
|
||||
log.warn('warn');
|
||||
log.error('error');
|
||||
|
||||
const messages = fileWriteSpy.mock.calls.map(([line]) => String(line).split('] ').at(-1));
|
||||
expect(messages).toEqual(testCase.expected);
|
||||
});
|
||||
}
|
||||
|
||||
it('accepts surrounding whitespace and mixed case', async () => {
|
||||
const fresh = await loadLoggerForFileLevel(' INFO ');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(expect.stringContaining('info'), undefined);
|
||||
});
|
||||
|
||||
it.each(['trace', 'verbose', 'erorr'])(
|
||||
'rejects unsupported file level %s at startup',
|
||||
async (level) => {
|
||||
await expect(loadLoggerForFileLevel(level)).rejects.toThrow(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('does not let the runtime console level change file output', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('info');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
fresh.setLogLevel('error');
|
||||
log.info('persisted-info');
|
||||
fresh.setLogLevel('trace');
|
||||
log.debug('filtered-debug');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('persisted-info'),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('skips rendering when both console and file filters reject a record', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('error');
|
||||
fresh.setLogLevel('error');
|
||||
const rendered = vi.fn(() => 'expensive');
|
||||
const value = { [Symbol.toPrimitive]: rendered };
|
||||
|
||||
fresh.createLogger('Test').debug('value=%s', value);
|
||||
|
||||
expect(rendered).not.toHaveBeenCalled();
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps trace out of files in an explicit file-threshold check', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
fresh.createLogger('Test').trace('full chain');
|
||||
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redacts authentication assignments from ordinary logs but not TRACE', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.info(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s safe=%s',
|
||||
'ordinary-password',
|
||||
'ordinary-authorization',
|
||||
'ordinary-cookie',
|
||||
'ordinary-token',
|
||||
'visible',
|
||||
);
|
||||
log.trace(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s',
|
||||
'trace-password',
|
||||
'trace-authorization',
|
||||
'trace-cookie',
|
||||
'trace-token',
|
||||
);
|
||||
log.info(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
log.info(
|
||||
'headers.authorization=Basic dotted-auth request.token=dotted-token '
|
||||
+ 'GET /callback?access_token=query-secret&x=1 '
|
||||
+ 'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
log.info(
|
||||
'Authorization: Digest username="alice", response="digest-secret"\n'
|
||||
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret',
|
||||
);
|
||||
log.info(
|
||||
'authToken=camel-auth idToken=camel-id clientSecret=camel-client '
|
||||
+ `json={"userPassword":"camel-password"}`,
|
||||
);
|
||||
log.info('_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret');
|
||||
log.info('Authorization: *** marker-secret');
|
||||
log.trace(
|
||||
`json={"authorization":"Basic trace-json-auth"} Authorization: Basic trace-header-auth Cookie=session=trace-cookie; Path=/`,
|
||||
);
|
||||
unsubscribe();
|
||||
|
||||
const ordinaryEntries = entries.filter((entry) => entry.level === 'info');
|
||||
const ordinary = ordinaryEntries.map((entry) => entry.message).join('\n');
|
||||
expect(ordinary).toContain('password=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('Cookie=***');
|
||||
expect(ordinary).toContain('token=***');
|
||||
expect(ordinary).toContain('headers.authorization=***');
|
||||
expect(ordinary).toContain('request.token=***');
|
||||
expect(ordinary).toContain('/callback?access_token=***&x=1');
|
||||
expect(ordinary).toContain('https://host/?api_key=***');
|
||||
expect(ordinary).toContain('Authorization: ***\nauthorization=***');
|
||||
expect(ordinary).toContain('authToken=***');
|
||||
expect(ordinary).toContain('idToken=***');
|
||||
expect(ordinary).toContain('clientSecret=***');
|
||||
expect(ordinary).toContain(`json={"userPassword":***}`);
|
||||
expect(ordinary).toContain('_token=***');
|
||||
expect(ordinary).toContain('--password=***');
|
||||
expect(ordinary).toContain('2faToken=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('safe=visible');
|
||||
expect(ordinary).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|camel-auth|camel-id|camel-client|camel-password|underscore-secret|cli-secret|two-factor-secret|marker-secret/,
|
||||
);
|
||||
|
||||
const trace = entries.filter((entry) => entry.level === 'trace')
|
||||
.map((entry) => entry.message)
|
||||
.join('\n');
|
||||
expect(trace).toContain('trace-password');
|
||||
expect(trace).toContain('trace-authorization');
|
||||
expect(trace).toContain('trace-cookie');
|
||||
expect(trace).toContain('trace-token');
|
||||
expect(trace).toContain('trace-json-auth');
|
||||
expect(trace).toContain('trace-header-auth');
|
||||
|
||||
const persisted = fileWriteSpy.mock.calls.map(([line]) => String(line)).join('\n');
|
||||
expect(persisted).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|trace-password|trace-json-auth/,
|
||||
);
|
||||
});
|
||||
|
||||
it('returns the complete retained normal and TRACE snapshot in record order', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
const log = fresh.createLogger('Export');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
log.info('normal-before');
|
||||
log.trace('trace-hex=001122aabbcc');
|
||||
log.warn('normal-after');
|
||||
|
||||
expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual([
|
||||
'normal-after',
|
||||
]);
|
||||
expect(fresh.getLogSnapshot().map((entry) => entry.message)).toEqual([
|
||||
'normal-before',
|
||||
'trace-hex=001122aabbcc',
|
||||
'normal-after',
|
||||
]);
|
||||
});
|
||||
|
||||
it('prints bootstrap credentials only to the current process terminal', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('error');
|
||||
fresh.setLogLevel('error');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const snapshotBefore = fresh.getLogSnapshot();
|
||||
const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
|
||||
try {
|
||||
fresh.logInitialWebuiCredentials('secret');
|
||||
|
||||
expect(stdout).toHaveBeenCalledWith(
|
||||
expect.stringContaining('initial credentials: user=admin password=secret'),
|
||||
);
|
||||
expect(entries).toEqual([]);
|
||||
expect(fresh.getLogSnapshot()).toEqual(snapshotBefore);
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
unsubscribe();
|
||||
stdout.mockRestore();
|
||||
const messages = fileWriteSpy.mock.calls.map(([line]) =>
|
||||
String(line).split('] ').at(-1),
|
||||
);
|
||||
expect(messages).toEqual(testCase.expected);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts surrounding whitespace and mixed case', async () => {
|
||||
const fresh = await loadLoggerForFileLevel(' INFO ');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(expect.stringContaining('info'), undefined);
|
||||
});
|
||||
|
||||
it.each(['trace', 'verbose', 'erorr'])(
|
||||
'rejects unsupported file level %s at startup',
|
||||
async (level) => {
|
||||
await expect(loadLoggerForFileLevel(level)).rejects.toThrow(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('does not let the runtime console level change file output', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('info');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
fresh.setLogLevel('error');
|
||||
log.info('persisted-info');
|
||||
fresh.setLogLevel('trace');
|
||||
log.debug('filtered-debug');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('persisted-info'),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('skips rendering when both console and file filters reject a record', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('error');
|
||||
fresh.setLogLevel('error');
|
||||
const rendered = vi.fn(() => 'expensive');
|
||||
const value = { [Symbol.toPrimitive]: rendered };
|
||||
|
||||
fresh.createLogger('Test').debug('value=%s', value);
|
||||
|
||||
expect(rendered).not.toHaveBeenCalled();
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps trace out of files in an explicit file-threshold check', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
fresh.createLogger('Test').trace('full chain');
|
||||
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redacts authentication assignments from ordinary logs but not TRACE', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.info(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s safe=%s',
|
||||
'ordinary-password',
|
||||
'ordinary-authorization',
|
||||
'ordinary-cookie',
|
||||
'ordinary-token',
|
||||
'visible',
|
||||
);
|
||||
log.trace(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s',
|
||||
'trace-password',
|
||||
'trace-authorization',
|
||||
'trace-cookie',
|
||||
'trace-token',
|
||||
);
|
||||
log.info(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
log.info(
|
||||
'headers.authorization=Basic dotted-auth request.token=dotted-token ' +
|
||||
'GET /callback?access_token=query-secret&x=1 ' +
|
||||
'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
log.info(
|
||||
'Authorization: Digest username="alice", response="digest-secret"\n' +
|
||||
'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret',
|
||||
);
|
||||
log.info(
|
||||
'authToken=camel-auth idToken=camel-id clientSecret=camel-client ' +
|
||||
`json={"userPassword":"camel-password"}`,
|
||||
);
|
||||
log.info('_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret');
|
||||
log.info('Authorization: *** marker-secret');
|
||||
log.trace(
|
||||
`json={"authorization":"Basic trace-json-auth"} Authorization: Basic trace-header-auth Cookie=session=trace-cookie; Path=/`,
|
||||
);
|
||||
unsubscribe();
|
||||
|
||||
const ordinaryEntries = entries.filter((entry) => entry.level === 'info');
|
||||
const ordinary = ordinaryEntries.map((entry) => entry.message).join('\n');
|
||||
expect(ordinary).toContain('password=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('Cookie=***');
|
||||
expect(ordinary).toContain('token=***');
|
||||
expect(ordinary).toContain('headers.authorization=***');
|
||||
expect(ordinary).toContain('request.token=***');
|
||||
expect(ordinary).toContain('/callback?access_token=***&x=1');
|
||||
expect(ordinary).toContain('https://host/?api_key=***');
|
||||
expect(ordinary).toContain('Authorization: ***\nauthorization=***');
|
||||
expect(ordinary).toContain('authToken=***');
|
||||
expect(ordinary).toContain('idToken=***');
|
||||
expect(ordinary).toContain('clientSecret=***');
|
||||
expect(ordinary).toContain(`json={"userPassword":***}`);
|
||||
expect(ordinary).toContain('_token=***');
|
||||
expect(ordinary).toContain('--password=***');
|
||||
expect(ordinary).toContain('2faToken=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('safe=visible');
|
||||
expect(ordinary).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|camel-auth|camel-id|camel-client|camel-password|underscore-secret|cli-secret|two-factor-secret|marker-secret/,
|
||||
);
|
||||
|
||||
const trace = entries
|
||||
.filter((entry) => entry.level === 'trace')
|
||||
.map((entry) => entry.message)
|
||||
.join('\n');
|
||||
expect(trace).toContain('trace-password');
|
||||
expect(trace).toContain('trace-authorization');
|
||||
expect(trace).toContain('trace-cookie');
|
||||
expect(trace).toContain('trace-token');
|
||||
expect(trace).toContain('trace-json-auth');
|
||||
expect(trace).toContain('trace-header-auth');
|
||||
|
||||
const persisted = fileWriteSpy.mock.calls.map(([line]) => String(line)).join('\n');
|
||||
expect(persisted).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|trace-password|trace-json-auth/,
|
||||
);
|
||||
});
|
||||
|
||||
it('returns the complete retained normal and TRACE snapshot in record order', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
const log = fresh.createLogger('Export');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
log.info('normal-before');
|
||||
log.trace('trace-hex=001122aabbcc');
|
||||
log.warn('normal-after');
|
||||
|
||||
expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual(['normal-after']);
|
||||
expect(fresh.getLogSnapshot().map((entry) => entry.message)).toEqual([
|
||||
'normal-before',
|
||||
'trace-hex=001122aabbcc',
|
||||
'normal-after',
|
||||
]);
|
||||
});
|
||||
|
||||
it('prints bootstrap credentials only to the current process terminal', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('error');
|
||||
fresh.setLogLevel('error');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const snapshotBefore = fresh.getLogSnapshot();
|
||||
const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
|
||||
try {
|
||||
fresh.logInitialWebuiCredentials('secret');
|
||||
|
||||
expect(stdout).toHaveBeenCalledWith(
|
||||
expect.stringContaining('initial credentials: user=admin password=secret'),
|
||||
);
|
||||
expect(entries).toEqual([]);
|
||||
expect(fresh.getLogSnapshot()).toEqual(snapshotBefore);
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
unsubscribe();
|
||||
stdout.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,33 +2,33 @@ import { describe, expect, it } from 'vitest';
|
||||
import { currentRequestId, nextRequestId, runWithRequestId } from '../src/request-context';
|
||||
|
||||
describe('request-context', () => {
|
||||
it('nextRequestId increments monotonically and stays a positive integer', () => {
|
||||
const a = nextRequestId();
|
||||
const b = nextRequestId();
|
||||
expect(a).toBeGreaterThan(0);
|
||||
expect(b).toBe(a + 1);
|
||||
});
|
||||
|
||||
it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
|
||||
runWithRequestId(42, () => {
|
||||
expect(currentRequestId()).toBe(42);
|
||||
runWithRequestId(99, () => {
|
||||
expect(currentRequestId()).toBe(99);
|
||||
});
|
||||
expect(currentRequestId()).toBe(42); // outer scope restored after the nested one
|
||||
it('nextRequestId increments monotonically and stays a positive integer', () => {
|
||||
const a = nextRequestId();
|
||||
const b = nextRequestId();
|
||||
expect(a).toBeGreaterThan(0);
|
||||
expect(b).toBe(a + 1);
|
||||
});
|
||||
|
||||
expect(currentRequestId()).toBeUndefined(); // cleared outside any scope
|
||||
it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
|
||||
await runWithRequestId(7, async () => {
|
||||
await Promise.resolve();
|
||||
expect(currentRequestId()).toBe(7); // survives awaits in the same async chain
|
||||
runWithRequestId(42, () => {
|
||||
expect(currentRequestId()).toBe(42);
|
||||
runWithRequestId(99, () => {
|
||||
expect(currentRequestId()).toBe(99);
|
||||
});
|
||||
expect(currentRequestId()).toBe(42); // outer scope restored after the nested one
|
||||
});
|
||||
|
||||
expect(currentRequestId()).toBeUndefined(); // cleared outside any scope
|
||||
|
||||
await runWithRequestId(7, async () => {
|
||||
await Promise.resolve();
|
||||
expect(currentRequestId()).toBe(7); // survives awaits in the same async chain
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the callback result', () => {
|
||||
expect(runWithRequestId(1, () => 'value')).toBe('value');
|
||||
});
|
||||
it('returns the callback result', () => {
|
||||
expect(runWithRequestId(1, () => 'value')).toBe('value');
|
||||
});
|
||||
});
|
||||
@@ -4,199 +4,226 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime';
|
||||
|
||||
describe('normalizeRuntimeConfig', () => {
|
||||
it('applies all defaults for an empty object', () => {
|
||||
expect(normalizeRuntimeConfig({})).toEqual({
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: false },
|
||||
trustProxy: '',
|
||||
logMaxTotalMb: 1024,
|
||||
logRetainDays: 7,
|
||||
logPerUin: false,
|
||||
it('applies all defaults for an empty object', () => {
|
||||
expect(normalizeRuntimeConfig({})).toEqual({
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: false },
|
||||
trustProxy: '',
|
||||
logMaxTotalMb: 1024,
|
||||
logRetainDays: 7,
|
||||
logPerUin: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('passes through valid values', () => {
|
||||
expect(normalizeRuntimeConfig({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
})).toEqual({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
it('passes through valid values', () => {
|
||||
expect(
|
||||
normalizeRuntimeConfig({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
}),
|
||||
).toEqual({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back on invalid types', () => {
|
||||
const out = normalizeRuntimeConfig({
|
||||
webuiPort: 0, // out of range → default
|
||||
webuiHost: 123, // non-string → default
|
||||
webuiTls: 'yes', // non-object → default
|
||||
trustProxy: 5, // non-string → default
|
||||
it('falls back on invalid types', () => {
|
||||
const out = normalizeRuntimeConfig({
|
||||
webuiPort: 0, // out of range → default
|
||||
webuiHost: 123, // non-string → default
|
||||
webuiTls: 'yes', // non-object → default
|
||||
trustProxy: 5, // non-string → default
|
||||
});
|
||||
expect(out.webuiPort).toBe(5099);
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: false });
|
||||
expect(out.trustProxy).toBe('');
|
||||
});
|
||||
expect(out.webuiPort).toBe(5099);
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: false });
|
||||
expect(out.trustProxy).toBe('');
|
||||
});
|
||||
|
||||
it('fails fast on invalid persisted log settings', () => {
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 }))
|
||||
.toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: -1 }))
|
||||
.toThrow(/logRetainDays/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' }))
|
||||
.toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: '' }))
|
||||
.toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER }))
|
||||
.toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER }))
|
||||
.toThrow(/logRetainDays/);
|
||||
});
|
||||
it('fails fast on invalid persisted log settings', () => {
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 })).toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: -1 })).toThrow(/logRetainDays/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' })).toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: '' })).toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER })).toThrow(
|
||||
/logMaxTotalMb/,
|
||||
);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER })).toThrow(
|
||||
/logRetainDays/,
|
||||
);
|
||||
});
|
||||
|
||||
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
|
||||
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true });
|
||||
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('127.0.0.1');
|
||||
});
|
||||
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
|
||||
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({
|
||||
enabled: true,
|
||||
});
|
||||
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('127.0.0.1');
|
||||
});
|
||||
|
||||
it('rejects a non-object input back to full defaults', () => {
|
||||
expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099);
|
||||
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('127.0.0.1');
|
||||
});
|
||||
it('rejects a non-object input back to full defaults', () => {
|
||||
expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099);
|
||||
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('127.0.0.1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveRuntimeEnvOverrides', () => {
|
||||
it('returns empty when no SNOWLUMA_* vars are set', () => {
|
||||
expect(resolveRuntimeEnvOverrides({})).toEqual({});
|
||||
});
|
||||
|
||||
it('parses port / host / trustProxy from env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_WEBUI_PORT: '6700',
|
||||
SNOWLUMA_WEBUI_HOST: '127.0.0.1',
|
||||
SNOWLUMA_WEBUI_TRUST_PROXY: '1',
|
||||
})).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
|
||||
});
|
||||
|
||||
it('parses log storage overrides including retainDays=0', () => {
|
||||
expect(resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '4096',
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '0',
|
||||
SNOWLUMA_LOG_PER_UIN: '1',
|
||||
})).toEqual({
|
||||
logMaxTotalMb: 4096,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
it('returns empty when no SNOWLUMA_* vars are set', () => {
|
||||
expect(resolveRuntimeEnvOverrides({})).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
it('fails fast on invalid log storage overrides', () => {
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '0',
|
||||
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '-1',
|
||||
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_PER_UIN: 'maybe',
|
||||
})).toThrow(/SNOWLUMA_LOG_PER_UIN/);
|
||||
});
|
||||
|
||||
it('fails fast when converted log storage overrides would be unsafe', () => {
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER),
|
||||
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER),
|
||||
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
});
|
||||
|
||||
it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '1' })).toEqual({
|
||||
webuiTls: { enabled: true },
|
||||
it('parses port / host / trustProxy from env', () => {
|
||||
expect(
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_WEBUI_PORT: '6700',
|
||||
SNOWLUMA_WEBUI_HOST: '127.0.0.1',
|
||||
SNOWLUMA_WEBUI_TRUST_PROXY: '1',
|
||||
}),
|
||||
).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
|
||||
});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({
|
||||
webuiTls: { enabled: false },
|
||||
|
||||
it('parses log storage overrides including retainDays=0', () => {
|
||||
expect(
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '4096',
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '0',
|
||||
SNOWLUMA_LOG_PER_UIN: '1',
|
||||
}),
|
||||
).toEqual({
|
||||
logMaxTotalMb: 4096,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
});
|
||||
});
|
||||
expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' }))
|
||||
.toThrow(/SNOWLUMA_WEBUI_TLS/);
|
||||
});
|
||||
|
||||
it('ignores an out-of-range / non-numeric port env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
|
||||
});
|
||||
it('fails fast on invalid log storage overrides', () => {
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '0',
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '-1',
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_PER_UIN: 'maybe',
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_PER_UIN/);
|
||||
});
|
||||
|
||||
it('treats trustProxy="0"/"off" as a real override (not absent)', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' });
|
||||
});
|
||||
it('fails fast when converted log storage overrides would be unsafe', () => {
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER),
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER),
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
});
|
||||
|
||||
it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '1' })).toEqual({
|
||||
webuiTls: { enabled: true },
|
||||
});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({
|
||||
webuiTls: { enabled: false },
|
||||
});
|
||||
expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' })).toThrow(
|
||||
/SNOWLUMA_WEBUI_TLS/,
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores an out-of-range / non-numeric port env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
|
||||
});
|
||||
|
||||
it('treats trustProxy="0"/"off" as a real override (not absent)', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({
|
||||
trustProxy: '0',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateRuntimeConfig (fs)', () => {
|
||||
let prevCwd: string;
|
||||
let dir: string;
|
||||
let prevPortEnv: string | undefined;
|
||||
beforeEach(async () => {
|
||||
const fs = await import('fs'); const os = await import('os'); const path = await import('path');
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-'));
|
||||
prevCwd = process.cwd();
|
||||
process.chdir(dir);
|
||||
prevPortEnv = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
});
|
||||
afterEach(async () => {
|
||||
process.chdir(prevCwd);
|
||||
if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
let prevCwd: string;
|
||||
let dir: string;
|
||||
let prevPortEnv: string | undefined;
|
||||
beforeEach(async () => {
|
||||
const fs = await import('fs');
|
||||
const os = await import('os');
|
||||
const path = await import('path');
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-'));
|
||||
prevCwd = process.cwd();
|
||||
process.chdir(dir);
|
||||
prevPortEnv = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
});
|
||||
afterEach(async () => {
|
||||
process.chdir(prevCwd);
|
||||
|
||||
it('merges a patch over on-disk values and persists normalized', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } });
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: true });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiHost).toBe('127.0.0.1');
|
||||
expect(onDisk.webuiTls).toEqual({ enabled: true });
|
||||
});
|
||||
if (prevPortEnv === undefined) {
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
} else {
|
||||
process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
|
||||
}
|
||||
|
||||
it('does NOT bake an env-overridden port into the persisted file', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
process.env.SNOWLUMA_WEBUI_PORT = '9999';
|
||||
updateRuntimeConfig({ webuiHost: '127.0.0.1' });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999
|
||||
});
|
||||
|
||||
it('keeps the previous runtime file intact when atomic replacement fails', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
updateRuntimeConfig({ logRetainDays: 7 });
|
||||
const runtimePath = path.join('config', 'runtime.json');
|
||||
const before = fs.readFileSync(runtimePath, 'utf8');
|
||||
vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
|
||||
throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' });
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
expect(() => updateRuntimeConfig({ logRetainDays: 0 }))
|
||||
.toThrow(/disk replacement failed/);
|
||||
expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before);
|
||||
expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]);
|
||||
});
|
||||
it('merges a patch over on-disk values and persists normalized', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs');
|
||||
const path = await import('path');
|
||||
const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } });
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: true });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiHost).toBe('127.0.0.1');
|
||||
expect(onDisk.webuiTls).toEqual({ enabled: true });
|
||||
});
|
||||
|
||||
it('does NOT bake an env-overridden port into the persisted file', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs');
|
||||
const path = await import('path');
|
||||
process.env.SNOWLUMA_WEBUI_PORT = '9999';
|
||||
updateRuntimeConfig({ webuiHost: '127.0.0.1' });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999
|
||||
});
|
||||
|
||||
it('keeps the previous runtime file intact when atomic replacement fails', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
updateRuntimeConfig({ logRetainDays: 7 });
|
||||
const runtimePath = path.join('config', 'runtime.json');
|
||||
const before = fs.readFileSync(runtimePath, 'utf8');
|
||||
vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
|
||||
throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' });
|
||||
});
|
||||
|
||||
expect(() => updateRuntimeConfig({ logRetainDays: 0 })).toThrow(/disk replacement failed/);
|
||||
expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before);
|
||||
expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -3,129 +3,202 @@ import { createSingleFlightCache } from '../src/single-flight-cache';
|
||||
|
||||
/** A promise whose resolve/reject is exposed, for driving single-flight races. */
|
||||
function deferred<T>() {
|
||||
let resolve!: (v: T) => void;
|
||||
let reject!: (e: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
|
||||
return { promise, resolve, reject };
|
||||
let resolve!: (v: T) => void;
|
||||
let reject!: (e: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
describe('SingleFlightCache', () => {
|
||||
it('caches within the TTL and reloads once expired', async () => {
|
||||
let clock = 1000;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 100, load, now: () => clock });
|
||||
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');
|
||||
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
clock = 1050; // still fresh (< 100)
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
cache[operation]('key');
|
||||
const second = cache.get('key');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
clock = 1101; // 101ms since store → expired
|
||||
expect(await cache.get('a')).toBe('a@1101');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
old.resolve('old');
|
||||
await expect(first).resolves.toBe('old');
|
||||
expect(cache.get('key')).toBe(second);
|
||||
|
||||
it('de-dupes concurrent callers onto a single load (single-flight)', async () => {
|
||||
const d = deferred<string>();
|
||||
const load = vi.fn(() => d.promise);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
|
||||
current.resolve('current');
|
||||
await expect(second).resolves.toBe('current');
|
||||
await expect(cache.get('key')).resolves.toBe('current');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
},
|
||||
);
|
||||
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
const p3 = cache.get('k');
|
||||
expect(load).toHaveBeenCalledTimes(1); // only one load in flight
|
||||
it('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');
|
||||
|
||||
d.resolve('v');
|
||||
expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keys independently — different keys load separately', async () => {
|
||||
const load = vi.fn(async (k: number) => k * 2);
|
||||
const cache = createSingleFlightCache<number, number>({ ttlMs: 1000, load });
|
||||
expect(await cache.get(1)).toBe(2);
|
||||
expect(await cache.get(2)).toBe(4);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('force bypasses the freshness check but still joins an in-flight load', async () => {
|
||||
let clock = 0;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load, now: () => clock });
|
||||
|
||||
expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh
|
||||
clock = 5; // still fresh
|
||||
expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// force still single-flights: two concurrent forced gets share one load.
|
||||
const d = deferred<string>();
|
||||
load.mockImplementationOnce(() => d.promise);
|
||||
const p1 = cache.get('a', { force: true });
|
||||
const p2 = cache.get('a', { force: true });
|
||||
expect(load).toHaveBeenCalledTimes(3); // not 4
|
||||
d.resolve('shared');
|
||||
expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']);
|
||||
});
|
||||
|
||||
it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => {
|
||||
let n = 0;
|
||||
const load = vi.fn(async () => ({ error: true as boolean, n: ++n }));
|
||||
const cache = createSingleFlightCache({ ttlMs: 10_000, load, shouldCache: (v) => !v.error });
|
||||
|
||||
// concurrent callers still share one load...
|
||||
const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]);
|
||||
expect(a).toEqual({ error: true, n: 1 });
|
||||
expect(b).toEqual({ error: true, n: 1 });
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
// ...but nothing was cached, so the next call reloads.
|
||||
expect(await cache.get('k')).toEqual({ error: true, n: 2 });
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// a good result IS cached.
|
||||
load.mockImplementationOnce(async () => ({ error: false, n: ++n }));
|
||||
const good = await cache.get('k');
|
||||
expect(good).toEqual({ error: false, n: 3 });
|
||||
expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => {
|
||||
let attempt = 0;
|
||||
const load = vi.fn(async () => {
|
||||
attempt++;
|
||||
if (attempt === 1) throw new Error('boom');
|
||||
return 'ok';
|
||||
await expect(cache.get('key')).resolves.toBe('current');
|
||||
old.resolve('old');
|
||||
await first;
|
||||
await expect(cache.get('key')).resolves.toBe('current');
|
||||
});
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
await expect(p1).rejects.toThrow('boom');
|
||||
await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
it('caches within the TTL and reloads once expired', async () => {
|
||||
let clock = 1000;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({
|
||||
ttlMs: 100,
|
||||
load,
|
||||
now: () => clock,
|
||||
});
|
||||
|
||||
// in-flight cleared + not cached → next call retries and succeeds.
|
||||
expect(await cache.get('k')).toBe('ok');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
clock = 1050; // still fresh (< 100)
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
it('invalidate drops a cached entry; clear drops all', async () => {
|
||||
const load = vi.fn(async (k: string) => k.toUpperCase());
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
clock = 1101; // 101ms since store → expired
|
||||
expect(await cache.get('a')).toBe('a@1101');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
cache.invalidate('a');
|
||||
await cache.get('a'); // reloads
|
||||
await cache.get('b'); // still cached
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
it('de-dupes concurrent callers onto a single load (single-flight)', async () => {
|
||||
const d = deferred<string>();
|
||||
const load = vi.fn(() => d.promise);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
|
||||
|
||||
cache.clear();
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
const p3 = cache.get('k');
|
||||
expect(load).toHaveBeenCalledTimes(1); // only one load in flight
|
||||
|
||||
d.resolve('v');
|
||||
expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keys independently — different keys load separately', async () => {
|
||||
const load = vi.fn(async (k: number) => k * 2);
|
||||
const cache = createSingleFlightCache<number, number>({ ttlMs: 1000, load });
|
||||
expect(await cache.get(1)).toBe(2);
|
||||
expect(await cache.get(2)).toBe(4);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('force bypasses the freshness check but still joins an in-flight load', async () => {
|
||||
let clock = 0;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({
|
||||
ttlMs: 10_000,
|
||||
load,
|
||||
now: () => clock,
|
||||
});
|
||||
|
||||
expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh
|
||||
clock = 5; // still fresh
|
||||
expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// force still single-flights: two concurrent forced gets share one load.
|
||||
const d = deferred<string>();
|
||||
load.mockImplementationOnce(() => d.promise);
|
||||
const p1 = cache.get('a', { force: true });
|
||||
const p2 = cache.get('a', { force: true });
|
||||
expect(load).toHaveBeenCalledTimes(3); // not 4
|
||||
d.resolve('shared');
|
||||
expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']);
|
||||
});
|
||||
|
||||
it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => {
|
||||
let n = 0;
|
||||
const load = vi.fn(async () => ({ error: true as boolean, n: ++n }));
|
||||
const cache = createSingleFlightCache({
|
||||
ttlMs: 10_000,
|
||||
load,
|
||||
shouldCache: (v) => !v.error,
|
||||
});
|
||||
|
||||
// concurrent callers still share one load...
|
||||
const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]);
|
||||
expect(a).toEqual({ error: true, n: 1 });
|
||||
expect(b).toEqual({ error: true, n: 1 });
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
// ...but nothing was cached, so the next call reloads.
|
||||
expect(await cache.get('k')).toEqual({ error: true, n: 2 });
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// a good result IS cached.
|
||||
load.mockImplementationOnce(async () => ({ error: false, n: ++n }));
|
||||
const good = await cache.get('k');
|
||||
expect(good).toEqual({ error: false, n: 3 });
|
||||
expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => {
|
||||
let attempt = 0;
|
||||
const load = vi.fn(async () => {
|
||||
attempt++;
|
||||
|
||||
if (attempt === 1) {
|
||||
throw new Error('boom');
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
});
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
await expect(p1).rejects.toThrow('boom');
|
||||
await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
// in-flight cleared + not cached → next call retries and succeeds.
|
||||
expect(await cache.get('k')).toBe('ok');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('invalidate drops a cached entry; clear drops all', async () => {
|
||||
const load = vi.fn(async (k: string) => k.toUpperCase());
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
cache.invalidate('a');
|
||||
await cache.get('a'); // reloads
|
||||
await cache.get('b'); // still cached
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
|
||||
cache.clear();
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 1116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user