Compare commits

..

7 Commits

Author SHA1 Message Date
DrSmoothl
adf6b6a3b4 test(protocol): isolate upload staging fixtures
Give cleanup tests a dedicated staging directory so they cannot remove files used by parallel upload tests.

Refs #520
2026-10-13 10:08:20 +08:00
DrSmoothl
5a0b26648c test(onebot): use async connections in migration fixtures
Use the production SQLite driver for concurrent migration checks while preserving history, index, and restart assertions.

Refs #520
2026-10-13 10:08:15 +08:00
DrSmoothl
a50df4e526 style(webui): preserve hook lint suppression after formatting
Keep the existing dependency annotation on the line checked by ESLint.
2026-10-13 10:00:55 +08:00
DrSmoothl
505b4772d6 test(core): align lock fixtures with async persistence
Exercise persistence failures and retries with the production database connection, and finish fixture writes before acquiring test locks.

Refs #520
2026-10-13 10:00:55 +08:00
DrSmoothl
927e03d435 test(sqlite): verify real lock contention across platforms
Use consistent database connections and prove write contention before checking event-loop responsiveness. Keep cleanup deterministic when an assertion fails.

Refs #520
2026-10-13 09:57:25 +08:00
DrSmoothl
056188d63d chore: resolve async SQLite merge conflicts
Integrate the current development branch, preserve the album comment fixes, and align the changes with repository formatting and dependency tooling.
2026-10-13 09:55:16 +08:00
手瓜一十雪
e699351f90 feat: adopt async SQLite and improve messaging and runtime diagnostics 2026-10-12 15:44:55 +08:00
294 changed files with 7901 additions and 15969 deletions

View File

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

View File

@@ -4,7 +4,6 @@ name: CI
on:
pull_request:
workflow_dispatch:
permissions:
contents: read

View File

@@ -136,6 +136,13 @@ 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

View File

@@ -85,6 +85,10 @@ 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

View File

@@ -16,7 +16,7 @@ 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, local account/login detection, Hook sessions, native transport lifecycle |
| `packages/bridge` | QQ process discovery, 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 |
@@ -33,17 +33,11 @@ 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` |

View File

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

View File

@@ -12,7 +12,7 @@
<p align="center">
<a href="#快速开始">快速开始</a> ·
<a href="https://snowluma.github.io/zh/docs/api">动作参考</a> ·
<a href="./docs/onebot-actions.md">动作参考</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 24+。
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载对应平台的完整发行包并解压。Lite 版需 Node.js 22.13+(23 系需 23.4+)。
2. Windows 运行 `launcher.bat`;Linux 执行:
```bash
@@ -53,14 +53,11 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生
3. 打开 [`http://localhost:5099`](http://localhost:5099),使用启动日志中的初始密码登录 WebUI,按引导接入 QQ 进程并配置 OneBot 连接。
账号识别由登录数据库的文件变化、进程和登录事件或手动操作触发,不做周期探测。未载入的 QQ 进程也不会持续调用 Windows Restart Manager;需要重查时可点击 WebUI 进程行的刷新/重连。
## 接入与文档
| 入口 | 文档 |
| --- | --- |
| WebSocket / HTTP | [OneBot 动作参考](https://snowluma.github.io/zh/docs/api) |
| 部署(Docker / Windows) | [部署指南](https://snowluma.github.io/zh/docs/guide/deploy) |
| WebSocket / HTTP | [OneBot 动作参考](docs/onebot-actions.md) |
| TypeScript SDK | [`packages/sdk/README.md`](packages/sdk/README.md) |
| MCP | [`packages/mcp/README.md`](packages/mcp/README.md) |
@@ -68,7 +65,7 @@ JSON 消息段接受标准的 `data.data` 字符串,也兼容 `data.data` 非
## 开发
需要 Node.js 24+ 与 pnpm 11.25.0,日常开发基于 `dev` 分支:
需要 Node.js 22.13+(23 系需 23.4+)与 pnpm 10.28.0,日常开发基于 `dev` 分支:
```bash
git clone https://github.com/SnowLuma/SnowLuma.git
@@ -81,6 +78,18 @@ pnpm test
贡献流程见 [`CONTRIBUTING.md`](CONTRIBUTING.md);模块边界与项目词汇见 [`CONTEXT.md`](CONTEXT.md);开发方向见 [`RoadMap.md`](RoadMap.md)。
## 引用消息预览
OneBot 发送 `reply` 段时,会将本地消息缓存中的原文附入 QQ 引用预览,保留文字、换行与引用关系。图片、语音等非文字段以类型提示显示,不重新上传媒体;原消息中的嵌套引用不递归展开。只有消息元数据而没有缓存正文时,不生成虚构的预览内容。
## 媒体读取与归档
`get_msg` 逐个尝试刷新图片、语音和视频的下载地址:获取到新地址就用于本次响应,刷新失败或缺少资源元数据时保留该段原地址,并继续处理其他资源。原地址为空时仍保持为空,单个资源失败不影响整条消息返回。地址更新时同步响应中的 `raw_message`,不改写保存的消息;保留的旧地址仍可能已经过期。
`get_record` 单独向 QQ 获取语音的当前下载地址,资源元数据缺失或远端获取失败时动作返回错误,不使用旧地址或发送时的本地文件兜底。历史记录若没有保存资源引用,无法仅凭文件名恢复下载地址。
SnowLuma 不为这些查询长期保存媒体文件或 Base64 内容,本地保留的是消息及资源元数据;上传、转码仍会使用临时文件。下载地址和 QQ 远端资源都有可用性限制,需要长期归档的消费端应及时下载并自行保存。
## 使用边界与许可
> [!IMPORTANT]

View File

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

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "2.0.3",
"version": "1.14.22",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",

View File

@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "2.0.3",
"version": "1.14.22",
"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-account": {
"types": "./src/qq-account/index.ts",
"default": "./src/qq-account/index.ts"
"./qq-port-probe": {
"types": "./src/qq-port-probe.ts",
"default": "./src/qq-port-probe.ts"
},
"./types": {
"types": "./src/types.ts",
@@ -54,8 +54,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/common": "workspace:*",
"@snowluma/sqlite": "workspace:*"
"@snowluma/common": "workspace:*"
},
"devDependencies": {
"@types/node": "catalog:",

View File

@@ -1,4 +1,3 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, runWithTraceRequest, type Logger } from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { PacketSender } from '@snowluma/common/packet-sender';
@@ -8,18 +7,15 @@ import { HookSession, type HookSessionDeps } from './hook-session';
import {
injectHookProcess,
listHookProcesses,
resolveHookNativePath,
unloadHookProcess,
type HookProcessBaseInfo,
} from './injector';
import { PipeWatcher } from './pipe-watcher';
import { createProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
import { QqHookClient } from './qq-hook-client';
import {
detectAccountLoginsForPids,
watchAccountChangesForPids,
type AccountLoginState,
} from './qq-account';
import type { HookProcessAccount, HookProcessInfo } from './types';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import type { HookProcessInfo } from './types';
const AUTO_LOAD_MAX_ATTEMPTS = 3;
@@ -57,14 +53,7 @@ export type HookManagerDeps = {
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
watcherIntervalMs?: number;
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
listProcesses?: () => Promise<HookProcessBaseInfo[]>;
/** Local account detection used to label each process with the account QQ is
* signed in as. Receives the pids to label so each one is resolved against
* the HOME it actually runs under (a container can give every QQ instance
* its own). Defaults to reading QQ's own account data. */
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
/** Subscribe to login database changes. Returns the subscription cleanup. */
watchAccounts?: (pids: readonly number[], onChange: () => void) => () => void;
listProcesses?: () => HookProcessBaseInfo[];
/** When true, every newly-discovered QQ process is auto-injected (fires
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
* Failed loads are logged and leave the session in the 'error' state.
@@ -105,9 +94,13 @@ export class HookManager {
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly pipeWatcher: PipeWatcher;
private readonly ownsPipeWatcher: boolean;
private readonly enumerator: ProcessEnumerator;
private readonly detectAccounts: (pids: readonly number[]) => Promise<AccountLoginState[]>;
private readonly watchAccounts: NonNullable<HookManagerDeps['watchAccounts']>;
/** Watcher/API process enumeration — isolated + timeout-bounded by default
* so a blocked native /proc walk can't freeze the loop (issue #158).
* Resolves to `null` (UNKNOWN) on timeout/failure. */
private readonly enumerate: () => Promise<HookProcessBaseInfo[] | null>;
/** The owned enumerator (worker lifecycle), or null when a custom lister was
* injected (tests) — nothing to tear down in that case. */
private readonly enumerator: ProcessEnumerator | null;
private readonly autoLoadOnDiscovery: boolean;
private readonly onSessionsChangedRaw?: () => void;
private readonly log: Logger;
@@ -115,12 +108,6 @@ export class HookManager {
private readonly autoLoadAttempts = new Map<number, AutoLoadAttempt>();
private readonly startPromise: Promise<void>;
private accounts = new Map<number, HookProcessAccount>();
private accountProbe: Promise<void> | null = null;
private accountsDirty = true;
private stopWatchingAccounts?: () => void;
private lastAccountProbeFailure = '';
private disposed = false;
constructor(deps: HookManagerDeps) {
@@ -131,26 +118,48 @@ export class HookManager {
this.injector = deps.injector ?? {
inject: injectHookProcess,
unload: unloadHookProcess,
unload: (pid, handle) => {
if (!handle) {
return;
}
unloadHookProcess(pid, handle);
},
};
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
this.detectAccounts = deps.detectAccounts ?? detectAccountLoginsForPids;
this.watchAccounts =
deps.watchAccounts ??
((pids, onChange) => watchAccountChangesForPids(pids, onChange, this.log));
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
this.enumerator = createProcessEnumerator({
listProcesses: deps.listProcesses ?? listHookProcesses,
log: this.log,
});
// A custom lister (tests) is used directly — no worker, no isolation, just
// an async wrap that maps a throw to the UNKNOWN sentinel. The default path
// wraps the native enumerator in a worker with a timeout.
if (deps.listProcesses) {
const lister = deps.listProcesses;
this.enumerator = null;
this.enumerate = async () => {
try {
return await lister();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
return null;
}
};
} else {
this.enumerator = createNativeProcessEnumerator({
addonPath: resolveHookNativePath('node'),
fallbackSync: listHookProcesses,
processName: defaultProcessName(),
log: this.log,
});
this.enumerate = () => this.enumerator!.enumerate();
}
if (deps.pipeWatcher) {
this.pipeWatcher = deps.pipeWatcher;
this.ownsPipeWatcher = false;
} else {
this.pipeWatcher = new PipeWatcher({
listProcesses: this.enumerator.enumerate,
listProcesses: this.enumerate,
listLivePipes: (processes) =>
QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
intervalMs: deps.watcherIntervalMs,
@@ -167,21 +176,23 @@ export class HookManager {
async listProcesses(): Promise<HookProcessInfo[]> {
await this.startPromise;
const processes = await this.enumerator.enumerate();
// A failed enumeration preserves the last known process set.
const sessions =
processes === null
? [...this.sessions.values()]
: processes.map((proc) => {
const session = this.ensureSession(proc.pid);
session.attachProcessInfo(proc);
return session;
});
await this.refreshAccounts();
return sessions
.filter((session) => this.sessions.get(session.pid) === session)
.map((session) => this.processInfo(session))
.sort((a, b) => a.pid - b.pid);
const processes = await this.enumerate();
if (processes === null) {
// Enumeration timed out / failed — report the last-known sessions rather
// than an empty list (which the WebUI would render as "no QQ").
return [...this.sessions.values()].map((s) => s.toInfo()).sort((a, b) => a.pid - b.pid);
}
const result: HookProcessInfo[] = [];
for (const proc of processes) {
const session = this.ensureSession(proc.pid);
session.attachProcessInfo(proc);
result.push(session.toInfo());
}
return result.sort((a, b) => a.pid - b.pid);
}
async loadProcess(pid: number): Promise<HookProcessInfo> {
@@ -189,11 +200,11 @@ export class HookManager {
await this.startPromise;
this.autoLoadAttempts.delete(pid);
const session = this.ensureSession(pid);
this.invalidateAccounts();
await session.load();
const info = await session.load();
// Pull the next tick forward so a freshly-injected pipe gets noticed
// within the next event-loop turn instead of after the full interval.
this.pipeWatcher.wake();
await this.refreshAccounts();
return this.processInfo(session);
return info;
}
async unloadProcess(pid: number): Promise<HookProcessInfo> {
@@ -201,21 +212,19 @@ export class HookManager {
await this.startPromise;
this.autoLoadAttempts.delete(pid);
const session = this.ensureSession(pid);
this.invalidateAccounts();
await session.unload();
await this.refreshAccounts();
return this.processInfo(session);
return session.unload();
}
async refreshProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
this.updateAccountWatcher();
this.invalidateAccounts();
await session.refresh();
await this.refreshAccounts();
return this.processInfo(session);
return session.refresh();
}
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
this.assertValidPid(pid);
return probeQqLoginInfo(pid);
}
dispose(): void {
@@ -224,16 +233,14 @@ export class HookManager {
}
this.disposed = true;
this.stopWatchingAccounts?.();
for (const session of this.sessions.values()) {
session.dispose();
}
this.sessions.clear();
this.accounts.clear();
this.autoLoadAttempts.clear();
this.enumerator.dispose();
this.enumerator?.dispose();
if (this.ownsPipeWatcher) {
this.pipeWatcher.dispose();
@@ -242,87 +249,6 @@ export class HookManager {
// ─────────────── wiring ───────────────
private processInfo(session: HookSession): HookProcessInfo {
return { ...session.toInfo(), account: this.accounts.get(session.pid) ?? null };
}
private invalidateAccounts(): void {
this.accountsDirty = true;
}
private updateAccountWatcher(): void {
this.stopWatchingAccounts?.();
this.stopWatchingAccounts = this.watchAccounts([...this.sessions.keys()], () => {
this.invalidateAccounts();
void this.refreshAccounts();
});
}
/** REST, watcher ticks and login reconciliation share the same account snapshot. */
private async refreshAccounts(): Promise<void> {
if (this.disposed || this.sessions.size === 0) {
return;
}
if (this.accountProbe) {
await this.accountProbe;
return;
}
if (!this.accountsDirty) {
return;
}
this.accountProbe = runWithTraceRequest(async () => {
// All callers await the replacement read too if a lifecycle change
// invalidates an in-flight result.
do {
this.accountsDirty = false;
await this.readAccounts();
} while (!this.disposed && this.sessions.size > 0 && this.accountsDirty);
}).finally(() => {
this.accountProbe = null;
});
await this.accountProbe;
}
private async readAccounts(): Promise<void> {
const accounts = new Map<number, HookProcessAccount>();
try {
for (const state of await this.detectAccounts([...this.sessions.keys()])) {
if (state.pid !== null && this.sessions.has(state.pid)) {
accounts.set(state.pid, { uin: state.uin, nickname: state.nickname });
}
}
this.lastAccountProbeFailure = '';
} catch (error) {
const message = errorMessage(error);
if (this.lastAccountProbeFailure !== message) {
this.lastAccountProbeFailure = message;
this.log.warn('account detection failed: %s', message);
}
}
if (this.disposed || this.accountsDirty) {
return;
}
const changed =
accounts.size !== this.accounts.size ||
[...accounts].some(([pid, account]) => {
const previous = this.accounts.get(pid);
return previous?.uin !== account.uin || previous.nickname !== account.nickname;
});
this.accounts = accounts;
if (changed) {
this.notifySessionsChanged();
}
}
private bindWatcher(): void {
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
if (this.disposed) {
@@ -379,7 +305,6 @@ export class HookManager {
const session = this.sessions.get(pid);
if (session) {
this.invalidateAccounts();
session.onPipeUp();
}
});
@@ -391,7 +316,6 @@ export class HookManager {
const session = this.sessions.get(pid);
if (session) {
this.invalidateAccounts();
session.onPipeDown();
}
});
@@ -414,8 +338,6 @@ export class HookManager {
return;
}
void this.refreshAccounts();
for (const session of this.sessions.values()) {
const autoLoad = this.autoLoadAttempts.get(session.pid);
@@ -558,10 +480,10 @@ export class HookManager {
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=unexpected_failure error=%j elapsedMs=%d',
session.pid,
attempt,
errorMessage(err),
errMsg(err),
Date.now() - startedAt,
);
this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errorMessage(err));
this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errMsg(err));
}
});
}
@@ -578,19 +500,12 @@ export class HookManager {
makeClient: this.makeClient,
pipeWatcher: this.pipeWatcher,
onPacket: this.onPacket,
detectLoginUin: async () => {
await this.refreshAccounts();
return this.accounts.get(pid)?.uin ?? null;
},
log: this.log,
});
session.attachProcessInfo({ name: defaultProcessName() });
session.on('login', (uin: string, sender) => {
// Account switches can keep the same 'online' status.
this.invalidateAccounts();
this.bridgeManager.onHookLogin(pid, uin, sender);
this.notifySessionsChanged();
});
session.on('disconnected', (wasLoggedIn: boolean) => {
if (wasLoggedIn) {
@@ -600,25 +515,17 @@ export class HookManager {
session.on('receive-health-changed', (healthy: boolean) => {
this.bridgeManager.onPidReceiveHealthChanged(pid, healthy);
});
let previousStatus = session.status;
session.on('status-changed', (status) => {
if (previousStatus === 'online' && status !== 'online') {
this.invalidateAccounts();
}
previousStatus = status;
// status-changed fires on EVERY internal status mutation, including the
// ones reached via login / disconnected / refresh — subscribing here
// alone covers every transition the WebUI processes view cares about.
session.on('status-changed', () => {
this.notifySessionsChanged();
});
session.on('disposed', () => {
this.sessions.delete(pid);
this.accounts.delete(pid);
this.updateAccountWatcher();
this.invalidateAccounts();
});
this.sessions.set(pid, session);
this.updateAccountWatcher();
this.invalidateAccounts();
return session;
}
@@ -637,7 +544,7 @@ export class HookManager {
try {
this.onSessionsChangedRaw();
} catch (err) {
this.log.warn('onSessionsChanged threw: %s', errorMessage(err));
this.log.warn('onSessionsChanged threw: %s', errMsg(err));
}
}
@@ -652,6 +559,10 @@ function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
function isTransientLibcMappingError(error: string): boolean {
return /^target process does not map \S*\/libc\.so\.6 while resolving mmap$/.test(error);
}
@@ -701,4 +612,5 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
}
export type { HookProcessBaseInfo } from './injector';
export type { HookProcessAccount, HookProcessInfo, HookProcessStatus } from './types';
export type { QqPortLoginInfo } from './qq-port-probe';
export type { HookProcessInfo, HookProcessStatus } from './types';

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,36 +1,55 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { EventEmitter } from 'node:events';
import { setImmediate as nextTurn } from 'node:timers/promises';
import { EventEmitter } from 'events';
import type { HookProcessBaseInfo } from './injector';
const DEFAULT_INTERVAL_MS = 1500;
const MIN_INTERVAL_MS = 250;
export type PipeWatcherDeps = {
/** 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. */
/** 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;
};
type PipeEvent =
| ['process-discovered', HookProcessBaseInfo]
| ['pipe-up' | 'pipe-down' | 'process-gone', number];
/** Publishes process and pipe snapshots, then emits their ordered differences. */
/**
* 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.
*/
export class PipeWatcher extends EventEmitter {
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
private readonly intervalMs: number;
private readonly log: Logger;
private livePipes = new Set<number>();
private knownPids = new Set<number>();
private timer: NodeJS.Timeout | null = null;
private tickTask: Promise<void> | null = null;
private pendingTick = false;
private ticking = false;
private pendingWake = false;
private startPromise: Promise<void> | null = null;
private stopped = false;
@@ -42,63 +61,51 @@ export class PipeWatcher extends EventEmitter {
this.log = deps.log ?? createLogger('PipeWatcher');
}
/** Was this PID's pipe live as of the last completed tick? */
isPipeLive(pid: number): boolean {
return this.livePipes.has(pid);
}
/** Was this PID alive as of the last completed tick? */
isProcessAlive(pid: number): boolean {
return this.knownPids.has(pid);
}
/** Read the initial snapshot and start polling. Repeated calls share startup. */
/**
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
* and begin the polling loop. Idempotent.
*/
start(): Promise<void> {
return (this.startPromise ??= this.tickNow().finally(() => {
this.scheduleNext(this.intervalMs);
}));
if (this.startPromise) {
return this.startPromise;
}
this.startPromise = (async () => {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
})();
return this.startPromise;
}
/** Coalesce wake requests into one scan after the current read. */
/** Pull the next scheduled tick forward to the next event-loop turn. */
wake(): void {
if (this.stopped) {
return;
}
if (this.tickTask) {
this.pendingTick = true;
} else {
this.scheduleNext(0);
}
this.scheduleNext(0);
}
/** Wait for a fresh snapshot, including a scan queued behind an active read. */
/** Force a single tick now. Resolves after diff events have been emitted. */
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;
return this.tickOnce();
}
stop(): void {
this.stopped = true;
this.pendingTick = false;
if (this.timer) {
clearTimeout(this.timer);
@@ -118,100 +125,139 @@ export class PipeWatcher extends EventEmitter {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
this.timer = null;
void this.tickAndReschedule();
}, delayMs);
this.timer = setTimeout(
() => {
this.timer = null;
void this.tickAndReschedule();
},
Math.max(0, delayMs),
);
}
private async tickAndReschedule(): Promise<void> {
try {
await this.tickNow();
} catch (error) {
this.log.warn('poll failed: %s', errorMessage(error));
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
}
private async readSnapshot(): Promise<void> {
let processes: HookProcessBaseInfo[] | null;
/**
* 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;
}
this.ticking = true;
try {
processes = await this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errorMessage(error));
processes = null;
}
let processes: HookProcessBaseInfo[] | 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]);
try {
processes = await this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = null;
}
}
for (const pid of currentPipes) {
if (!this.livePipes.has(pid)) {
events.push(['pipe-up', pid]);
}
}
// Disconnect pipes before disposing their departed processes.
for (const pid of this.livePipes) {
if (!currentPipes.has(pid)) {
events.push(['pipe-down', pid]);
}
}
for (const pid of this.knownPids) {
if (!knownPids.has(pid)) {
events.push(['process-gone', pid]);
}
}
this.knownPids = knownPids;
this.livePipes = currentPipes;
for (const [event, payload] of events) {
if (this.stopped) {
// 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;
}
this.emit(event, payload);
}
let livePipes: Set<number> | null;
if (!this.stopped) {
try {
livePipes = await this.listLivePipes(processes);
} catch (error) {
this.log.warn('listLivePipes failed: %s', errMsg(error));
livePipes = null;
}
const newKnownPids = new Set<number>();
for (const proc of processes) {
newKnownPids.add(proc.pid);
}
// 1. Newly discovered processes.
for (const proc of processes) {
if (!this.knownPids.has(proc.pid)) {
this.emit('process-discovered', proc);
}
}
// 2. Pipes that came up. Ignore pipes for processes we don't know
// about (would race against an out-of-order tick).
const newLivePipes = new Set<number>();
if (livePipes === null) {
// Keep the last known pipe state for processes that still exist, while
// allowing confirmed process exits to complete their normal teardown.
for (const pid of this.livePipes) {
if (newKnownPids.has(pid)) {
newLivePipes.add(pid);
}
}
} else {
for (const pid of livePipes) {
if (!newKnownPids.has(pid)) {
continue;
}
newLivePipes.add(pid);
if (!this.livePipes.has(pid)) {
this.emit('pipe-up', pid);
}
}
}
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
// subscribers can run disconnect logic before dispose logic.
for (const pid of this.livePipes) {
if (!newLivePipes.has(pid)) {
this.emit('pipe-down', pid);
}
}
// 4. Processes that disappeared.
for (const pid of this.knownPids) {
if (!newKnownPids.has(pid)) {
this.emit('process-gone', pid);
}
}
this.knownPids = newKnownPids;
this.livePipes = newLivePipes;
this.emit('tick');
} finally {
this.ticking = false;
if (this.pendingWake) {
this.pendingWake = false;
// Defer to break sync recursion if a listener calls wake().
setImmediate(() => {
void this.tickOnce();
});
}
}
}
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}

View File

@@ -1,77 +1,291 @@
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 {
/** null means unknown: keep the previous process set. */
/** 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;
}
interface ProcessEnumeratorDeps {
listProcesses: () => Promise<HookProcessBaseInfo[]>;
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;
}
export function createProcessEnumerator(deps: ProcessEnumeratorDeps): ProcessEnumerator {
const DEFAULT_TIMEOUT_MS = 4000;
const DEFAULT_MAX_ORPHANS = 4;
// Worker body (CommonJS — eval workers default to CJS so `require` is available;
// `process.dlopen` is a global and needs no module system). Loads the addon
// handed in via workerData, then answers each 'enumerate' with the raw pid list
// from the blocking native call. All the cheap post-processing stays on main.
const WORKER_SOURCE = `
const { parentPort, workerData } = require('node:worker_threads');
let addon = null;
try {
const mod = { exports: {} };
process.dlopen(mod, workerData.addonPath);
addon = mod.exports;
} catch (e) {
parentPort.postMessage({ type: 'fatal', error: String((e && e.message) || e) });
}
if (addon) {
parentPort.on('message', (msg) => {
if (!msg || msg.type !== 'enumerate') return;
try {
const pids = addon.getAllMainProcess();
parentPort.postMessage({ type: 'result', id: msg.id, pids: Array.from(pids) });
} catch (e) {
parentPort.postMessage({ type: 'error', id: msg.id, error: String((e && e.message) || e) });
}
});
parentPort.postMessage({ type: 'ready' });
}
`;
function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] {
return [...new Set(pids)]
.filter((pid) => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map((pid) => ({ pid, name: processName, path: '' }));
}
export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator {
const log = deps.log ?? createLogger('ProcessEnumerator');
const timeoutMs = deps.timeoutMs ?? 4000;
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
// fallback there is a cheap socket read, not a /proc walk.
if (!deps.addonPath) {
return {
async enumerate() {
try {
return deps.fallbackSync();
} catch (err) {
log.warn('enumerate fallback failed: %s', errMsg(err));
return null;
}
},
dispose() {
/* nothing to tear down */
},
};
}
const addonPath = deps.addonPath;
let worker: Worker | null = null;
/** Set once we learn the addon can't load in a worker — permanent fallback. */
let isolationBroken = false;
let orphans = 0;
let seq = 0;
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
let disposed = false;
let pending: {
promise: Promise<HookProcessBaseInfo[] | null>;
settle: (result: HookProcessBaseInfo[] | null) => void;
} | null = null;
const spawnWorker = (): void => {
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
worker = w;
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
if (msg.type === 'ready') {
return;
}
if (msg.type === 'fatal') {
// The addon won't load off-thread — give up on isolation for good and
// fall back to the synchronous path from here on. Resolve any in-flight
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
log.warn(
'process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration',
msg.error ?? '',
);
isolationBroken = true;
for (const { resolve } of pending.values()) {
resolve(null);
}
pending.clear();
teardownWorker();
return;
}
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
const entry = pending.get(msg.id);
if (!entry) {
return;
}
pending.delete(msg.id);
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
}
});
w.on('error', (err) => {
log.warn('enumeration worker error: %s', errMsg(err));
if (worker === w) {
teardownWorker();
}
});
};
const teardownWorker = (): void => {
const w = worker;
worker = null;
if (!w) {
return;
}
// 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 {
enumerate() {
if (disposed) {
return Promise.resolve(null);
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
if (disposed || isolationBroken) {
return syncFallback();
}
if (pending) {
return pending.promise;
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();
}
let resolve!: (result: HookProcessBaseInfo[] | null) => void;
const promise = new Promise<HookProcessBaseInfo[] | null>((done) => {
resolve = done;
const w = worker;
if (!w) {
return syncFallback();
}
const id = ++seq;
const resultPromise = new Promise<number[] | null>((resolve) => {
pending.set(id, { resolve });
});
const settle = (result: HookProcessBaseInfo[] | null) => {
clearTimeout(timer);
resolve(result);
};
try {
w.postMessage({ type: 'enumerate', id });
} catch (err) {
pending.delete(id);
log.warn('failed to post enumerate request: %s', errMsg(err));
teardownWorker();
return syncFallback();
}
const timer = setTimeout(() => {
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; keeping prior process set',
'process enumeration timed out after %dms (worker abandoned) — keeping prior process set',
timeoutMs,
);
settle(null);
}, timeoutMs);
pending = { promise, settle };
teardownWorker();
return null;
}
// 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;
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;
pending?.settle(null);
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);
}

View File

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

View File

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

View File

@@ -1,23 +0,0 @@
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 { watchAccountChangesForPids } from './watch';
export {
decryptDatabase,
detectAlgorithm,
type DecryptedDatabase,
type KdfHmacAlgorithm,
type PageHmacAlgorithm,
type SqlcipherAlgorithm,
} from './sqlcipher';

View File

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

View File

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

View File

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

View File

@@ -1,115 +0,0 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { watch, type FSWatcher } from 'node:fs';
import path from 'node:path';
import { loginDbPaths, qqDataRootsForPid } from './paths';
export function watchAccountChangesForPids(
pids: readonly number[],
onChange: () => void,
log: Logger = createLogger('QqAccount'),
): () => void {
const roots = new Set<string>();
for (const pid of pids) {
try {
for (const root of qqDataRootsForPid(pid)) {
roots.add(root);
}
} catch (error) {
log.warn('account watch root failed: PID=%d err=%s', pid, errorMessage(error));
}
}
return watchAccountFiles([...roots].flatMap(loginDbPaths), onChange, log);
}
/** Watch directories so replacing login.db or recreating its WAL keeps working. */
export function watchAccountFiles(
dbPaths: readonly string[],
onChange: () => void,
log: Logger = createLogger('QqAccount'),
): () => void {
const watchers = new Map<string, FSWatcher>();
let timer: NodeJS.Timeout | undefined;
const changed = () => {
clearTimeout(timer);
timer = setTimeout(() => {
timer = undefined;
onChange();
}, 250);
timer.unref();
};
const observe = (dbPath: string) => {
watchers.get(dbPath)?.close();
watchers.delete(dbPath);
const dbDirectory = path.dirname(dbPath);
let directory = dbDirectory;
for (;;) {
const target = path.relative(directory, dbPath).split(path.sep)[0]!;
try {
const watcher = watch(directory, { persistent: false }, (_event, filename) => {
if (
watchers.get(dbPath) !== watcher ||
(filename !== null &&
filename !== target &&
!(directory === dbDirectory && filename === `${target}-wal`))
) {
return;
}
// QQ may create its data directories after process discovery.
if (directory !== dbDirectory) {
observe(dbPath);
}
changed();
});
watcher.on('error', (error) => {
if (watchers.get(dbPath) !== watcher) {
return;
}
watcher.close();
watchers.delete(dbPath);
log.warn('account watch failed: path=%s err=%s', dbPath, errorMessage(error));
});
watchers.set(dbPath, watcher);
return;
} catch (error) {
const parent = path.dirname(directory);
if (
error instanceof Error &&
'code' in error &&
error.code === 'ENOENT' &&
parent !== directory
) {
directory = parent;
continue;
}
log.warn('account watch failed: path=%s err=%s', dbPath, errorMessage(error));
return;
}
}
};
for (const dbPath of new Set(dbPaths)) {
observe(dbPath);
}
return () => {
clearTimeout(timer);
for (const watcher of watchers.values()) {
watcher.close();
}
watchers.clear();
};
}

View File

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

View File

@@ -0,0 +1,293 @@
import { createLogger } from '@snowluma/common/logger';
import { exec } from 'child_process';
import http from 'http';
import https from 'https';
import { promisify } from 'util';
const execAsync = promisify(exec);
const log = createLogger('LoginProbe');
const probeNotes = new Map<number, string>();
function noteProbe(pid: number, result: string, ports: number, processes: number | null): void {
const processText = processes === null ? '' : ` processes=${processes}`;
const message = `login probe: PID=${pid} result=${result} ports=${ports}${processText}`;
if (probeNotes.get(pid) === message) {
return;
}
probeNotes.set(pid, message);
log.info(message);
}
const CONNECTION_TIMEOUT_MS = 500;
const COMMAND_TIMEOUT_MS = 1500;
const OVERALL_PROBE_TIMEOUT_MS = 5000;
const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as const };
// QQ's Ptlogin quick-login ports plus its main process mean a single
// logged-in client surfaces roughly this many processes. When no usable
// probe port is found, a count BELOW this implies the target PID is still at
// the login screen; AT/ABOVE it the environment is ambiguous (multiple or
// unrelated `qq` processes), so the passive probe returns no conclusion.
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". Neither outcome triggers interactive probing.
*/
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 | null> {
const useHttps = port % 2 !== 0;
const res1 = await fetchPtlogin(port, useHttps);
const res2 = await fetchPtlogin(port, useHttps);
if (res1 === null && res2 === null) {
return null;
}
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 null;
}
async function getQqProcessCount(): Promise<number> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync(
'tasklist /fi "imagename eq QQ.exe" /nh',
EXEC_OPTIONS,
);
return stdout
.toLowerCase()
.split('\n')
.filter((line) => line.includes('qq.exe')).length;
} else {
const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS);
return parseInt(stdout.trim(), 10) || 0;
}
} catch {
// On failure report the ambiguous threshold so we never falsely
// conclude "logged out".
return LOGGED_OUT_PROCESS_COUNT_MAX;
}
}
async function getProcessPorts(pid: number): Promise<number[] | null> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
const parts = line.trim().split(/\s+/);
if (parts.length < 5) {
continue;
}
const owningPid = parts[parts.length - 1];
if (owningPid !== String(pid)) {
continue;
}
const localAddr = parts[1];
const portMatch = localAddr.match(/:(\d+)$/);
if (!portMatch) {
continue;
}
ports.add(Number(portMatch[1]));
}
return Array.from(ports);
} else {
const { stdout } = await execAsync('ss -tlnp', EXEC_OPTIONS);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) {
continue;
}
const match = line.match(/:(\d+)\s/);
if (match) {
ports.add(Number(match[1]));
}
}
return Array.from(ports);
}
} catch {
return null;
}
}
async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo | null> {
const ports = await getProcessPorts(pid);
if (ports === null) {
noteProbe(pid, 'unavailable', 0, null);
return null;
}
if (ports.length === 0) {
const totalPids = await getQqProcessCount();
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
noteProbe(pid, 'no-ports', 0, totalPids);
return { port: 0, uin: '', identityKnown: false };
}
noteProbe(pid, 'inconclusive', 0, totalPids);
return null;
}
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
const matchedOddPorts = ports.filter((p) => ODD_PT_PORTS.includes(p));
const matchedEvenPorts = ports.filter((p) => EVEN_PT_PORTS.includes(p));
let ptPortsToTry: number[] = [];
if (matchedOddPorts.length > 0) {
ptPortsToTry = matchedOddPorts;
} else if (matchedEvenPorts.length > 0) {
ptPortsToTry = matchedEvenPorts;
}
if (ptPortsToTry.length > 0) {
for (const port of ptPortsToTry) {
const ptResult = await tryPtloginMethod(port);
if (ptResult !== null) {
return ptResult;
}
}
} else {
const totalPids = await getQqProcessCount();
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
noteProbe(pid, 'no-ports', ports.length, totalPids);
return {
port: ports[0],
uin: '',
identityKnown: false,
};
}
noteProbe(pid, 'inconclusive', ports.length, totalPids);
return null;
}
// Background discovery must remain passive. Interactive application
// endpoints are deliberately excluded from automatic probing.
noteProbe(pid, 'no-match', ptPortsToTry.length, null);
return null;
}
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
let timer: ReturnType<typeof setTimeout> | undefined;
let timedOut = false;
const timeout = new Promise<null>((resolve) => {
timer = setTimeout(() => {
timedOut = true;
resolve(null);
}, OVERALL_PROBE_TIMEOUT_MS);
});
try {
const result = await Promise.race([probeQqLoginInfoInternal(pid), timeout]);
if (timedOut) {
log.warn('login check timed out: PID=%d', pid);
}
return result;
} finally {
if (timer) {
clearTimeout(timer);
}
}
}

View File

@@ -76,18 +76,18 @@ function isNativeRuntimeIntegrity(value: unknown): value is NativeRuntimeIntegri
);
}
let cached: Promise<RuntimeIntegrity> | undefined;
let cached: 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> {
export function getRuntimeIntegrity(): RuntimeIntegrity {
if (process.platform !== 'win32') {
return { status: 'unsupported' };
}
if (cached) {
return cached;
}
try {
const addon = getNativeHookAddon();
@@ -95,17 +95,17 @@ async function readRuntimeIntegrity(): Promise<RuntimeIntegrity> {
throw new Error(getNativeHookLoadError() ?? '原生组件不可用');
}
if (typeof addon.getRuntimeIntegrityAsync !== 'function') {
if (typeof addon.getRuntimeIntegrity !== 'function') {
throw new Error('当前原生组件不支持完整性诊断,请更新原生组件');
}
const result = await addon.getRuntimeIntegrityAsync();
const result = addon.getRuntimeIntegrity();
if (!isNativeRuntimeIntegrity(result)) {
throw new Error('原生完整性诊断返回了无效数据');
}
return {
cached = {
status: 'available',
pid: result.pid,
executablePath: result.executablePath,
@@ -113,9 +113,11 @@ async function readRuntimeIntegrity(): Promise<RuntimeIntegrity> {
file: result.file,
};
} catch (error) {
return {
cached = {
status: 'unavailable',
error: error instanceof Error ? error.message : String(error),
};
}
return cached;
}

View File

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

View File

@@ -5,7 +5,6 @@ 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
@@ -24,21 +23,13 @@ interface Harness {
setLivePipes: (next: number[]) => void;
onSessionsChanged: ReturnType<typeof vi.fn>;
clientFactory: ReturnType<typeof vi.fn>;
notifyAccountChange: () => void;
watchAccounts: ReturnType<typeof vi.fn>;
}
function makeManager(
opts: {
processes?: number[];
livePipes?: number[];
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
} = {},
): Harness {
function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness {
let pids = opts.processes ?? [];
let live = new Set<number>(opts.livePipes ?? []);
const pipeWatcher = new PipeWatcher({
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
@@ -65,27 +56,15 @@ function makeManager(
onPidReceiveHealthChanged: vi.fn(),
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
const onSessionsChanged = vi.fn();
let accountChanged = () => {};
const watchAccounts = vi.fn((_pids: readonly number[], onChange: () => void) => {
accountChanged = onChange;
return vi.fn();
});
const manager = new HookManager({
bridgeManager,
pipeWatcher,
injector: {
inject: vi.fn(async () => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(async () => {}),
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
},
makeClient: clientFactory,
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: opts.detectAccounts ?? (async () => []),
watchAccounts,
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
onSessionsChanged,
});
return {
@@ -94,8 +73,6 @@ function makeManager(
bridgeManager,
onSessionsChanged,
clientFactory,
notifyAccountChange: () => accountChanged(),
watchAccounts,
setProcesses: (next) => {
pids = next;
},
@@ -175,7 +152,7 @@ describe('HookManager.onSessionsChanged', () => {
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: '' })),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(),
intervalMs: 60_000,
});
@@ -187,11 +164,11 @@ describe('HookManager.onSessionsChanged', () => {
} as unknown as BridgeManagerSink,
pipeWatcher,
injector: {
inject: vi.fn(async () => ({
inject: vi.fn(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(async () => {}),
unload: vi.fn(),
},
makeClient: vi.fn(() => {
const c = new EventEmitter() as any;
@@ -206,9 +183,7 @@ describe('HookManager.onSessionsChanged', () => {
return c;
}),
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: async () => [],
watchAccounts: () => () => {},
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
// onSessionsChanged deliberately omitted
});
await pipeWatcher.start();
@@ -221,443 +196,6 @@ describe('HookManager.onSessionsChanged', () => {
});
});
describe('HookManager account re-probe', () => {
it('reuses the account snapshot across ticks and REST reads while all sessions are online (#549)', async () => {
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 5151 },
]);
const ctx = makeManager({
processes: [4242, 5151],
livePipes: [4242, 5151],
detectAccounts,
});
const now = vi.spyOn(Date, 'now');
try {
await ctx.pipeWatcher.start();
await flush();
for (const [index, uin] of ['10001', '10002'].entries()) {
const client = ctx.clientFactory.mock.results[index]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin, uinNumber: BigInt(uin) });
}
const initial = await ctx.manager.listProcesses();
expect(initial.map((info) => info.status)).toEqual(['online', 'online']);
const baseline = detectAccounts.mock.calls.length;
ctx.onSessionsChanged.mockClear();
const startedAt = Date.now();
for (let tick = 1; tick <= 10; tick++) {
now.mockReturnValue(startedAt + tick * 6000);
await ctx.pipeWatcher.tickNow();
expect(await ctx.manager.listProcesses()).toEqual(initial);
}
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it.each(['loadProcess', 'unloadProcess', 'refreshProcess'] as const)(
'refreshes account labels on %s even within the probe interval',
async (operation) => {
let nickname = 'Alice';
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => [{ uin: '10001', uid: 'u_a', nickname, pid: 4242 }],
});
try {
expect((await ctx.manager.listProcesses())[0]!.account?.nickname).toBe('Alice');
nickname = 'Updated';
expect((await ctx.manager[operation](4242)).account?.nickname).toBe('Updated');
} finally {
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
},
);
it('discards an in-flight account result when an online process switches accounts', async () => {
const stale = Promise.withResolvers<AccountLoginState[]>();
const fresh = Promise.withResolvers<AccountLoginState[]>();
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
]);
const ctx = makeManager({
processes: [4242],
livePipes: [4242],
detectAccounts,
});
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
await ctx.manager.listProcesses();
detectAccounts.mockImplementationOnce(() => stale.promise);
detectAccounts.mockImplementationOnce(() => fresh.promise);
const refreshing = ctx.manager.refreshProcess(4242);
await flush();
const baseline = detectAccounts.mock.calls.length;
client.emit('loginState', { loggedIn: true, uin: '10002', uinNumber: 10002n });
const snapshot = ctx.manager.listProcesses();
await flush();
ctx.onSessionsChanged.mockClear();
stale.resolve([{ uin: '10003', uid: 'u_c', nickname: 'Stale', pid: 4242 }]);
await flush();
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
expect(detectAccounts).toHaveBeenCalledTimes(baseline + 1);
fresh.resolve([{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 4242 }]);
expect((await snapshot)[0]!.account).toEqual({ uin: '10002', nickname: 'Bob' });
expect((await refreshing).account).toEqual({ uin: '10002', nickname: 'Bob' });
} finally {
stale.resolve([]);
fresh.resolve([]);
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
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.each(['pipe-down', 'client-close', 'logout'] as const)(
're-probes after %s and observes later login data changes',
async (event) => {
let accounts: AccountLoginState[] = [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
];
const detectAccounts = vi.fn(async () => accounts);
const ctx = makeManager({
processes: [4242],
livePipes: [4242],
detectAccounts,
});
const now = vi.spyOn(Date, 'now');
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
await ctx.manager.listProcesses();
accounts = [];
if (event === 'pipe-down') {
ctx.setLivePipes([]);
await ctx.pipeWatcher.tickNow();
} else if (event === 'client-close') {
client.emit('close');
} else {
client.emit('loginState', { loggedIn: false, uin: '0', uinNumber: 0n });
}
await flush();
expect((await ctx.manager.listProcesses())[0]!.account).toBeNull();
accounts = [{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 4242 }];
now.mockReturnValue(Date.now() + 6000);
ctx.notifyAccountChange();
await ctx.pipeWatcher.tickNow();
expect((await ctx.manager.listProcesses())[0]!.account?.uin).toBe('10002');
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
},
);
it('re-probes when another process appears and when it exits', async () => {
let nickname = 'Alice';
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname, pid: 4242 },
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 5151 },
]);
const ctx = makeManager({ processes: [4242], livePipes: [4242], detectAccounts });
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
await ctx.manager.listProcesses();
nickname = 'Updated';
ctx.setProcesses([4242, 5151]);
await ctx.pipeWatcher.tickNow();
expect((await ctx.manager.listProcesses()).map((info) => info.account)).toEqual([
{ uin: '10001', nickname: 'Updated' },
{ uin: '10002', nickname: 'Bob' },
]);
nickname = 'Final';
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
await flush();
const list = await ctx.manager.listProcesses();
expect(list).toHaveLength(1);
expect(list[0]!.account?.nickname).toBe('Final');
} finally {
ctx.manager.dispose();
ctx.pipeWatcher.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();
expect((await ctx.manager.refreshProcess(4242)).account?.uin).toBe('10001');
const baseline = detectAccounts.mock.calls.length;
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();
}
});
// Login database changes can reveal login before the hook is loaded.
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,
});
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 }];
ctx.notifyAccountChange();
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,
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
ctx.notifyAccountChange();
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,
});
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 },
];
ctx.notifyAccountChange();
await flush();
await flush();
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
ctx.manager.dispose();
});
it('does not poll unlabelled, unloaded processes even after the old interval expires', async () => {
const detectAccounts = vi.fn(async () => [] as AccountLoginState[]);
const ctx = makeManager({
processes: [4242],
detectAccounts,
});
const now = vi.spyOn(Date, 'now');
try {
await ctx.manager.listProcesses();
const baseline = detectAccounts.mock.calls.length;
const startedAt = Date.now();
for (let tick = 1; tick <= 10; tick++) {
now.mockReturnValue(startedAt + tick * 6000);
await ctx.pipeWatcher.tickNow();
expect((await ctx.manager.listProcesses())[0]!.account).toBeNull();
}
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('does not re-probe a mixed set of online and unloaded processes', async () => {
const detectAccounts = vi.fn(async (): Promise<AccountLoginState[]> => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
]);
const ctx = makeManager({
processes: [4242, 5151],
livePipes: [4242],
detectAccounts,
});
const now = vi.spyOn(Date, 'now');
try {
await ctx.pipeWatcher.start();
await flush();
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
expect((await ctx.manager.listProcesses()).map((info) => info.status)).toEqual([
'online',
'available',
]);
const baseline = detectAccounts.mock.calls.length;
now.mockReturnValue(Date.now() + 60_000);
await ctx.pipeWatcher.tickNow();
await ctx.manager.listProcesses();
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
} finally {
now.mockRestore();
ctx.manager.dispose();
ctx.pipeWatcher.dispose();
}
});
it('releases file subscriptions when the process set changes and the manager stops', async () => {
const ctx = makeManager({ processes: [4242] });
try {
await ctx.pipeWatcher.start();
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([4242], expect.any(Function));
const firstStop = ctx.watchAccounts.mock.results.at(-1)!.value;
ctx.setProcesses([4242, 5151]);
await ctx.pipeWatcher.tickNow();
expect(firstStop).toHaveBeenCalledOnce();
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([4242, 5151], expect.any(Function));
const secondStop = ctx.watchAccounts.mock.results.at(-1)!.value;
ctx.setProcesses([5151]);
await ctx.pipeWatcher.tickNow();
await flush();
expect(secondStop).toHaveBeenCalledOnce();
expect(ctx.watchAccounts).toHaveBeenLastCalledWith([5151], expect.any(Function));
const finalStop = ctx.watchAccounts.mock.results.at(-1)!.value;
ctx.manager.dispose();
expect(finalStop).toHaveBeenCalledOnce();
} finally {
ctx.manager.dispose();
ctx.pipeWatcher.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');
},
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
await flush();
await flush();
// Detection failing is not a label change, so nothing is published.
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
expect((await ctx.manager.listProcesses())[0]!.account).toBeNull();
ctx.manager.dispose();
});
});
describe('HookManager receive-health wiring (#233)', () => {
it('forwards stale and recovered receive health for the owning PID', async () => {
const ctx = makeManager({ processes: [4242], livePipes: [4242] });

View File

@@ -7,7 +7,6 @@ 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,
@@ -29,21 +28,20 @@ function makeManager(opts: {
autoLoadOnDiscovery?: boolean;
processes?: number[];
onSessionsChanged?: () => void;
inject?: (pid: number) => Promise<HookInjectResult>;
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
}) {
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 unload = vi.fn();
const pipeWatcher = new PipeWatcher({
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
});
@@ -77,10 +75,7 @@ function makeManager(opts: {
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 () => []),
watchAccounts: () => () => {},
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
});
return {
manager,
@@ -474,41 +469,3 @@ describe('shouldAutoLoadPid', () => {
expect(shouldAutoLoadPid(99999, log)).toBe(true);
});
});
describe('HookManager — signed-in account labelling', () => {
it('labels each process with the account detected on it', async () => {
const ctx = makeManager({
processes: [4242, 5151],
detectAccounts: async () => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: null },
],
});
try {
const list = await ctx.manager.listProcesses();
expect(list.map((info) => [info.pid, info.account])).toEqual([
[4242, { uin: '10001', nickname: 'Alice' }],
[5151, null],
]);
} finally {
ctx.manager.dispose();
}
});
it('leaves processes unlabelled when detection fails', async () => {
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => {
throw new Error('login.db unreadable');
},
});
try {
const list = await ctx.manager.listProcesses();
expect(list[0]!.account).toBeNull();
} finally {
ctx.manager.dispose();
}
});
});

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,120 +1,57 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createProcessEnumerator } from '../src/process-enumerator';
import { describe, it, expect, vi } from 'vitest';
import { createNativeProcessEnumerator } from '../src/process-enumerator';
import type { HookProcessBaseInfo } from '../src/injector';
const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' });
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('keeps timed-out native work in flight until it actually finishes', async () => {
const request = deferred();
const listProcesses = vi.fn(() => request.promise).mockResolvedValueOnce([QQ(1)]);
const enumerator = createProcessEnumerator({ listProcesses, timeoutMs: 100 });
expect(await enumerator.enumerate()).toEqual([QQ(1)]);
const stalled = enumerator.enumerate();
await vi.advanceTimersByTimeAsync(100);
expect(await stalled).toBeNull();
for (let i = 0; i < 10; i++) {
expect(await enumerator.enumerate()).toBeNull();
}
expect(listProcesses).toHaveBeenCalledTimes(2);
request.resolve([QQ(2)]);
await vi.advanceTimersByTimeAsync(0);
listProcesses.mockResolvedValueOnce([QQ(3)]);
expect(await enumerator.enumerate()).toEqual([QQ(3)]);
expect(await stalled).toBeNull();
enumerator.dispose();
});
it.each(['throw', 'reject'] as const)(
'keeps a %s unknown and allows a fresh request',
async (kind) => {
const listProcesses = vi.fn<() => Promise<HookProcessBaseInfo[]>>(() => {
if (kind === 'throw') {
throw new Error('process table unavailable');
}
return Promise.reject(new Error('process table unavailable'));
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',
});
const enumerator = createProcessEnumerator({ listProcesses });
expect(await enumerator.enumerate()).toBeNull();
expect(vi.getTimerCount()).toBe(0);
listProcesses.mockResolvedValueOnce([]);
expect(await enumerator.enumerate()).toEqual([]);
enumerator.dispose();
},
);
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]);
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('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('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);
});
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('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();
});
// First call spawns the worker; the fatal message drains it to UNKNOWN.
const first = await en.enumerate();
expect(first).toBeNull();
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();
// 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();
});
});
});

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,119 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import { mkdtemp, mkdir, rename, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { createLogger } from '@snowluma/common/logger';
import { watchAccountFiles } from '../src/qq-account/watch';
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof fs>();
return { ...actual, watch: vi.fn(actual.watch) };
});
let root: string;
const subscriptions: Array<() => void> = [];
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-account-watch-'));
});
afterEach(async () => {
for (const stop of subscriptions.splice(0)) {
stop();
}
await rm(root, { recursive: true, force: true });
vi.restoreAllMocks();
vi.clearAllMocks();
});
function subscribe(dbPaths = [path.join(root, 'login.db')]) {
const changed = vi.fn();
const log = createLogger('AccountWatchTest');
const warning = vi.spyOn(log, 'warn');
const stop = watchAccountFiles(dbPaths, changed, log);
subscriptions.push(stop);
return { changed, stop, warning };
}
describe('account file changes', () => {
it('coalesces login database and WAL changes while ignoring message data and SHM', async () => {
const dbPath = path.join(root, 'login.db');
const { changed } = subscribe([dbPath, dbPath]);
expect(fs.watch).toHaveBeenCalledTimes(1);
await writeFile(dbPath, 'login');
await writeFile(`${dbPath}-wal`, 'wal');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1));
await writeFile(path.join(root, 'nt_msg.db'), 'message');
await writeFile(`${dbPath}-shm`, 'shared memory');
await delay(350);
expect(changed).toHaveBeenCalledTimes(1);
});
it('observes database replacement and WAL recreation', async () => {
const dbPath = path.join(root, 'login.db');
await writeFile(dbPath, 'initial');
const { changed } = subscribe();
await writeFile(path.join(root, 'replacement'), 'replacement');
await rename(path.join(root, 'replacement'), dbPath);
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1));
await writeFile(dbPath, 'updated');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(2));
await writeFile(`${dbPath}-wal`, 'wal');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(3));
await rm(`${dbPath}-wal`);
await writeFile(`${dbPath}-wal`, 'new wal');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(4));
});
it('starts watching login data created after QQ process discovery', async () => {
const dbPath = path.join(root, 'QQ', 'global', 'nt_db', 'login.db');
const { changed } = subscribe([dbPath]);
await mkdir(path.dirname(dbPath), { recursive: true });
await writeFile(dbPath, 'initial');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1));
await writeFile(`${dbPath}-wal`, 'login');
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(2));
});
it('closes watchers and cancels pending notifications on disposal', async () => {
const { changed, stop } = subscribe();
await writeFile(path.join(root, 'login.db'), 'initial');
await delay(30);
stop();
await writeFile(path.join(root, 'login.db'), 'later');
await delay(350);
expect(changed).not.toHaveBeenCalled();
});
it('reports watch failures without starting a polling fallback', async () => {
vi.mocked(fs.watch).mockImplementationOnce(() => {
throw Object.assign(new Error('access denied'), { code: 'EACCES' });
});
const { changed, warning } = subscribe();
expect(warning).toHaveBeenCalledWith(
'account watch failed: path=%s err=%s',
path.join(root, 'login.db'),
'access denied',
);
await delay(350);
expect(fs.watch).toHaveBeenCalledTimes(1);
expect(changed).not.toHaveBeenCalled();
});
it('reports asynchronous watch errors and closes the failed watcher', () => {
const { changed, warning } = subscribe();
const watcher = vi.mocked(fs.watch).mock.results[0]!.value;
const close = vi.spyOn(watcher, 'close');
watcher.emit('error', new Error('watch unavailable'));
expect(close).toHaveBeenCalledOnce();
expect(warning).toHaveBeenCalledWith(
'account watch failed: path=%s err=%s',
path.join(root, 'login.db'),
'watch unavailable',
);
expect(changed).not.toHaveBeenCalled();
});
});

View File

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

View File

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

View File

@@ -0,0 +1,77 @@
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: process.platform === 'win32' ? 'QQ.exe 4242 Console 1 1234 K\n' : '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:
process.platform === 'win32'
? 'TCP 127.0.0.1:9218 0.0.0.0:0 LISTENING 4242\n'
: '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:
process.platform === 'win32'
? 'QQ.exe 4242 Console 1 1234 K\n'.repeat(8)
: '8\n',
stderr: '',
});
});
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
expect(socketCtorMock).not.toHaveBeenCalled();
});
});

View File

@@ -56,22 +56,20 @@ describe('runtime integrity diagnostics', () => {
});
it('keeps one startup snapshot for logging and all WebUI polls', async () => {
const read = vi.fn().mockResolvedValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrityAsync: read });
const read = vi.fn().mockReturnValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrity: read });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
const pending = getRuntimeIntegrity();
expect(getRuntimeIntegrity()).toBe(pending);
const first = await pending;
const first = getRuntimeIntegrity();
expect(first).toMatchObject({
status: 'available',
process: { rid: 8192 },
file: { label: null },
});
read.mockResolvedValue({
read.mockReturnValue({
...sample(),
file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } },
});
expect(await getRuntimeIntegrity()).toBe(first);
expect(getRuntimeIntegrity()).toBe(first);
expect(read).toHaveBeenCalledTimes(1);
});
@@ -79,13 +77,13 @@ describe('runtime integrity diagnostics', () => {
'retains %s query errors and the other successful result',
async (field) => {
native.load.mockReturnValue({
getRuntimeIntegrityAsync: async () => ({
getRuntimeIntegrity: () => ({
...sample(),
[field]: { status: 'error', operation: 'Win32Query', code: 5 },
}),
});
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(await getRuntimeIntegrity()).toMatchObject({
expect(getRuntimeIntegrity()).toMatchObject({
status: 'available',
[field]: { status: 'error', operation: 'Win32Query', code: 5 },
});
@@ -95,7 +93,7 @@ describe('runtime integrity diagnostics', () => {
it('reports old addons as unavailable rather than Medium', async () => {
native.load.mockReturnValue({});
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(await getRuntimeIntegrity()).toMatchObject({
expect(getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: expect.stringContaining('不支持'),
});
@@ -105,7 +103,7 @@ describe('runtime integrity diagnostics', () => {
native.load.mockReturnValue(null);
native.error.mockReturnValue('dlopen failed: incompatible binary');
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(await getRuntimeIntegrity()).toMatchObject({
expect(getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: 'dlopen failed: incompatible binary',
});
@@ -117,26 +115,28 @@ describe('runtime integrity diagnostics', () => {
{ ...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 });
native.load.mockReturnValue({ getRuntimeIntegrity: () => result });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(await getRuntimeIntegrity()).toMatchObject({
expect(getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: expect.stringContaining('无效数据'),
});
});
it('preserves rejected errors without repeatedly probing on WebUI polls', async () => {
it('preserves thrown errors without repeatedly probing on WebUI polls', async () => {
const read = vi
.fn()
.mockRejectedValueOnce(new Error('allocation failed'))
.mockResolvedValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrityAsync: read });
.mockImplementationOnce(() => {
throw new Error('allocation failed');
})
.mockReturnValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrity: read });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(await getRuntimeIntegrity()).toMatchObject({
expect(getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: 'allocation failed',
});
expect(await getRuntimeIntegrity()).toMatchObject({
expect(getRuntimeIntegrity()).toMatchObject({
status: 'unavailable',
error: 'allocation failed',
});
@@ -146,7 +146,7 @@ describe('runtime integrity diagnostics', () => {
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(getRuntimeIntegrity()).toEqual({ status: 'unsupported' });
expect(native.load).not.toHaveBeenCalled();
});
});

View File

@@ -1,33 +1,13 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "2.0.3",
"version": "1.14.22",
"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": {
"./update-source": {
"types": "./src/update-source.ts",
"default": "./src/update-source.ts"
},
"./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"
@@ -44,10 +24,6 @@
"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"
@@ -103,15 +79,13 @@
},
"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",
"semver": "7.7.4"
"@zxcvbn-ts/language-en": "^4.1.1"
},
"engines": {
"node": ">=24"

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,10 +1,8 @@
import fs from 'fs';
import path from 'path';
import { isObject } from './coerce';
import { normalizeUpdateSourceConfig, type UpdateSourceConfig } from './update-source';
export interface RuntimeConfig {
updateSource?: UpdateSourceConfig;
webuiPort?: number;
/** When true, every newly-discovered QQ process gets auto-injected by
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
@@ -45,9 +43,6 @@ export const MAX_LOG_RETAIN_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / (24 * 60
export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
const obj = isObject(parsed) ? parsed : {};
return {
...(obj.updateSource === undefined
? {}
: { updateSource: normalizeUpdateSourceConfig(obj.updateSource) }),
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
webuiHost: normalizeHost(obj.webuiHost),
@@ -222,8 +217,7 @@ function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): b
parsed.trustProxy === n.trustProxy &&
parsed.logMaxTotalMb === n.logMaxTotalMb &&
parsed.logRetainDays === n.logRetainDays &&
parsed.logPerUin === n.logPerUin &&
JSON.stringify(parsed.updateSource) === JSON.stringify(n.updateSource)
parsed.logPerUin === n.logPerUin
);
}

View File

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

View File

@@ -1,4 +1,19 @@
/** TTL caching and request deduplication to limit repeated upstream requests. */
/**
* 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.
*/
export interface SingleFlightCacheOptions<K, V> {
/** Freshness window in ms. A cached entry older than this is reloaded. */
@@ -55,35 +70,30 @@ export class SingleFlightCache<K, V> {
return existing;
}
const load = async (): Promise<V> => {
const task = (async () => {
const value = await this.load(key);
if (this.inflight.get(key) === task && this.shouldCache(value)) {
if (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);
}
})().finally(() => {
// Run after registration even when load throws synchronously.
this.inflight.delete(key);
});
this.inflight.set(key, task);
return task;
}
/** Detach the entry and its pending load; existing callers still settle. */
/** Drop a cached entry. Does not abort an in-flight load. */
invalidate(key: K): void {
this.fresh.delete(key);
this.inflight.delete(key);
}
/** Detach all entries and pending loads without aborting existing callers. */
/** Drop all cached entries. Does not abort in-flight loads. */
clear(): void {
this.fresh.clear();
this.inflight.clear();
}
}

View File

@@ -1,60 +0,0 @@
export interface UpdateSourceConfig {
mode: 'auto' | 'direct' | 'mirror';
mirror: string;
mirrors: string[];
}
export function normalizeMirrorUrl(value: unknown): string {
if (typeof value !== 'string' || value.length > 2048) {
throw new Error('镜像地址必须是 HTTP(S) URL');
}
let url: URL;
try {
url = new URL(value.trim());
} catch {
throw new Error('镜像地址必须是 HTTP(S) URL');
}
if (
!['http:', 'https:'].includes(url.protocol) ||
url.username ||
url.password ||
url.search ||
url.hash
) {
throw new Error('镜像地址仅支持 HTTP(S),不能包含账号、密码、查询参数或片段');
}
return url.href.replace(/\/+$/, '');
}
export function normalizeUpdateSourceConfig(value: unknown): UpdateSourceConfig {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error('更新来源必须是对象');
}
if (
!('mode' in value) ||
(value.mode !== 'auto' && value.mode !== 'direct' && value.mode !== 'mirror')
) {
throw new Error('更新来源模式无效');
}
if (!('mirrors' in value) || !Array.isArray(value.mirrors) || value.mirrors.length > 16) {
throw new Error('自动筛选最多支持 16 个镜像');
}
const mirror = 'mirror' in value && value.mirror !== '' ? normalizeMirrorUrl(value.mirror) : '';
if (value.mode === 'mirror' && !mirror) {
throw new Error('请指定镜像地址');
}
return {
mode: value.mode,
mirror,
mirrors: [...new Set(value.mirrors.map(normalizeMirrorUrl))],
};
}

View File

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

View File

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

View File

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

View File

@@ -13,46 +13,6 @@ function deferred<T>() {
}
describe('SingleFlightCache', () => {
it.each(['invalidate', 'clear'] as const)(
'%s detaches pending loads from the cache',
async (operation) => {
const old = deferred<string>();
const current = deferred<string>();
const load = vi
.fn()
.mockReturnValueOnce(old.promise)
.mockReturnValueOnce(current.promise);
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
const first = cache.get('key');
cache[operation]('key');
const second = cache.get('key');
expect(load).toHaveBeenCalledTimes(2);
old.resolve('old');
await expect(first).resolves.toBe('old');
expect(cache.get('key')).toBe(second);
current.resolve('current');
await expect(second).resolves.toBe('current');
await expect(cache.get('key')).resolves.toBe('current');
expect(load).toHaveBeenCalledTimes(2);
},
);
it('does not let a late invalidated result overwrite a newer value', async () => {
const old = deferred<string>();
const load = vi.fn().mockReturnValueOnce(old.promise).mockResolvedValue('current');
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
const first = cache.get('key');
cache.invalidate('key');
await expect(cache.get('key')).resolves.toBe('current');
old.resolve('old');
await first;
await expect(cache.get('key')).resolves.toBe('current');
});
it('caches within the TTL and reloads once expired', async () => {
let clock = 1000;
const load = vi.fn(async (k: string) => `${k}@${clock}`);

View File

@@ -1,54 +0,0 @@
import { describe, expect, it } from 'vitest';
import { normalizeMirrorUrl, normalizeUpdateSourceConfig } from '../src/update-source';
import { normalizeRuntimeConfig } from '../src/runtime';
describe('update source configuration', () => {
it('normalizes proxy prefixes, deduplicates mirrors and retains order', () => {
expect(
normalizeUpdateSourceConfig({
mode: 'auto',
mirror: '',
mirrors: [
' https://EXAMPLE.com/proxy/ ',
'https://example.com/proxy',
'https://other.example',
],
}),
).toEqual({
mode: 'auto',
mirror: '',
mirrors: ['https://example.com/proxy', 'https://other.example'],
});
});
it.each([
'',
'file:///tmp/x',
'ftp://example.com',
'https://user:secret@example.com',
'https://example.com/?token=a',
'https://example.com/#a',
null,
])('rejects invalid mirror %s', (url) => {
expect(() => normalizeMirrorUrl(url)).toThrow();
});
it.each([
null,
[],
{ mode: ['auto'], mirrors: [] },
{ mode: 'mirror', mirror: '', mirrors: [] },
{ mode: 'auto', mirrors: Array(17).fill('https://example.com') },
])('rejects invalid configuration %j', (config) => {
expect(() => normalizeUpdateSourceConfig(config)).toThrow();
});
it('retains configured update sources when normalizing runtime settings', () => {
const updateSource = { mode: 'direct', mirror: '', mirrors: [] };
expect(normalizeRuntimeConfig({ updateSource, webuiPort: 7777 })).toMatchObject({
updateSource,
webuiPort: 7777,
});
expect(normalizeRuntimeConfig({})).not.toHaveProperty('updateSource');
});
});

View File

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

View File

@@ -25,7 +25,6 @@ import {
} from '@snowluma/protocol/services/qidian/fetch-corp-info';
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
import { GetGroupShareLink } from '@snowluma/protocol/oidb-services/contacts/get-group-share-link';
import {
SendTuwenArk,
type SendTuwenArkParams,
@@ -158,20 +157,6 @@ export class ContactsApi {
return GetGroupRecommendArk.invoke(this.ctx, { groupId });
}
getGroupShareLink(
groupId: number,
needShortUrl = true,
srcId = 73,
additionalParam = '',
): Promise<string> {
return GetGroupShareLink.invoke(this.ctx, {
groupId,
needShortUrl,
srcId,
additionalParam,
});
}
/** Send a custom 图文 ark card to a C2C peer or group (0xdc2_34). */
sendTuwenArk(params: SendTuwenArkParams): Promise<void> {
return SendTuwenArk.invoke(this.ctx, params);
@@ -581,48 +566,11 @@ export class ContactsApi {
return requests;
}
async resolveGroupJoinRequest(
groupId: number,
uid: string,
subType: 'add' | 'invite',
invitedUid?: string,
): Promise<GroupRequestInfo | null> {
const [main, filtered] = await Promise.allSettled([
this.fetchGroupRequestsByUid(false),
this.fetchGroupRequestsByUid(true),
]);
if (main.status === 'rejected') {
throw main.reason;
/** Live observation write. IncomingPacketPipeline and tests only. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
if (groupUin > 0 && sequence > 0) {
this.groupInviteCardSeqs_.set(groupUin, sequence);
}
if (filtered.status === 'rejected') {
throw filtered.reason;
}
return (
[...main.value, ...filtered.value].find((request) => {
if (request.groupId !== groupId || request.state !== 1) {
return false;
}
return subType === 'add'
? request.eventType === 1 && request.targetUid === uid
: (request.eventType === 2 || request.eventType === 22) &&
request.invitorUid === uid &&
request.targetUid === invitedUid;
}) ?? null
);
}
/** Returns whether this live card introduces a new approval sequence. */
rememberGroupInviteCardSequence(groupUin: number, sequence: number): boolean {
if (this.groupInviteCardSeqs_.get(groupUin) === sequence) {
return false;
}
this.groupInviteCardSeqs_.set(groupUin, sequence);
return true;
}
/** The approval msgseq captured from a private "qun.invite" card for this

View File

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

View File

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

View File

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

View File

@@ -16,19 +16,19 @@ const log = createLogger('Bridge');
const runtimeLog = createLogger('Bridge.Runtime');
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
interface ProcessConnection {
pid: number;
client: PacketSender;
receiveHealthy: boolean;
}
export class Bridge implements BridgeInterface {
readonly identity: IdentityService;
/** Insertion order tracks login recency; the newest connection sends packets. */
private readonly connections = new Map<number, ProcessConnection>();
private pids_ = new Set<number>();
private readonly receiveHealthByPid_ = new Map<number, boolean>();
/** Packet senders keyed by their owning QQ process. Keeping the sender and
* PID together is what makes disconnect fallback deterministic: a sender
* can never outlive the PID that supplied it. */
private readonly packetClientsByPid_ = new Map<number, PacketSender>();
readonly events = new BridgeEventBus();
readonly apis: ApiHub;
private readonly pipeline: IncomingPacketPipeline;
private packetClient_: PacketSender | null = null;
private packetClientPid_: number | null = null;
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
@@ -36,13 +36,13 @@ export class Bridge implements BridgeInterface {
// Per-account dedup for QQ NT's already-deduped system pushes (#137).
private readonly sysMsgDedup_ = new SysMsgDedup();
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
private disposed_ = false;
private disposePromise_: Promise<void> | null = null;
private readonly pendingPackets_ = new Set<Promise<void>>();
private rosterWarmupStarted_ = false;
private settleRosterWarmup!: (result: RosterWarmupResult) => void;
private readonly rosterWarmup = new Promise<RosterWarmupResult>((resolve) => {
this.settleRosterWarmup = resolve;
});
private rosterWarmupSettled_ = false;
private rosterWarmupResult_: RosterWarmupResult | null = null;
private readonly rosterWarmupWaiters_: Array<(result: RosterWarmupResult) => void> = [];
constructor(identity: IdentityService) {
this.identity = identity;
@@ -61,10 +61,72 @@ export class Bridge implements BridgeInterface {
fetchGroupMemberList: async (groupId) => {
await this.apis.contacts.fetchGroupMemberList(groupId);
},
resolveGroupJoinRequest: (groupId, uid, subType, invitedUid) =>
this.apis.contacts.resolveGroupJoinRequest(groupId, uid, subType, invitedUid),
rememberGroupInviteCardSequence: (groupUin, sequence) =>
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence),
resolveGroupJoinRequest: async (groupId, uid, subType) => {
const [main, filtered] = await Promise.allSettled([
this.apis.contacts.fetchGroupRequestsByUid(false),
this.apis.contacts.fetchGroupRequestsByUid(true),
]);
if (main.status === 'rejected') {
log.warn(
'group-request enrichment main inbox failed: group=%d uid=%s err=%s',
groupId,
uid,
main.reason instanceof Error ? main.reason.message : String(main.reason),
);
}
if (filtered.status === 'rejected') {
log.warn(
'group-request enrichment filtered inbox failed: group=%d uid=%s err=%s',
groupId,
uid,
filtered.reason instanceof Error
? filtered.reason.message
: String(filtered.reason),
);
}
if (main.status === 'rejected' && filtered.status === 'rejected') {
throw new Error('failed to fetch group requests from both inboxes');
}
const requests = [
...(main.status === 'fulfilled' ? main.value : []),
...(filtered.status === 'fulfilled' ? filtered.value : []),
];
const matches = requests.filter((r) => {
if (r.groupId !== groupId) {
return false;
}
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
});
if (subType === 'invite') {
return matches.find((r) => r.notifyType === 1) ?? matches[0] ?? null;
}
return matches.find((r) => r.notifyType === 7) ?? matches[0] ?? null;
},
resolveGroupInviteCardSequence: async (groupId) => {
const deadline = Date.now() + 1_000;
do {
const sequence = this.apis.contacts.getGroupInviteCardSequence(groupId);
if (sequence) {
return sequence;
}
await new Promise((resolve) => setTimeout(resolve, 25));
} while (Date.now() < deadline);
return null;
},
rememberGroupInviteCardSequence: (groupUin, sequence) => {
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence);
},
});
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) =>
parseMsgPushOrThrow(pkt, identity, this.sysMsgDedup_),
@@ -87,8 +149,13 @@ export class Bridge implements BridgeInterface {
return this.disposePromise_;
}
this.disposed_ = true;
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
this.connections.clear();
this.pids_.clear();
this.receiveHealthByPid_.clear();
this.packetClientsByPid_.clear();
this.packetClient_ = null;
this.packetClientPid_ = null;
this.onlineClients_ = null;
this.disposePromise_ = (async () => {
try {
@@ -101,6 +168,22 @@ export class Bridge implements BridgeInterface {
return this.disposePromise_;
}
/** Legacy two-step setter retained for external compatibility. It assigns
* the sender to the most recently attached PID when one exists. New
* BridgeManager code uses bindPid() for an atomic transition. */
setPacketClient(client: PacketSender): void {
this.packetClient_ = client;
const pids = [...this.pids_];
const pid = pids.length > 0 ? pids[pids.length - 1]! : null;
this.packetClientPid_ = pid;
if (pid !== null) {
this.packetClientsByPid_.set(pid, client);
}
this.maybeStartRosterWarmup();
}
registerCmd(cmd: string, parser: CmdParser): void {
this.pipeline.registerCmd(cmd, parser);
}
@@ -109,18 +192,34 @@ export class Bridge implements BridgeInterface {
return this.pipeline.handlesCmd(cmd);
}
bindPid(pid: number, client: PacketSender): void {
const previous = this.activeConnection;
this.connections.delete(pid);
// A new login stays healthy until the watchdog confirms a failure.
this.connections.set(pid, { pid, client, receiveHealthy: true });
/** Attach a process without a sender. Retained for compatibility; the
* manager uses bindPid() for the atomic PID+sender transition. Re-attaching
* deliberately refreshes recency. */
attachPid(pid: number): void {
this.pids_.delete(pid);
this.pids_.add(pid);
// A fresh/rebound login starts UNKNOWN-but-compatible. The receive
// watchdog only flips this false after observing QQ's own heartbeat and
// then missing the full stale + confirmation window.
this.receiveHealthByPid_.set(pid, true);
}
if (previous?.pid !== pid || previous.client !== client) {
/** Atomically attach a process and make its sender the active sender.
* Set insertion order is the recency order used for fallback. */
bindPid(pid: number, client: PacketSender): void {
const previousPid = this.packetClientPid_;
const previousClient = this.packetClient_;
this.attachPid(pid);
this.packetClientsByPid_.set(pid, client);
this.packetClient_ = client;
this.packetClientPid_ = pid;
if (previousPid !== pid || previousClient !== client) {
runtimeLog.trace(
'bridge_sender_fact event=selected uin=%j pid=%d previousPid=%j',
this.identity.uin,
pid,
previous?.pid ?? null,
previousPid,
);
}
@@ -130,63 +229,88 @@ export class Bridge implements BridgeInterface {
/** @internal BridgeManager lookup used when an incoming packet is the first
* observation that a live PID changed UIN. */
packetClientForPid(pid: number): PacketSender | null {
return this.connections.get(pid)?.client ?? null;
return this.packetClientsByPid_.get(pid) ?? null;
}
detachPid(pid: number): void {
const wasActive = this.activePid === pid;
this.connections.delete(pid);
const active = this.activeConnection;
this.pids_.delete(pid);
this.receiveHealthByPid_.delete(pid);
this.packetClientsByPid_.delete(pid);
if (wasActive && active) {
runtimeLog.trace(
'bridge_sender_fact event=fallback uin=%j detachedPid=%d fallbackPid=%d',
this.identity.uin,
pid,
active.pid,
);
log.debug(
'packet sender changed: UIN=%s PID=%d→%d',
this.identity.uin,
pid,
active.pid,
);
if (this.packetClientPid_ !== pid) {
// An unscoped legacy sender cannot be associated with a particular PID.
// It is safe to retain while another PID exists, but never after the
// Bridge becomes empty.
if (this.pids_.size === 0) {
this.packetClient_ = null;
this.packetClientPid_ = null;
}
return;
}
this.selectFallbackPacketClient(pid);
}
hasPid(pid: number): boolean {
return this.connections.has(pid);
return this.pids_.has(pid);
}
get empty(): boolean {
return this.connections.size === 0;
}
private get activeConnection(): ProcessConnection | undefined {
return [...this.connections.values()].at(-1);
return this.pids_.size === 0;
}
get activePid(): number | null {
return this.activeConnection?.pid ?? null;
if (this.packetClientPid_ !== null && this.pids_.has(this.packetClientPid_)) {
return this.packetClientPid_;
}
const pids = [...this.pids_];
return pids.length > 0 ? pids[pids.length - 1]! : null;
}
get receiveHealthy(): boolean {
return [...this.connections.values()].some((connection) => connection.receiveHealthy);
for (const pid of this.pids_) {
const healthy = this.receiveHealthByPid_.get(pid);
if (healthy === undefined) {
const message = `Bridge receive-health invariant violated: PID=${pid} has no health state`;
log.error(message);
throw new Error(message);
}
if (healthy) {
return true;
}
}
return false;
}
setPidReceiveHealthy(pid: number, healthy: boolean): void {
const connection = this.connections.get(pid);
if (!connection) {
if (!this.pids_.has(pid)) {
throw new Error(`Bridge receive-health invariant violated: PID=${pid} is not attached`);
}
connection.receiveHealthy = healthy;
this.receiveHealthByPid_.set(pid, healthy);
}
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
return this.onlineClients_;
}
whenRosterWarmupSettled(): Promise<RosterWarmupResult> {
return this.rosterWarmup;
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
return Promise.resolve(this.rosterWarmupResult_);
}
this.maybeStartRosterWarmup();
return new Promise((resolve) => {
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
resolve(this.rosterWarmupResult_);
return;
}
this.rosterWarmupWaiters_.push(resolve);
});
}
onPacket(pkt: PacketInfo): Promise<void> {
if (this.disposePromise_) {
if (this.disposed_) {
return Promise.reject(new Error('Bridge is disposed'));
}
@@ -234,9 +358,7 @@ export class Bridge implements BridgeInterface {
body: Uint8Array,
timeoutMs = packetTimeoutMs(),
): Promise<SendPacketResult> {
const connection = this.activeConnection;
if (!connection) {
if (!this.packetClient_) {
return runWithTraceRequest(() => {
const startedAt = Date.now();
runtimeLog.trace(() => [
@@ -269,7 +391,11 @@ export class Bridge implements BridgeInterface {
}
const startedAt = Date.now();
const result = await connection.client.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
const result = await this.packetClient_.sendPacket(
serviceCmd,
Buffer.from(body),
timeoutMs,
);
const elapsed = Date.now() - startedAt;
const respLen = result.responseData ? result.responseData.length : 0;
@@ -298,12 +424,52 @@ export class Bridge implements BridgeInterface {
return result;
}
private selectFallbackPacketClient(detachedPid: number): void {
const pids = [...this.pids_];
for (let index = pids.length - 1; index >= 0; index -= 1) {
const fallbackPid = pids[index]!;
const fallback = this.packetClientsByPid_.get(fallbackPid);
if (!fallback) {
continue;
}
this.packetClient_ = fallback;
this.packetClientPid_ = fallbackPid;
runtimeLog.trace(
'bridge_sender_fact event=fallback uin=%j detachedPid=%d fallbackPid=%d',
this.identity.uin,
detachedPid,
fallbackPid,
);
log.debug(
'packet sender fallback: UIN=%s detached PID=%d fallback PID=%d',
this.identity.uin,
detachedPid,
fallbackPid,
);
return;
}
this.packetClient_ = null;
this.packetClientPid_ = null;
if (this.pids_.size > 0) {
log.warn(
'packet sender unavailable after PID detach: UIN=%s detached PID=%d remaining PIDs=%d',
this.identity.uin,
detachedPid,
this.pids_.size,
);
}
}
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);
}
private maybeStartRosterWarmup(): void {
if (this.disposePromise_ || this.rosterWarmupStarted_ || this.empty) {
if (this.disposed_ || this.rosterWarmupStarted_ || !this.packetClient_) {
return;
}
@@ -316,7 +482,7 @@ export class Bridge implements BridgeInterface {
void this.runRosterWarmup().then(
(result) =>
this.settleRosterWarmup(
this.disposePromise_ ? { friendsLoaded: false, groupsLoaded: false } : result,
this.disposed_ ? { friendsLoaded: false, groupsLoaded: false } : result,
),
(err) => {
log.warn(
@@ -329,14 +495,28 @@ export class Bridge implements BridgeInterface {
);
}
private settleRosterWarmup(result: RosterWarmupResult): void {
if (this.rosterWarmupSettled_) {
return;
}
this.rosterWarmupSettled_ = true;
this.rosterWarmupResult_ = result;
const waiters = this.rosterWarmupWaiters_.splice(0);
for (const resolve of waiters) {
resolve(result);
}
}
private stillOpen(): boolean {
return this.disposePromise_ === null;
return !this.disposed_;
}
private async runRosterWarmup(): Promise<RosterWarmupResult> {
await this.identity.initialization;
if (this.disposePromise_) {
if (this.disposed_) {
return { friendsLoaded: false, groupsLoaded: false };
}

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,366 @@
import {
readFileSync,
writeFileSync,
mkdirSync,
statSync,
openSync,
readSync,
closeSync,
fstatSync,
} from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createLogger, type Logger } from '@snowluma/common/logger';
export const STAGE_FILE_NAME = 's7.log';
export const MIRROR_LIMIT_BYTES = 1024 * 1024;
const VERSION_HEADER = /^v\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
export function isVersionHeader(line: string): boolean {
return VERSION_HEADER.test(line);
}
export function lineSeverity(line: string): 'info' | 'error' {
const parts = line.trim().split(/\s+/);
return parts.length >= 4 && parts[3] === '1' ? 'error' : 'info';
}
export function publicLine(version: string, raw: string): string {
return `${version} ${raw.trim()}`;
}
function byteSize(lines: readonly string[]): number {
if (lines.length === 0) {
return 0;
}
return Buffer.byteLength(`${lines.join('\n')}\n`, 'utf8');
}
export function trimMirror(text: string, limit = MIRROR_LIMIT_BYTES): string {
const lines = text.split('\n').filter((line) => line.length > 0);
const size = () => byteSize(lines);
while (lines.length > 0 && size() > limit) {
const body = lines.findIndex((line) => !isVersionHeader(line));
if (body >= 0) {
lines.splice(body, 1);
continue;
}
if (lines.length <= 1) {
break;
}
lines.shift();
}
if (lines.length === 0) {
return '';
}
return `${lines.join('\n')}\n`;
}
export function appendEvents(
mirror: string,
version: string,
events: readonly string[],
limit = MIRROR_LIMIT_BYTES,
): string {
const fresh = events.map((line) => line.trim()).filter((line) => line.length > 0);
if (fresh.length === 0) {
return mirror;
}
const header = `v${version}`;
const lines = mirror.split('\n').filter((line) => line.length > 0);
let lastHeader = '';
for (const line of lines) {
if (isVersionHeader(line)) {
lastHeader = line;
}
}
const next = [...lines];
if (lastHeader !== header) {
next.push(header);
}
next.push(...fresh);
return trimMirror(`${next.join('\n')}\n`, limit);
}
export function tempStagePath(
platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): string {
if (platform === 'win32') {
const base = env.TMP || env.TEMP || os.tmpdir();
return path.join(base, STAGE_FILE_NAME);
}
const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`;
}
export function readAppVersion(moduleUrl: string | URL = import.meta.url): string {
if (typeof __APP_VERSION__ === 'string' && __APP_VERSION__) {
return __APP_VERSION__;
}
try {
const raw = readFileSync(new URL('../package.json', moduleUrl), 'utf8');
const version = JSON.parse(raw).version;
if (typeof version === 'string' && version.trim()) {
return version.trim();
}
} catch {
// Built layouts that do not sit next to a package manifest keep the fallback.
}
return '0.0.0';
}
export function errorCode(error: unknown): string {
if (error && typeof error === 'object' && 'code' in error) {
const code = (error as { code?: unknown }).code;
if (typeof code === 'string' && code) {
return code;
}
}
return 'ERR';
}
export interface StageSyncOptions {
version: string;
dataDir: string;
tempPath: string;
log?: Logger;
intervalMs?: number;
}
interface IngestResult {
mirror: string;
offset: number;
lines: string[];
missing: boolean;
errorCode?: string;
}
export function ingestTemp(args: {
tempText: string;
offset: number;
mirror: string;
version: string;
missing?: boolean;
errorCode?: string;
}): IngestResult {
if (args.missing) {
return { mirror: args.mirror, offset: args.offset, lines: [], missing: true };
}
if (args.errorCode) {
return {
mirror: args.mirror,
offset: args.offset,
lines: [],
missing: false,
errorCode: args.errorCode,
};
}
const start = args.offset > args.tempText.length ? 0 : args.offset;
const chunk = args.tempText.slice(start);
const newline = chunk.lastIndexOf('\n');
if (newline < 0) {
return { mirror: args.mirror, offset: start, lines: [], missing: false };
}
const complete = chunk.slice(0, newline + 1);
const lines = complete
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0);
return {
mirror: appendEvents(args.mirror, args.version, lines),
offset: start + newline + 1,
lines,
missing: false,
};
}
function readOffset(file: string): number {
try {
const raw = readFileSync(file, 'utf8').trim();
const value = Number(raw);
return Number.isSafeInteger(value) && value >= 0 ? value : 0;
} catch {
return 0;
}
}
function readTemp(file: string): { text: string; missing: boolean; errorCode?: string } {
let fd: number | undefined;
try {
fd = openSync(file, 'r');
const info = fstatSync(fd);
const size = info.size;
if (size > 8 * 1024 * 1024) {
return { text: '', missing: false, errorCode: 'E2BIG' };
}
const buf = Buffer.alloc(size);
let got = 0;
while (got < size) {
const n = readSync(fd, buf, got, size - got, got);
if (n <= 0) {
break;
}
got += n;
}
return { text: buf.subarray(0, got).toString('utf8'), missing: false };
} catch (error) {
const code = errorCode(error);
if (code === 'ENOENT') {
return { text: '', missing: true };
}
return { text: '', missing: false, errorCode: code };
} finally {
if (fd !== undefined) {
closeSync(fd);
}
}
}
export function startNativeStageSync(options: StageSyncOptions): { stop: () => void } {
const log = options.log ?? createLogger('native');
const mirrorPath = path.join(options.dataDir, STAGE_FILE_NAME);
const offsetPath = path.join(options.dataDir, 's7.off');
let offset = readOffset(offsetPath);
let failed = false;
let stopped = false;
const tick = () => {
if (stopped) {
return;
}
let tempSize = 0;
try {
tempSize = statSync(options.tempPath).size;
} catch (error) {
const code = errorCode(error);
if (code === 'ENOENT') {
return;
}
if (!failed) {
failed = true;
log.error('sync failed %s', code);
}
return;
}
if (tempSize < offset) {
offset = 0;
}
const temp = readTemp(options.tempPath);
if (temp.missing) {
return;
}
if (temp.errorCode) {
if (!failed) {
failed = true;
log.error('sync failed %s', temp.errorCode);
}
return;
}
let mirror = '';
try {
mirror = readFileSync(mirrorPath, 'utf8');
} catch (error) {
if (errorCode(error) !== 'ENOENT') {
if (!failed) {
failed = true;
log.error('sync failed %s', errorCode(error));
}
return;
}
}
const ingested = ingestTemp({
tempText: temp.text,
offset,
mirror,
version: options.version,
});
if (ingested.lines.length === 0 && ingested.offset === offset) {
failed = false;
return;
}
try {
mkdirSync(options.dataDir, { recursive: true });
writeFileSync(mirrorPath, ingested.mirror);
writeFileSync(offsetPath, `${ingested.offset}\n`);
offset = ingested.offset;
failed = false;
} catch (error) {
if (!failed) {
failed = true;
log.error('sync failed %s', errorCode(error));
}
return;
}
for (const line of ingested.lines) {
const text = publicLine(options.version, line);
if (lineSeverity(line) === 'error') {
log.error('%s', text);
} else {
log.info('%s', text);
}
}
};
tick();
const timer = setInterval(tick, options.intervalMs ?? 500);
timer.unref?.();
return {
stop() {
stopped = true;
clearInterval(timer);
},
};
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,236 +0,0 @@
import { createHash } from 'node:crypto';
import { createWriteStream } from 'node:fs';
import { mkdir, readFile, writeFile, rm } from 'node:fs/promises';
import path from 'node:path';
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { unzipSync } from 'fflate';
import { x as extractTar } from 'tar';
import { isRuntimeEntry, readManifest } from './files';
import { assetName, fetchRelease } from './release';
export { assetName } from './release';
import { readUpdateSource, sourceUrls } from './sources';
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
interface ReleaseAsset {
url: string;
size: number | null;
digest: string;
}
async function releaseAsset(
version: string,
target: string,
source: UpdateSourceConfig,
): Promise<ReleaseAsset> {
const name = assetName(version, target);
const { data: release, fromPage } = await fetchRelease(version, source);
if (
!release ||
typeof release !== 'object' ||
!('assets' in release) ||
!Array.isArray(release.assets)
) {
throw new Error('发布信息无效');
}
const asset: unknown = release.assets.find(
(item: unknown) =>
item !== null && typeof item === 'object' && 'name' in item && item.name === name,
);
const url = `https://github.com/SnowLuma/SnowLuma/releases/download/v${version}/${name}`;
if (
!asset ||
typeof asset !== 'object' ||
!('size' in asset) ||
!(
(fromPage && asset.size === null) ||
(typeof asset.size === 'number' && Number.isSafeInteger(asset.size) && asset.size > 0)
) ||
!('digest' in asset) ||
typeof asset.digest !== 'string' ||
!/^sha256:[a-f0-9]{64}$/.test(asset.digest)
) {
throw new Error('更新包不存在或缺少校验信息');
}
return { url, size: asset.size, digest: asset.digest };
}
export function archivePath(name: string): string {
const normalized = name.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/$/, '');
if (normalized === '.' || normalized === '') {
return '';
}
const parts = normalized.split('/');
if (
!isRuntimeEntry(parts[0]) ||
parts.some((part) => !part || part === '.' || part === '..' || /[:\0]/.test(part))
) {
throw new Error(`更新包路径无效: ${name}`);
}
return normalized;
}
export async function downloadUpdate(
directory: string,
version: string,
target: string,
source = readUpdateSource(),
): Promise<void> {
const asset = await releaseAsset(version, target, source);
const archive = path.join(directory, 'archive');
const urls = sourceUrls(asset.url, source);
const failures: string[] = [];
for (const [index, url] of urls.entries()) {
let created = false;
try {
const headersTimeout = new AbortController();
const timer = setTimeout(() => headersTimeout.abort(), 8_000);
let response: Response;
try {
response = await fetch(url, {
signal: AbortSignal.any([
headersTimeout.signal,
AbortSignal.timeout(10 * 60_000),
]),
});
} finally {
clearTimeout(timer);
}
if (!response.ok || !response.body) {
await response.body?.cancel();
throw new Error(`下载更新失败: HTTP ${response.status}`);
}
if (/text\/html/i.test(response.headers.get('content-type') ?? '')) {
await response.body.cancel();
throw new Error('下载源返回了 HTML 页面,而不是更新包');
}
const hash = createHash('sha256');
const length = response.headers.get('content-length');
const size =
asset.size ?? (length === null ? null : /^\d+$/.test(length) ? Number(length) : 0);
if (size !== null && (!Number.isSafeInteger(size) || size <= 0)) {
await response.body.cancel();
throw new Error('下载源返回了无效的更新包大小');
}
let received = 0;
const output = createWriteStream(archive, { flags: 'wx' });
output.once('open', () => {
created = true;
});
await pipeline(
Readable.fromWeb(response.body),
new Transform({
transform(chunk: Buffer, _encoding, callback) {
received += chunk.length;
if (received > (size ?? 256 * 1024 * 1024)) {
callback(new Error('更新包大小不匹配'));
return;
}
hash.update(chunk);
callback(null, chunk);
},
}),
output,
);
if (
(size !== null && received !== size) ||
`sha256:${hash.digest('hex')}` !== asset.digest
) {
throw new Error('更新包校验失败');
}
break;
} catch (error) {
if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {
throw error;
}
failures.push(error instanceof Error ? error.message : String(error));
if (index === urls.length - 1) {
throw new Error([...new Set(failures)].join(';'));
}
if (created) {
await rm(archive);
}
}
}
const payload = path.join(directory, 'payload');
await mkdir(payload);
if (target.startsWith('win32')) {
const files = unzipSync(await readFile(archive), {
filter: (entry) => {
archivePath(entry.name);
return true;
},
});
for (const [name, bytes] of Object.entries(files)) {
const relative = archivePath(name);
if (!relative || name.endsWith('/')) {
continue;
}
const destination = path.join(payload, relative);
await mkdir(path.dirname(destination), { recursive: true });
await writeFile(destination, bytes, { flag: 'wx' });
}
} else {
let invalidEntry: Error | undefined;
await extractTar({
file: archive,
cwd: payload,
strict: true,
filter: (name, entry) => {
try {
archivePath(name);
if (
!('type' in entry) ||
(entry.type !== 'File' && entry.type !== 'Directory')
) {
throw new Error('更新包包含链接或特殊文件');
}
return true;
} catch (error) {
invalidEntry = error instanceof Error ? error : new Error(String(error));
return false;
}
},
});
if (invalidEntry) {
throw invalidEntry;
}
}
const manifest = await readManifest(payload);
if (manifest.version !== version || manifest.target !== target) {
throw new Error('更新包版本或平台不匹配');
}
}

View File

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

View File

@@ -1,196 +0,0 @@
import { parseVersion } from '@snowluma/common/semver';
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
import { RELEASE_ROOT, sourceUrls } from './sources';
export function assetName(version: string, target: string): string {
const platform = target.replace('win32', 'win');
return `SnowLuma-v${version}-${platform}-lite.${target.startsWith('win32') ? 'zip' : 'tar.gz'}`;
}
async function readText(response: Response, limit: number): Promise<string> {
if (!response.body) {
throw new Error('发布信息为空');
}
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let size = 0;
try {
for (;;) {
const { value, done } = await reader.read();
if (done) {
break;
}
size += value.length;
if (size > limit) {
await reader.cancel();
throw new Error('发布信息过大');
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
return Buffer.concat(chunks).toString('utf8');
}
function attribute(tag: string, name: string): string | undefined {
return new RegExp(`\\s${name}\\s*=\\s*(["'])(.*?)\\1`, 'i')
.exec(tag)?.[2]
.replaceAll('&amp;', '&')
.replaceAll('&#39;', "'")
.replaceAll('&quot;', '"');
}
export function parseLatestReleasePage(html: string) {
const meta = html
.match(/<meta\b[^>]*>/gi)
?.find((tag) => attribute(tag, 'property') === 'og:url');
const canonical = meta && attribute(meta, 'content');
if (!canonical) {
throw new Error('发布页面缺少版本信息');
}
const url = new URL(canonical, 'https://github.com');
const tag = /^\/SnowLuma\/SnowLuma\/releases\/tag\/([^/]+)$/.exec(url.pathname)?.[1];
const decoded = tag && decodeURIComponent(tag);
const version = decoded?.startsWith('v') ? decoded.slice(1) : undefined;
const parsed = parseVersion(version);
if (url.origin !== 'https://github.com' || !parsed || parsed.prerelease.length) {
throw new Error('发布页面不是 SnowLuma 正式版本');
}
return { tag_name: `v${parsed.raw}`, html_url: `${RELEASE_ROOT}/tag/v${parsed.raw}` };
}
/** Match the digest in the same asset row; never borrow a neighbouring asset's hash. */
export function parseReleaseAssetsPage(html: string, version: string) {
const assets: { name: string; size: null; digest: string }[] = [];
const expected = ['win32-x64', 'linux-x64', 'linux-arm64'].map((target) =>
assetName(version, target),
);
for (const row of html.match(/<li\b[^>]*>[\s\S]*?<\/li>/gi) ?? []) {
const links = row.match(/<a\b[^>]*>/gi) ?? [];
const name = expected.find((candidate) =>
links.some((link) => {
const href = attribute(link, 'href');
return (
href === `/SnowLuma/SnowLuma/releases/download/v${version}/${candidate}` ||
href === `${RELEASE_ROOT}/download/v${version}/${candidate}`
);
}),
);
if (!name) {
continue;
}
const digests = (row.match(/<clipboard-copy\b[^>]*>/gi) ?? [])
.map((tag) => attribute(tag, 'value'))
.filter((value): value is string =>
Boolean(value && /^sha256:[a-f0-9]{64}$/.test(value)),
);
if (digests.length !== 1 || assets.some((asset) => asset.name === name)) {
throw new Error('发布页面缺少唯一的文件校验信息');
}
// GitHub renders a rounded size in HTML. Verify the exact digest even
// when a proxy streams the asset without Content-Length.
assets.push({ name, size: null, digest: digests[0]! });
}
if (!assets.length) {
throw new Error('发布页面没有可验证的更新包');
}
return { tag_name: `v${version}`, assets };
}
export interface ReleaseResult {
data: unknown;
fromPage: boolean;
}
export async function fetchRelease(
version: string | undefined,
source: UpdateSourceConfig,
userAgent = 'SnowLuma',
timeoutMs = 8_000,
): Promise<ReleaseResult> {
const apiUrl = `https://api.github.com/repos/SnowLuma/SnowLuma/releases/${version ? `tags/v${version}` : 'latest'}`;
let primaryError: unknown;
try {
const response = await fetch(apiUrl, {
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': userAgent,
'X-GitHub-Api-Version': '2022-11-28',
},
signal: AbortSignal.timeout(timeoutMs),
});
if (!response.ok) {
await response.body?.cancel();
throw new Error(`GitHub ${response.status}`);
}
return {
data: JSON.parse(await readText(response, 256 * 1024)) as unknown,
fromPage: false,
};
} catch (error) {
primaryError = error;
}
const originalUrl = version
? `${RELEASE_ROOT}/expanded_assets/v${version}`
: `${RELEASE_ROOT}/latest`;
const controller = new AbortController();
try {
// Only a parsed release page can win. Fast errors and HTML interstitials
// cannot cancel a slower working source.
// Download proxies often only support assets. Always retain GitHub's
// release page for version/digest lookup, even with a pinned download mirror.
const urls = [...new Set([originalUrl, ...sourceUrls(originalUrl, source)])];
const data = await Promise.any(
urls.map(async (url) => {
const response = await fetch(url, {
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]),
});
if (!response.ok) {
await response.body?.cancel();
throw new Error(`HTTP ${response.status}`);
}
const html = await readText(response, 1024 * 1024);
return version
? parseReleaseAssetsPage(html, version)
: parseLatestReleasePage(html);
}),
);
return { data, fromPage: true };
} catch (error) {
const failures = error instanceof AggregateError ? error.errors : [error];
const details = [primaryError, ...failures]
.filter(Boolean)
.map((failure: unknown) =>
failure instanceof Error ? failure.message : String(failure),
);
throw new Error(`${[...new Set(details)].join(';')};请在更新来源中检测或指定可用镜像`);
} finally {
controller.abort();
}
}

View File

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

View File

@@ -1,125 +0,0 @@
import { APP_VERSION } from '@snowluma/common/version';
import { readRuntimeConfig, updateRuntimeConfig } from '@snowluma/common/runtime';
import {
normalizeUpdateSourceConfig,
type UpdateSourceConfig,
} from '@snowluma/common/update-source';
export const RELEASE_ROOT = 'https://github.com/SnowLuma/SnowLuma/releases';
export const DEFAULT_UPDATE_SOURCE: UpdateSourceConfig = {
mode: 'auto',
mirror: '',
mirrors: [
'https://ghfast.top',
'https://ghproxy.net',
'https://gh-proxy.com',
'https://github.chenc.dev',
'https://fastgit.cc',
'https://gh.noki.icu',
'https://cors.isteed.cc',
'https://gh-proxy.org',
'https://githubproxy.gohj99.site',
'https://github.xxlab.tech',
],
};
export function readUpdateSource(): UpdateSourceConfig {
return normalizeUpdateSourceConfig(readRuntimeConfig().updateSource ?? DEFAULT_UPDATE_SOURCE);
}
export function saveUpdateSource(value: unknown): UpdateSourceConfig {
const config = normalizeUpdateSourceConfig(value);
updateRuntimeConfig({ updateSource: config });
return config;
}
export function sourceUrls(url: string, config: UpdateSourceConfig): string[] {
if (config.mode === 'direct') {
return [url];
}
if (config.mode === 'mirror') {
return [`${config.mirror}/${url}`];
}
return [url, ...config.mirrors.map((mirror) => `${mirror}/${url}`)];
}
export interface MirrorProbeResult {
mirror: string;
available: boolean;
latencyMs: number;
error?: string;
}
export async function testUpdateSources(value: unknown): Promise<MirrorProbeResult[]> {
const config = normalizeUpdateSourceConfig(value);
const mirrors = [
...new Set(['', ...config.mirrors, ...(config.mirror ? [config.mirror] : [])]),
];
const target = process.platform === 'win32' ? 'win-x64' : `linux-${process.arch}`;
const extension = process.platform === 'win32' ? 'zip' : 'tar.gz';
const probeUrl = `${RELEASE_ROOT}/download/v${APP_VERSION}/SnowLuma-v${APP_VERSION}-${target}-lite.${extension}`;
const results = await Promise.all(
mirrors.map(async (mirror): Promise<MirrorProbeResult> => {
const start = performance.now();
try {
const response = await fetch(mirror ? `${mirror}/${probeUrl}` : probeUrl, {
headers: { Range: 'bytes=0-3' },
signal: AbortSignal.timeout(5_000),
});
if (!response.ok || !response.body) {
await response.body?.cancel();
throw new Error(`HTTP ${response.status}`);
}
if (/text\/html/i.test(response.headers.get('content-type') ?? '')) {
await response.body.cancel();
throw new Error('返回了 HTML 页面,而不是更新包');
}
const reader = response.body.getReader();
const prefix: number[] = [];
try {
while (prefix.length < 4) {
const { value, done } = await reader.read();
if (done) {
break;
}
prefix.push(...value.subarray(0, 4 - prefix.length));
}
} finally {
await reader.cancel();
reader.releaseLock();
}
const signature = extension === 'zip' ? [0x50, 0x4b, 0x03, 0x04] : [0x1f, 0x8b];
if (!signature.every((byte, index) => prefix[index] === byte)) {
throw new Error('返回内容不是有效的更新包');
}
return {
mirror,
available: true,
latencyMs: Math.round(performance.now() - start),
};
} catch (error) {
return {
mirror,
available: false,
latencyMs: Math.round(performance.now() - start),
error: error instanceof Error ? error.message : String(error),
};
}
}),
);
return results.sort(
(a, b) => Number(b.available) - Number(a.available) || a.latencyMs - b.latencyMs,
);
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,3 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger } from '@snowluma/common/logger';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
@@ -435,6 +434,10 @@ function invoke(options: RestoreBackupOptions, operation: RestoreOperation): voi
options.beforeOperation?.(operation);
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function isMissingPathError(error: unknown): boolean {
return (
typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,3 @@
import { errorMessage } from '@snowluma/common/errors';
// WebUI TLS helpers. Cert/key live as config/cert.pem + config/key.pem
// (NapCat-aligned, self-contained, travels in A2 backups). Two pure-ish
// helpers: validate a pasted pair (save path) and resolve the on-disk pair
@@ -26,6 +25,10 @@ export interface RequiredTlsContext {
key: Buffer;
}
function errMsg(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
/** Parse-validate a cert/key pair (used by the save endpoint before writing). */
export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation {
if (!cert || !cert.toString().trim()) {
@@ -40,7 +43,7 @@ export function validateTlsPair(cert: string | Buffer, key: string | Buffer): Tl
tls.createSecureContext({ cert, key });
return { ok: true };
} catch (e) {
return { ok: false, reason: `invalid cert/key: ${errorMessage(e)}` };
return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` };
}
}
@@ -60,7 +63,7 @@ export function resolveTlsContext(configDir: string): TlsResolution {
cert = fs.readFileSync(certPath);
key = fs.readFileSync(keyPath);
} catch (e) {
return { ok: false, reason: `failed to read cert/key: ${errorMessage(e)}` };
return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` };
}
const valid = validateTlsPair(cert, key);

View File

@@ -1,13 +1,21 @@
import { APP_VERSION } from '@snowluma/common/version';
import { compareVersions, parseVersion } from '@snowluma/common/semver';
// Advisory update check against the public GitHub Releases API.
//
// Strictly read-only (T0): SnowLuma never downloads or applies anything
// itself — cross-platform self-update is a minefield (Windows locks loaded
// .node/.dll/node.exe, Docker bakes the app into image layers, bare installs
// have no supervisor). We only tell the WebUI that a newer *stable* release
// exists and link the user to it; they download and apply manually.
//
// The result is cached to stay well under GitHub's 60 req/hr unauthenticated
// rate limit, and every failure degrades silently (the UI just shows
// "无法检查更新" rather than nagging).
import { createLogger } from '@snowluma/common/logger';
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
import type { UpdateSourceConfig } from '@snowluma/common/update-source';
import { fetchRelease } from './release';
import { readUpdateSource } from './sources';
const log = createLogger('Update');
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — comfortably under the rate limit
const FETCH_TIMEOUT_MS = 8_000;
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
@@ -31,21 +39,73 @@ export interface UpdateCheckResult {
error?: string;
}
interface GithubRelease {
tag_name?: string;
html_url?: string;
body?: string;
published_at?: string;
}
export function currentVersion(): string {
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
}
function isEnabled(): boolean {
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
}
/**
* Compare two dotted versions. Returns >0 if `a` is newer than `b`, <0 if
* older, 0 if equal. The numeric core (major.minor.patch) compares
* numerically; a prerelease (`-rc.1`) ranks below its release. Good enough
* for "is the latest stable strictly newer than what we run" — and avoids
* pulling in a `semver` runtime dependency (the dist bundle ships none).
*/
export function compareVersions(a: string, b: string): number {
const parse = (v: string) => {
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
while (nums.length < 3) {
nums.push(0);
}
return { nums, pre };
};
const pa = parse(a);
const pb = parse(b);
for (let i = 0; i < 3; i++) {
if (pa.nums[i] !== pb.nums[i]) {
return pa.nums[i] - pb.nums[i];
}
}
if (pa.pre === pb.pre) {
return 0;
}
if (!pa.pre) {
return 1;
} // release > prerelease
if (!pb.pre) {
return -1;
}
return pa.pre < pb.pre ? -1 : 1;
}
// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's
// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results
// are intentionally not cached (shouldCache) so the next check retries.
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
ttlMs: CACHE_TTL_MS,
shouldCache: (r) => !r.error,
load: async (key) => {
// This key is constructed below from our version and normalized settings.
const [current, source] = JSON.parse(key) as [string, UpdateSourceConfig];
const result = await fetchLatest(current, source);
load: async (current) => {
const result = await fetchLatest(current);
if (result.error) {
log.debug('update check failed: %s', result.error);
@@ -57,10 +117,7 @@ const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
},
});
async function fetchLatest(
current: string,
source: UpdateSourceConfig,
): Promise<UpdateCheckResult> {
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
const base: UpdateCheckResult = {
current,
latest: null,
@@ -74,43 +131,34 @@ async function fetchLatest(
try {
// `/releases/latest` already excludes drafts and prereleases, so this is
// stable-channel by construction.
const { data: rel } = await fetchRelease(
undefined,
source,
`SnowLuma/${current}`,
FETCH_TIMEOUT_MS,
);
const res = await fetch(LATEST_RELEASE_URL, {
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': `SnowLuma/${current}`,
'X-GitHub-Api-Version': '2022-11-28',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!rel || typeof rel !== 'object' || Array.isArray(rel)) {
return { ...base, error: 'invalid release info' };
if (!res.ok) {
return { ...base, error: `github ${res.status}` };
}
const tag =
'tag_name' in rel && typeof rel.tag_name === 'string' ? rel.tag_name.trim() : '';
const rel = (await res.json()) as GithubRelease;
const tag = (rel.tag_name ?? '').trim();
if (!tag) {
return { ...base, error: 'no tag' };
}
const latest = tag.startsWith('v') ? tag.slice(1) : tag;
if (!parseVersion(latest)) {
return { ...base, error: 'invalid release version' };
}
const latest = tag.replace(/^v/, '');
return {
current,
latest,
hasUpdate: compareVersions(latest, current) > 0,
htmlUrl: 'html_url' in rel && typeof rel.html_url === 'string' ? rel.html_url : null,
notes:
'body' in rel && typeof rel.body === 'string' && rel.body
? rel.body.slice(0, NOTES_MAX)
: null,
publishedAt:
'published_at' in rel && typeof rel.published_at === 'string'
? rel.published_at
: null,
htmlUrl: rel.html_url ?? null,
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
publishedAt: rel.published_at ?? null,
checkedAt: Date.now(),
};
} catch (e) {
@@ -124,26 +172,14 @@ async function fetchLatest(
* failures come back as a result with `error` set and `hasUpdate: false`, and
* are not cached so the next check retries.
*/
export async function getUpdateInfo(
force = false,
source?: UpdateSourceConfig,
): Promise<UpdateCheckResult> {
const current = APP_VERSION;
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
const current = currentVersion();
if (!isEnabled()) {
return { ...emptyResult(current), error: 'disabled' };
}
try {
return await updateCache.get(JSON.stringify([current, source ?? readUpdateSource()]), {
force,
});
} catch (error) {
return {
...emptyResult(current),
error: error instanceof Error ? error.message : String(error),
};
}
return updateCache.get(current, { force });
}
function emptyResult(current: string): UpdateCheckResult {

View File

@@ -1,80 +0,0 @@
import { Hono } from 'hono';
import type { HttpBindings } from '@hono/node-server';
import type { UpdateService } from '../update/service';
import { readUpdateSource, saveUpdateSource, testUpdateSources } from '../update/sources';
import {
normalizeUpdateSourceConfig,
type UpdateSourceConfig,
} from '@snowluma/common/update-source';
export function updateRoutes(service: UpdateService, restart: () => void) {
const app = new Hono<{ Bindings: HttpBindings }>();
app.get('/status', (c) => c.json(service.status()));
app.get('/sources', (c) => {
try {
return c.json({ config: readUpdateSource() });
} catch (error) {
return c.json({ message: error instanceof Error ? error.message : String(error) }, 500);
}
});
app.post('/sources', async (c) => {
let config: UpdateSourceConfig;
try {
config = normalizeUpdateSourceConfig(await c.req.json());
} catch (error) {
return c.json({ message: error instanceof Error ? error.message : String(error) }, 400);
}
try {
saveUpdateSource(config);
return c.json({
config,
saved: true,
applied: true,
online: true,
errors: [],
message: '更新来源已保存',
});
} catch (error) {
return c.json({ message: error instanceof Error ? error.message : String(error) }, 500);
}
});
app.post('/sources/test', async (c) => {
try {
return c.json({ results: await testUpdateSources(await c.req.json()) });
} catch (error) {
return c.json({ message: error instanceof Error ? error.message : String(error) }, 400);
}
});
app.post('/download', async (c) => {
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ message: '请求必须是 JSON 对象' }, 400);
}
if (!body || typeof body !== 'object' || !('version' in body)) {
return c.json({ message: '缺少更新版本' }, 400);
}
try {
service.start(body.version);
return c.json(service.status(), 202);
} catch (error) {
return c.json({ message: error instanceof Error ? error.message : String(error) }, 409);
}
});
app.post('/restart', (c) => {
try {
service.restart();
c.env.outgoing.once('finish', restart);
return c.json(service.status(), 202);
} catch (error) {
return c.json({ message: error instanceof Error ? error.message : String(error) }, 409);
}
});
return app;
}

View File

@@ -754,8 +754,9 @@ describe('apis/contacts / invite-card pending application', () => {
const api = new ContactsApi({ identity: { uin: '10001' } } as any);
expect(api.getGroupInviteCardSequence(12345)).toBeUndefined();
expect(api.rememberGroupInviteCardSequence(12345, 778899)).toBe(true);
expect(api.rememberGroupInviteCardSequence(12345, 778899)).toBe(false);
api.rememberGroupInviteCardSequence(12345, 778899);
api.rememberGroupInviteCardSequence(0, 1);
api.rememberGroupInviteCardSequence(1, 0);
expect(api.getGroupInviteCardSequence(12345)).toBe(778899);
expect(api.findGroupInviteCardGroupBySequence(778899)).toBe(12345);

View File

@@ -1,216 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import { deflateSync, gzipSync } from 'zlib';
import { buildApiContext, type OneBotInstanceContext } from '@snowluma/onebot/instance-context';
import type { Elem } from '@snowluma/proto-defs/element';
import type { LongMsgResult, RecvLongMsgReq, RecvLongMsgResp } from '@snowluma/proto-defs/longmsg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { ForwardApi } from '../../src/bridge/apis/forward';
import type { BridgeContext } from '../../src/bridge/bridge-context';
import { mockBridge } from './_helpers';
function forwardCard(format: 'xml' | 'lightApp', resId: string, key?: string): Elem {
const content =
format === 'xml'
? `<msg serviceID="35" m_resid="${resId}"${key ? ` m_fileName="${key}"` : ''} />`
: JSON.stringify({
app: 'com.tencent.multimsg',
meta: { detail: { resid: resId, uniseq: key } },
});
const data = Buffer.concat([Buffer.from([1]), deflateSync(Buffer.from(content))]);
return format === 'xml'
? { richMsg: { serviceId: 35, template1: data } }
: { lightApp: { data } };
}
function message(...elems: Elem[]): PushMsgBody {
return {
responseHead: {
fromUin: 20002,
fromUid: 'sender-uid',
grp: { groupUin: 12345, memberCard: 'alice' },
},
contentHead: { msgType: 82, sequence: 10, timestamp: 1700000000 },
body: { richText: { elems } },
};
}
function setup(downloads: Map<string, LongMsgResult>) {
const requested: string[] = [];
const bridge = mockBridge({
sendRawPacket: vi.fn(async (command: string, bytes: Uint8Array) => {
expect(command).toBe('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg');
const resId = protobuf_decode<RecvLongMsgReq>(bytes).info!.resId!;
requested.push(resId);
const data = downloads.get(resId);
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(
protobuf_encode<RecvLongMsgResp>({
result: {
resId,
payload: data
? gzipSync(protobuf_encode<LongMsgResult>(data))
: undefined,
},
}),
),
};
}),
});
const forward = new ForwardApi(bridge as unknown as BridgeContext);
const ctx = {
selfId: 10001,
bridge: { apis: { forward } },
converterCtx: {
selfId: 10001,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
},
} as unknown as OneBotInstanceContext;
return { api: buildApiContext(ctx), requested };
}
describe('get_forward_msg / nested downloads (#529)', () => {
it.each(['xml', 'lightApp'] as const)(
'resolves siblings and three levels of %s forwards from one outer payload',
async (format) => {
const outer = `nested-fetch-${format}-outer`;
const inner = `nested-fetch-${format}-inner`;
const sibling = `nested-fetch-${format}-sibling`;
const leaf = `nested-fetch-${format}-leaf`;
const { api, requested } = setup(
new Map([
[
outer,
{
action: [
{
actionCommand: 'MultiMsg',
actionData: {
msgBody: [
message(forwardCard(format, inner, 'inner-key')),
message(forwardCard(format, sibling, 'sibling-key')),
],
},
},
{
actionCommand: 'leaf-key',
actionData: {
msgBody: [
message(
{ text: { str: 'deepest content' } },
{
customFace: {
md5: Buffer.alloc(16, 0xab),
origUrl: 'https://example.com/forward.png',
width: 32,
height: 24,
},
},
),
],
},
},
{
actionCommand: 'sibling-key',
actionData: {
msgBody: [message({ text: { str: 'sibling content' } })],
},
},
{
actionCommand: 'inner-key',
actionData: {
msgBody: [message(forwardCard(format, leaf, 'leaf-key'))],
},
},
],
},
],
]),
);
const parent = await api.getForwardMsg(outer);
expect(parent.map((node) => node.message)).toEqual([
[{ type: 'forward', data: { id: inner } }],
[{ type: 'forward', data: { id: sibling } }],
]);
const middle = await api.getForwardMsg(inner);
expect(middle[0]!.message).toEqual([{ type: 'forward', data: { id: leaf } }]);
expect((await api.getForwardMsg(leaf))[0]).toMatchObject({
sender: { user_id: 20002, nickname: 'alice' },
time: 1700000000,
message: [
{ type: 'text', data: { text: 'deepest content' } },
{ type: 'image', data: { url: 'https://example.com/forward.png' } },
],
});
expect((await api.getForwardMsg(sibling))[0]!.message).toEqual([
{ type: 'text', data: { text: 'sibling content' } },
]);
expect(requested).toEqual([outer]);
},
);
it.each([undefined, 'unmatched-key'])(
'downloads by resId when the XML filename is %s and preserves empty-payload errors',
async (key) => {
const outer = `nested-fetch-fallback-${key}-outer`;
const inner = `nested-fetch-fallback-${key}-inner`;
const empty = `nested-fetch-fallback-${key}-empty`;
const { api, requested } = setup(
new Map([
[
outer,
{
action: [
{
actionCommand: 'MultiMsg',
actionData: {
msgBody: [
message(forwardCard('xml', inner, key)),
message(forwardCard('xml', empty, key)),
],
},
},
{
actionCommand: 'unrelated-key',
actionData: {
msgBody: [message({ text: { str: 'unrelated content' } })],
},
},
],
},
],
[
inner,
{
action: [
{
actionCommand: 'MultiMsg',
actionData: {
msgBody: [message({ text: { str: 'downloaded content' } })],
},
},
],
},
],
]),
);
await api.getForwardMsg(outer);
expect((await api.getForwardMsg(inner))[0]!.message).toEqual([
{ type: 'text', data: { text: 'downloaded content' } },
]);
await expect(api.getForwardMsg(empty)).rejects.toThrow(
'download forward message payload is empty',
);
expect(requested).toEqual([outer, inner, empty]);
},
);
});

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