lint
This commit is contained in:
871 files changed
+59051
-18949
No files matched your search
@@ -11,6 +11,9 @@ trim_trailing_whitespace = true
|
||||
[*.{json,yml,yaml,md}]
|
||||
indent_size = 2
|
||||
|
||||
[*.{ts,tsx,mts,cts}]
|
||||
indent_size = 4
|
||||
|
||||
[*.py]
|
||||
indent_size = 4
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Dependencies, build outputs and local tooling
|
||||
node_modules/
|
||||
.pnpm-store/
|
||||
dist/
|
||||
coverage/
|
||||
.turbo/
|
||||
.vite/
|
||||
.claude/
|
||||
dev/
|
||||
pnpm-lock.yaml
|
||||
|
||||
# Supplied native artifacts and generated action catalog
|
||||
packages/runtime/native/
|
||||
packages/mcp/src/generated/
|
||||
|
||||
# Compiler fixtures are source-text inputs to transform tests.
|
||||
packages/proton/test/fixtures/
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf",
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.ts", "*.tsx", "*.mts", "*.cts"],
|
||||
"options": {
|
||||
"tabWidth": 4
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -59,6 +59,8 @@ pnpm --filter @snowluma/onebot test # example: tests for the affected package
|
||||
pnpm --filter webui test # the frontend package has no @snowluma/ prefix
|
||||
```
|
||||
|
||||
TypeScript formatting uses the root [Prettier configuration](.prettierrc.json), [local ESLint formatting rules](eslint.format.config.ts), and [ignore list](.prettierignore). Use `pnpm format` for all TS/TSX/MTS/CTS files and `pnpm format:check` for a read-only check. For selected files, run `pnpm exec eslint --config eslint.format.config.ts --fix <paths>` followed by `pnpm exec prettier --write <paths>`. These commands enforce four-space indentation, braces around control-statement bodies, and blank lines around statement blocks while preserving other logical spacing. They are separate from CI and its code-quality lint rules. Generated catalogs and compiler fixtures retain their source formatting.
|
||||
|
||||
Use focused tests while iterating. Before handing off a code change, run the full checks required by CONTRIBUTING.md and report anything that could not run. [PR CI](.github/workflows/ci.yml) is the reference; `pnpm run ci` reproduces its commands locally, including dependency installation and the generated-catalog check.
|
||||
|
||||
- **Documentation-only changes:** verify links, paths, commands and `git diff --check`; runtime tests do not validate prose.
|
||||
@@ -79,7 +81,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful
|
||||
- **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content.
|
||||
- **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible.
|
||||
- **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter.
|
||||
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and two-space indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.
|
||||
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and four-space TypeScript indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.
|
||||
- **Keep diagnostics safe.** Use existing sanitization when recording external input. Credentials, private keys, private account data and unredacted captures do not belong in commits, fixtures or public reports.
|
||||
|
||||
## Generated files and related changes
|
||||
|
||||
+21
-1
@@ -104,7 +104,7 @@ git checkout -b fix/onebot-mention-encoding
|
||||
### 2. 写代码
|
||||
|
||||
- **保持改动聚焦**:一个 PR 只做一件事。顺手发现的其他问题请单独开 issue 或新 PR。
|
||||
- **跟随既有风格**:不要为了你个人偏好引入大规模格式化或重命名。
|
||||
- **跟随既有风格**:TypeScript 排版以仓库 Prettier 配置为准;普通功能或修复 PR 只格式化涉及的文件,避免混入无关的大规模格式化或重命名。
|
||||
- **写测试**:修 bug 时优先写一个能复现该 bug 的测试,确认它会 fail,再让它 pass。新增功能至少补上 happy path 的测试。
|
||||
- **不要添加无意义的注释**:标识符已经说清楚的事情不需要再写一遍。注释应当解释"为什么",而不是"做了什么"。
|
||||
|
||||
@@ -169,10 +169,30 @@ git push origin fix/onebot-mention-encoding
|
||||
### 代码风格
|
||||
|
||||
- TypeScript 严格模式,按 `tsconfig.base.json` 配置。
|
||||
- TypeScript 使用四空格缩进,控制语句始终带大括号。排版由根目录 [`.prettierrc.json`](./.prettierrc.json) 和独立的本地 [ESLint 格式规则](./eslint.format.config.ts) 管理;普通 `pnpm lint` 负责代码质量检查。
|
||||
- 优先用现有抽象,不要为"假想的未来需求"提前抽象。
|
||||
- 不要给内部函数加防御性的参数校验,除非是系统边界(用户输入、外部 API)。
|
||||
- 不要保留死代码、被注释掉的代码或者 `// TODO` 没有具体上下文的占位。
|
||||
|
||||
从仓库根目录运行本地格式化命令:
|
||||
|
||||
```bash
|
||||
pnpm format # 为全部 TS/TSX/MTS/CTS 补大括号、空行并排版
|
||||
pnpm format:check # 检查上述规则,不修改文件
|
||||
|
||||
# 只格式化指定文件:先处理控制语句与空行,再排版
|
||||
pnpm exec eslint --config eslint.format.config.ts --fix packages/core/src/index.ts
|
||||
pnpm exec prettier --write packages/core/src/index.ts
|
||||
```
|
||||
|
||||
格式化范围排除 [`.prettierignore`](./.prettierignore) 中的构建产物、生成文件和编译器测试夹具;普通源码与测试都参与格式化。这两个命令供本地使用,不接入 CI。
|
||||
|
||||
空行采用保守规则:在语句块前后留空行,保留已有逻辑分段,不强行拆开连续声明或普通调用,也不在每条 `return`、`break` 前插空行;共用同一分支的连续 `case` 标签保持相邻。JSON、YAML 等文件继续使用原有缩进。
|
||||
|
||||
编辑器请选择项目本地安装的 Prettier 并读取仓库配置。VS Code 可安装
|
||||
`esbenp.prettier-vscode`,将 TypeScript / TypeScript React 的默认格式化器设为
|
||||
Prettier,并按需开启保存时格式化。
|
||||
|
||||
### 测试
|
||||
|
||||
- 单测放在被测代码同包的 `tests/` 或同目录的 `*.test.ts`,按既有风格走。
|
||||
|
||||
+11
-7
@@ -1,14 +1,17 @@
|
||||
import js from '@eslint/js';
|
||||
import eslintConfigPrettier from 'eslint-config-prettier/flat';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import reactRefresh from 'eslint-plugin-react-refresh';
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1');
|
||||
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(
|
||||
/^\/(.:\/)/,
|
||||
'$1',
|
||||
);
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores([
|
||||
export const sourceIgnores = globalIgnores([
|
||||
'**/dist/**',
|
||||
'**/node_modules/**',
|
||||
'**/coverage/**',
|
||||
@@ -20,7 +23,10 @@ export default defineConfig([
|
||||
'**/test/fixtures/**',
|
||||
'packages/runtime/native/**',
|
||||
'packages/mcp/src/generated/**',
|
||||
]),
|
||||
]);
|
||||
|
||||
export default defineConfig([
|
||||
sourceIgnores,
|
||||
{
|
||||
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
|
||||
extends: [js.configs.recommended],
|
||||
@@ -33,7 +39,6 @@ export default defineConfig([
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'no-unused-vars': 'off',
|
||||
'no-useless-assignment': 'off',
|
||||
'prefer-const': 'off',
|
||||
@@ -49,7 +54,6 @@ export default defineConfig([
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'prefer-const': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/no-empty-object-type': 'off',
|
||||
@@ -99,10 +103,10 @@ export default defineConfig([
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'prefer-const': 'off',
|
||||
'react-refresh/only-export-components': 'off',
|
||||
'react-hooks/set-state-in-effect': 'off',
|
||||
},
|
||||
},
|
||||
eslintConfigPrettier,
|
||||
]);
|
||||
@@ -0,0 +1,39 @@
|
||||
import stylistic from '@stylistic/eslint-plugin';
|
||||
import { defineConfig } from 'eslint/config';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import { sourceIgnores } from './eslint.config.ts';
|
||||
|
||||
// Local formatting only; CI continues to use eslint.config.ts for code quality.
|
||||
export default defineConfig([
|
||||
sourceIgnores,
|
||||
{
|
||||
// Preserve quality-rule suppressions when running only formatting rules.
|
||||
linterOptions: { reportUnusedDisableDirectives: 'off' },
|
||||
},
|
||||
{
|
||||
files: ['**/*.{ts,tsx,mts,cts}'],
|
||||
languageOptions: {
|
||||
parser: tseslint.parser,
|
||||
},
|
||||
plugins: {
|
||||
'@stylistic': stylistic,
|
||||
'@typescript-eslint': tseslint.plugin,
|
||||
'react-hooks': reactHooks,
|
||||
},
|
||||
rules: {
|
||||
curly: ['error', 'all'],
|
||||
'@stylistic/padding-line-between-statements': [
|
||||
'error',
|
||||
{ blankLine: 'always', prev: '*', next: 'block-like' },
|
||||
{ blankLine: 'always', prev: 'block-like', next: '*' },
|
||||
// Stacked case labels share a branch and must stay adjacent.
|
||||
{
|
||||
blankLine: 'never',
|
||||
prev: { selector: 'SwitchCase[consequent.length=0]' },
|
||||
next: ['case', 'default'],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -25,6 +25,8 @@
|
||||
"typecheck": "pnpm -r --if-present typecheck",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"format": "eslint --config eslint.format.config.ts --fix \"**/*.{ts,tsx,mts,cts}\" && prettier --write \"**/*.{ts,tsx,mts,cts}\"",
|
||||
"format:check": "eslint --config eslint.format.config.ts \"**/*.{ts,tsx,mts,cts}\" && prettier --check \"**/*.{ts,tsx,mts,cts}\"",
|
||||
"ci": "node tools/ci-check.mjs",
|
||||
"start": "node dist/index.mjs",
|
||||
"bump": "node tools/bump-version.mjs",
|
||||
@@ -32,14 +34,17 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@stylistic/eslint-plugin": "5.10.0",
|
||||
"@vitest/coverage-istanbul": "4.1.4",
|
||||
"@vitest/coverage-v8": "^4.1.4",
|
||||
"cross-env": "^10.1.0",
|
||||
"eslint": "^10.2.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.5.0",
|
||||
"jiti": "^2.6.1",
|
||||
"prettier": "3.9.10",
|
||||
"typescript": "catalog:",
|
||||
"typescript-eslint": "^8.58.2"
|
||||
},
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
createLogger,
|
||||
runWithTraceRequest,
|
||||
type Logger,
|
||||
} from '@snowluma/common/logger';
|
||||
import { createLogger, runWithTraceRequest, type Logger } from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types';
|
||||
@@ -123,7 +119,10 @@ export class HookManager {
|
||||
this.injector = deps.injector ?? {
|
||||
inject: injectHookProcess,
|
||||
unload: (pid, handle) => {
|
||||
if (!handle) return;
|
||||
if (!handle) {
|
||||
return;
|
||||
}
|
||||
|
||||
unloadHookProcess(pid, handle);
|
||||
},
|
||||
};
|
||||
@@ -136,6 +135,7 @@ export class HookManager {
|
||||
if (deps.listProcesses) {
|
||||
const lister = deps.listProcesses;
|
||||
this.enumerator = null;
|
||||
|
||||
this.enumerate = async () => {
|
||||
try {
|
||||
return await lister();
|
||||
@@ -160,7 +160,8 @@ export class HookManager {
|
||||
} else {
|
||||
this.pipeWatcher = new PipeWatcher({
|
||||
listProcesses: this.enumerate,
|
||||
listLivePipes: processes => QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
|
||||
listLivePipes: (processes) =>
|
||||
QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
|
||||
intervalMs: deps.watcherIntervalMs,
|
||||
log: this.log,
|
||||
});
|
||||
@@ -176,19 +177,21 @@ export class HookManager {
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
await this.startPromise;
|
||||
const processes = await this.enumerate();
|
||||
|
||||
if (processes === null) {
|
||||
// Enumeration timed out / failed — report the last-known sessions rather
|
||||
// than an empty list (which the WebUI would render as "no QQ").
|
||||
return [...this.sessions.values()]
|
||||
.map((s) => s.toInfo())
|
||||
.sort((a, b) => a.pid - b.pid);
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -225,14 +228,20 @@ export class HookManager {
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.disposed = true;
|
||||
|
||||
for (const session of this.sessions.values()) {
|
||||
session.dispose();
|
||||
}
|
||||
|
||||
this.sessions.clear();
|
||||
this.autoLoadAttempts.clear();
|
||||
this.enumerator?.dispose();
|
||||
|
||||
if (this.ownsPipeWatcher) {
|
||||
this.pipeWatcher.dispose();
|
||||
}
|
||||
@@ -242,7 +251,10 @@ export class HookManager {
|
||||
|
||||
private bindWatcher(): void {
|
||||
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const session = this.ensureSession(info.pid);
|
||||
session.attachProcessInfo(info);
|
||||
@@ -252,6 +264,7 @@ export class HookManager {
|
||||
renderParamsVerbose(info),
|
||||
this.autoLoadOnDiscovery,
|
||||
]);
|
||||
|
||||
// Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets
|
||||
// injected without a human clicking "Load" in WebUI. Fire-and-forget:
|
||||
// failures are already captured inside loadInternal and surfaced via
|
||||
@@ -259,11 +272,15 @@ export class HookManager {
|
||||
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
|
||||
this.runAutoLoad(session);
|
||||
}
|
||||
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
});
|
||||
this.pipeWatcher.on('process-gone', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
this.autoLoadAttempts.delete(pid);
|
||||
const session = this.sessions.get(pid);
|
||||
@@ -272,19 +289,35 @@ export class HookManager {
|
||||
pid,
|
||||
session !== undefined,
|
||||
);
|
||||
if (session) session.notifyProcessGone();
|
||||
|
||||
if (session) {
|
||||
session.notifyProcessGone();
|
||||
}
|
||||
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
});
|
||||
this.pipeWatcher.on('pipe-up', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.onPipeUp();
|
||||
|
||||
if (session) {
|
||||
session.onPipeUp();
|
||||
}
|
||||
});
|
||||
this.pipeWatcher.on('pipe-down', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.onPipeDown();
|
||||
|
||||
if (session) {
|
||||
session.onPipeDown();
|
||||
}
|
||||
});
|
||||
// After every tick, retry sessions that are stuck in 'connecting' OR
|
||||
// 'disconnected' while the pipe is up. Mirrors the original
|
||||
@@ -301,18 +334,29 @@ export class HookManager {
|
||||
// for a while then stops" with logs `pipe error: read EPIPE` →
|
||||
// `session closed: UIN=…`.
|
||||
this.pipeWatcher.on('tick', () => {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const session of this.sessions.values()) {
|
||||
const autoLoad = this.autoLoadAttempts.get(session.pid);
|
||||
if (autoLoad && !autoLoad.inFlight && session.status === 'error'
|
||||
&& isTransientLibcMappingError(session.error)) {
|
||||
|
||||
if (
|
||||
autoLoad &&
|
||||
!autoLoad.inFlight &&
|
||||
session.status === 'error' &&
|
||||
isTransientLibcMappingError(session.error)
|
||||
) {
|
||||
this.runAutoLoad(session, autoLoad);
|
||||
continue;
|
||||
}
|
||||
if ((session.status === 'connecting'
|
||||
|| session.status === 'disconnected'
|
||||
|| session.status === 'error')
|
||||
&& this.pipeWatcher.isPipeLive(session.pid)) {
|
||||
|
||||
if (
|
||||
(session.status === 'connecting' ||
|
||||
session.status === 'disconnected' ||
|
||||
session.status === 'error') &&
|
||||
this.pipeWatcher.isPipeLive(session.pid)
|
||||
) {
|
||||
session.onPipeUp();
|
||||
}
|
||||
}
|
||||
@@ -320,9 +364,15 @@ export class HookManager {
|
||||
}
|
||||
|
||||
private runAutoLoad(session: HookSession, existing?: AutoLoadAttempt): void {
|
||||
if (this.disposed || session.isDisposed) return;
|
||||
if (this.disposed || session.isDisposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const state = existing ?? { attempts: 0, inFlight: false };
|
||||
if (state.inFlight || state.attempts >= AUTO_LOAD_MAX_ATTEMPTS) return;
|
||||
|
||||
if (state.inFlight || state.attempts >= AUTO_LOAD_MAX_ATTEMPTS) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.attempts += 1;
|
||||
state.inFlight = true;
|
||||
@@ -337,8 +387,10 @@ export class HookManager {
|
||||
attempt,
|
||||
AUTO_LOAD_MAX_ATTEMPTS,
|
||||
);
|
||||
|
||||
try {
|
||||
const info = await session.load();
|
||||
|
||||
if (this.autoLoadAttempts.get(session.pid) !== state) {
|
||||
this.log.trace(
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=dropped reason=superseded elapsedMs=%d',
|
||||
@@ -348,6 +400,7 @@ export class HookManager {
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
state.inFlight = false;
|
||||
|
||||
if (info.status !== 'error') {
|
||||
@@ -361,6 +414,7 @@ export class HookManager {
|
||||
renderParamsVerbose(info),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
|
||||
if (attempt > 1) {
|
||||
this.log.info(
|
||||
'auto-load recovered: PID=%d attempt=%d/%d',
|
||||
@@ -369,6 +423,7 @@ export class HookManager {
|
||||
AUTO_LOAD_MAX_ATTEMPTS,
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -420,6 +475,7 @@ export class HookManager {
|
||||
if (this.autoLoadAttempts.get(session.pid) === state) {
|
||||
this.autoLoadAttempts.delete(session.pid);
|
||||
}
|
||||
|
||||
this.log.trace(
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=unexpected_failure error=%j elapsedMs=%d',
|
||||
session.pid,
|
||||
@@ -434,7 +490,10 @@ export class HookManager {
|
||||
|
||||
private ensureSession(pid: number): HookSession {
|
||||
let session = this.sessions.get(pid);
|
||||
if (session) return session;
|
||||
|
||||
if (session) {
|
||||
return session;
|
||||
}
|
||||
|
||||
session = new HookSession(pid, {
|
||||
injector: this.injector,
|
||||
@@ -449,7 +508,9 @@ export class HookManager {
|
||||
this.bridgeManager.onHookLogin(pid, uin, sender);
|
||||
});
|
||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
if (wasLoggedIn) {
|
||||
this.bridgeManager.onPidDisconnected(pid);
|
||||
}
|
||||
});
|
||||
session.on('receive-health-changed', (healthy: boolean) => {
|
||||
this.bridgeManager.onPidReceiveHealthChanged(pid, healthy);
|
||||
@@ -472,8 +533,14 @@ export class HookManager {
|
||||
* A throwing subscriber must not abort the watcher's emit loop or break
|
||||
* a HookSession event handler in flight. */
|
||||
private notifySessionsChanged(): void {
|
||||
if (this.disposed) return;
|
||||
if (!this.onSessionsChangedRaw) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.onSessionsChangedRaw) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this.onSessionsChangedRaw();
|
||||
} catch (err) {
|
||||
@@ -482,7 +549,9 @@ export class HookManager {
|
||||
}
|
||||
|
||||
private assertValidPid(pid: number): void {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
if (!Number.isInteger(pid) || pid <= 0) {
|
||||
throw new Error('invalid pid');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -512,12 +581,18 @@ function isTransientLibcMappingError(error: string): boolean {
|
||||
* for picking the right PID from WebUI.
|
||||
*/
|
||||
export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
|
||||
if (process.platform !== 'linux') return true;
|
||||
if (process.platform !== 'linux') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Escape hatch: operators who explicitly want auto-load on every
|
||||
// enumerated PID can set this to opt out of the filter.
|
||||
if (process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL === '1') return true;
|
||||
if (process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL === '1') {
|
||||
return true;
|
||||
}
|
||||
|
||||
let cmdline: string;
|
||||
|
||||
try {
|
||||
cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
|
||||
} catch {
|
||||
@@ -526,13 +601,16 @@ export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
|
||||
// will fail with a clear error.
|
||||
return true;
|
||||
}
|
||||
|
||||
if (cmdline.includes('--type=')) {
|
||||
const type = (/--type=([^\0\s]+)/.exec(cmdline)?.[1]) ?? 'unknown';
|
||||
const type = /--type=([^\0\s]+)/.exec(cmdline)?.[1] ?? 'unknown';
|
||||
log.info('auto-load skip: PID=%d is an Electron child process (--type=%s)', pid, type);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export type { HookProcessBaseInfo } from './injector';
|
||||
export type { QqPortLoginInfo } from './qq-port-probe';
|
||||
export type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
@@ -17,16 +17,26 @@ export class HookPacketClient implements PacketSender {
|
||||
private readonly onOutboundHealthChanged?: OutboundHealthListener,
|
||||
) {}
|
||||
|
||||
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
|
||||
async sendPacket(
|
||||
serviceCmd: string,
|
||||
body: Buffer,
|
||||
timeoutMs = packetTimeoutMs(),
|
||||
): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: 'qq_hook client is not logged in',
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const reply = await this.client.send(serviceCmd, body, {
|
||||
const reply = (await this.client.send(serviceCmd, body, {
|
||||
wantReply: true,
|
||||
replyTimeoutMs: timeoutMs,
|
||||
}) as QqHookSendReply;
|
||||
})) as QqHookSendReply;
|
||||
this.setOutboundHealthy(true);
|
||||
return {
|
||||
success: reply.error === 0,
|
||||
@@ -36,10 +46,13 @@ export class HookPacketClient implements PacketSender {
|
||||
responseData: reply.body,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof HookPipeRequestError
|
||||
&& error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE) {
|
||||
if (
|
||||
error instanceof HookPipeRequestError &&
|
||||
error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE
|
||||
) {
|
||||
this.setOutboundHealthy(false);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
@@ -51,7 +64,10 @@ export class HookPacketClient implements PacketSender {
|
||||
}
|
||||
|
||||
private setOutboundHealthy(healthy: boolean): void {
|
||||
if (this.outboundHealthy === healthy) return;
|
||||
if (this.outboundHealthy === healthy) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.outboundHealthy = healthy;
|
||||
this.onOutboundHealthChanged?.(healthy);
|
||||
}
|
||||
|
||||
@@ -10,27 +10,44 @@ export interface HookRuntimeDirDeps {
|
||||
}
|
||||
|
||||
function configuredDirectory(value: string | undefined, variable: string): string | null {
|
||||
if (!value) return null;
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!path.isAbsolute(value)) {
|
||||
throw new Error(`${variable} must be an absolute path`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseProcessEnvironment(raw: string): NodeJS.ProcessEnv {
|
||||
const result: NodeJS.ProcessEnv = {};
|
||||
|
||||
for (const entry of raw.split('\0')) {
|
||||
if (!entry) continue;
|
||||
if (!entry) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const separator = entry.indexOf('=');
|
||||
if (separator <= 0) continue;
|
||||
|
||||
if (separator <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result[entry.slice(0, separator)] = entry.slice(separator + 1);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseRealUid(status: string): number | null {
|
||||
const match = /^Uid:\s+(\d+)/m.exec(status);
|
||||
if (!match) return null;
|
||||
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const uid = Number(match[1]);
|
||||
return Number.isSafeInteger(uid) && uid >= 0 ? uid : null;
|
||||
}
|
||||
@@ -44,24 +61,30 @@ function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function ownRuntimeDir(
|
||||
platform: NodeJS.Platform,
|
||||
env: NodeJS.ProcessEnv,
|
||||
ownUid: number,
|
||||
): string {
|
||||
function ownRuntimeDir(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, ownUid: number): string {
|
||||
const explicit = configuredDirectory(
|
||||
env.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
'SNOWLUMA_HOOK_RUNTIME_DIR',
|
||||
);
|
||||
if (explicit) return explicit;
|
||||
|
||||
if (explicit) {
|
||||
return explicit;
|
||||
}
|
||||
|
||||
const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR');
|
||||
if (xdg) return xdg;
|
||||
|
||||
if (xdg) {
|
||||
return xdg;
|
||||
}
|
||||
|
||||
if (platform === 'darwin') {
|
||||
const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR');
|
||||
if (tmpdir) return path.join(tmpdir, 'snowluma-hook');
|
||||
|
||||
if (tmpdir) {
|
||||
return path.join(tmpdir, 'snowluma-hook');
|
||||
}
|
||||
}
|
||||
|
||||
return `/tmp/snowluma-${ownUid}`;
|
||||
}
|
||||
|
||||
@@ -69,14 +92,12 @@ function ownRuntimeDir(
|
||||
* Resolve the socket directory for the target QQ process. The supervisor may
|
||||
* run under a different user, so its own runtime directory is not authoritative.
|
||||
*/
|
||||
export function resolveHookRuntimeDir(
|
||||
targetPid?: number,
|
||||
deps: HookRuntimeDirDeps = {},
|
||||
): string {
|
||||
export function resolveHookRuntimeDir(targetPid?: number, deps: HookRuntimeDirDeps = {}): string {
|
||||
const platform = deps.platform ?? process.platform;
|
||||
const env = deps.env ?? process.env;
|
||||
const ownUid = deps.ownUid
|
||||
?? (typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid);
|
||||
const ownUid =
|
||||
deps.ownUid ??
|
||||
(typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid);
|
||||
const readText = deps.readText ?? ((file: string) => readFileSync(file, 'utf8'));
|
||||
|
||||
if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) {
|
||||
@@ -84,18 +105,27 @@ export function resolveHookRuntimeDir(
|
||||
}
|
||||
|
||||
let environError: unknown;
|
||||
|
||||
try {
|
||||
const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`));
|
||||
const explicit = configuredDirectory(
|
||||
targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
`QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`,
|
||||
);
|
||||
if (explicit) return explicit;
|
||||
|
||||
if (explicit) {
|
||||
return explicit;
|
||||
}
|
||||
|
||||
const xdg = configuredDirectory(
|
||||
targetEnv.XDG_RUNTIME_DIR,
|
||||
`QQ process ${targetPid} XDG_RUNTIME_DIR`,
|
||||
);
|
||||
if (xdg) return xdg;
|
||||
|
||||
if (xdg) {
|
||||
return xdg;
|
||||
}
|
||||
|
||||
environError = new Error('runtime directory is not present');
|
||||
} catch (error) {
|
||||
// An invalid explicit path is configuration corruption and must remain
|
||||
@@ -104,27 +134,35 @@ export function resolveHookRuntimeDir(
|
||||
if (error instanceof Error && error.message.includes('must be an absolute path')) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
environError = error;
|
||||
}
|
||||
|
||||
let statusError: unknown;
|
||||
|
||||
try {
|
||||
const uid = parseRealUid(readText(`/proc/${targetPid}/status`));
|
||||
if (uid !== null) return `/tmp/snowluma-${uid}`;
|
||||
|
||||
if (uid !== null) {
|
||||
return `/tmp/snowluma-${uid}`;
|
||||
}
|
||||
|
||||
statusError = new Error('real uid is not available');
|
||||
} catch (error) {
|
||||
statusError = error;
|
||||
}
|
||||
|
||||
if (isProcessGoneError(statusError)
|
||||
&& (isProcessGoneError(environError)
|
||||
|| (environError instanceof Error
|
||||
&& environError.message === 'runtime directory is not present'))) {
|
||||
if (
|
||||
isProcessGoneError(statusError) &&
|
||||
(isProcessGoneError(environError) ||
|
||||
(environError instanceof Error &&
|
||||
environError.message === 'runtime directory is not present'))
|
||||
) {
|
||||
return ownRuntimeDir(platform, env, ownUid);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`cannot resolve hook runtime directory for PID ${targetPid}: `
|
||||
+ `environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`,
|
||||
`cannot resolve hook runtime directory for PID ${targetPid}: ` +
|
||||
`environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`,
|
||||
);
|
||||
}
|
||||
@@ -129,18 +129,33 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
// ─────────────── readonly public surface ───────────────
|
||||
|
||||
get status(): HookProcessStatus { return this._status; }
|
||||
get error(): string { return this._error; }
|
||||
get uin(): string { return this._uin; }
|
||||
get method(): string { return this._method; }
|
||||
get isDisposed(): boolean { return this.disposed; }
|
||||
get status(): HookProcessStatus {
|
||||
return this._status;
|
||||
}
|
||||
get error(): string {
|
||||
return this._error;
|
||||
}
|
||||
get uin(): string {
|
||||
return this._uin;
|
||||
}
|
||||
get method(): string {
|
||||
return this._method;
|
||||
}
|
||||
get isDisposed(): boolean {
|
||||
return this.disposed;
|
||||
}
|
||||
get receiveHealthy(): boolean {
|
||||
return this._receiveHealthy && this._outboundHealthy;
|
||||
}
|
||||
|
||||
attachProcessInfo(info: { name?: string; path?: string }): void {
|
||||
if (info.name) this._name = info.name;
|
||||
if (info.path) this._path = info.path;
|
||||
if (info.name) {
|
||||
this._name = info.name;
|
||||
}
|
||||
|
||||
if (info.path) {
|
||||
this._path = info.path;
|
||||
}
|
||||
}
|
||||
|
||||
toInfo(): HookProcessInfo {
|
||||
@@ -178,27 +193,45 @@ export class HookSession extends EventEmitter {
|
||||
* attempts and adopts pre-existing hooks. Idempotent; safe to call on
|
||||
* every watcher tick where the pipe is live. */
|
||||
onPipeUp(): void {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.reconcilePipeUp();
|
||||
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}).catch((err) => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
onPipeDown(): void {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.reconcilePipeDown();
|
||||
}).catch(err => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}).catch((err) => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
/** Called by the manager when the watcher reports the QQ.exe process is
|
||||
* gone. Cleans up and signals the manager to remove this session. */
|
||||
notifyProcessGone(): void {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
@@ -212,8 +245,12 @@ export class HookSession extends EventEmitter {
|
||||
this.injectResult = null;
|
||||
this._method = '';
|
||||
this.setStatus('available', '');
|
||||
|
||||
try {
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
if (wasLoggedIn) {
|
||||
this.emit('disconnected', true);
|
||||
}
|
||||
|
||||
this.disposed = true;
|
||||
this.emit('disposed');
|
||||
this.log.trace(() => [
|
||||
@@ -235,18 +272,27 @@ export class HookSession extends EventEmitter {
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}).catch((err) =>
|
||||
this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)),
|
||||
);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.disposed = true;
|
||||
this.tearDownClient();
|
||||
|
||||
// Process shutdown must take the same PID-detach path as a live drop.
|
||||
// tearDownClient strips the pipe client first, so this emit is the only
|
||||
// disconnected edge HookManager will see.
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
if (wasLoggedIn) {
|
||||
this.emit('disconnected', true);
|
||||
}
|
||||
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
@@ -264,13 +310,16 @@ export class HookSession extends EventEmitter {
|
||||
operation,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
]);
|
||||
|
||||
try {
|
||||
const info = await this.serialize(command);
|
||||
const outcome = info.status === 'error'
|
||||
|| (operation === 'unload' && info.status !== 'available')
|
||||
const outcome =
|
||||
info.status === 'error' ||
|
||||
(operation === 'unload' && info.status !== 'available')
|
||||
? 'failed'
|
||||
: 'completed';
|
||||
let reason: string;
|
||||
|
||||
if (operation === 'unload' && info.status === 'connecting') {
|
||||
reason = 'unload_verification_failed';
|
||||
} else if (outcome === 'failed') {
|
||||
@@ -278,6 +327,7 @@ export class HookSession extends EventEmitter {
|
||||
} else {
|
||||
reason = `${operation}_settled`;
|
||||
}
|
||||
|
||||
this.log.trace(() => [
|
||||
'hook_session_terminal pid=%d operation=%s outcome=%s reason=%s%s state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
@@ -307,7 +357,9 @@ export class HookSession extends EventEmitter {
|
||||
private serialize<T>(op: () => Promise<T>): Promise<T> {
|
||||
const previous = this.opChain;
|
||||
let release!: () => void;
|
||||
const completion = new Promise<void>(resolve => { release = resolve; });
|
||||
const completion = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
this.opChain = previous.then(() => completion);
|
||||
return (async () => {
|
||||
try {
|
||||
@@ -324,6 +376,7 @@ export class HookSession extends EventEmitter {
|
||||
private async loadInternal(): Promise<HookProcessInfo> {
|
||||
this._error = '';
|
||||
this.setStatus('loading', '');
|
||||
|
||||
try {
|
||||
if (!this.injected) {
|
||||
// Fast path: a previous SnowLuma run may have left the hook DLL
|
||||
@@ -353,6 +406,7 @@ export class HookSession extends EventEmitter {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this.applyStatus();
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
@@ -363,22 +417,29 @@ export class HookSession extends EventEmitter {
|
||||
// call returned. A live pipe still has the account state, so connect
|
||||
// instead of staying on the failed load.
|
||||
await this.pipeWatcher.tickNow?.();
|
||||
|
||||
if (!this.disposed && this.pipeWatcher.isPipeLive(this.pid)) {
|
||||
this.log.info('PID=%d load failed but pipe is up; connecting', this.pid);
|
||||
await this.reconcilePipeUp();
|
||||
}
|
||||
}
|
||||
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
private async unloadInternal(): Promise<HookProcessInfo> {
|
||||
this._error = '';
|
||||
|
||||
try {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
|
||||
if (wasLoggedIn) {
|
||||
this.emit('disconnected', true);
|
||||
}
|
||||
|
||||
const handle = this.injectResult?.handle;
|
||||
|
||||
if (this.injected && handle) {
|
||||
this.injector.unload(this.pid, handle);
|
||||
this.log.info('SnowLuma unloaded from PID=%d', this.pid);
|
||||
@@ -395,6 +456,7 @@ export class HookSession extends EventEmitter {
|
||||
// a successful unload reads as "pipe still live" until the next
|
||||
// background tick runs and we'd report a spurious failure.
|
||||
await this.pipeWatcher.tickNow?.();
|
||||
|
||||
if (this.pipeWatcher.isPipeLive(this.pid)) {
|
||||
this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
|
||||
this.setStatus('connecting', this._error);
|
||||
@@ -407,11 +469,13 @@ export class HookSession extends EventEmitter {
|
||||
this.setStatus('error', this._error);
|
||||
this.log.error('unload failed: PID=%d err=%s', this.pid, this._error);
|
||||
}
|
||||
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
private async refreshInternal(): Promise<HookProcessInfo> {
|
||||
this._error = '';
|
||||
|
||||
try {
|
||||
// Same pipe-up / pipe-down reconcilers the watcher drives, chosen by
|
||||
// a fresh poll. This collapses what used to be a hand-copied pair of
|
||||
@@ -427,6 +491,7 @@ export class HookSession extends EventEmitter {
|
||||
this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
|
||||
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
|
||||
}
|
||||
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
@@ -436,12 +501,15 @@ export class HookSession extends EventEmitter {
|
||||
* defaults to the current `loggedIn`; callers that just tore the client
|
||||
* down pass the value captured *before* teardown (teardown clears it). */
|
||||
private applyStatus(wasLoggedIn: boolean = this.loggedIn, error = ''): void {
|
||||
this.setStatus(statusFor({
|
||||
this.setStatus(
|
||||
statusFor({
|
||||
injected: this.injected,
|
||||
connected: this.connected,
|
||||
loggedIn: this.loggedIn,
|
||||
wasLoggedIn,
|
||||
}), error);
|
||||
}),
|
||||
error,
|
||||
);
|
||||
}
|
||||
|
||||
/** Pipe is up: adopt a DLL that survived a SnowLuma restart, drop a
|
||||
@@ -450,9 +518,16 @@ export class HookSession extends EventEmitter {
|
||||
private async reconcilePipeUp(): Promise<void> {
|
||||
if (!this.injected) {
|
||||
this.injected = true;
|
||||
if (!this._method) this._method = 'reconnect';
|
||||
|
||||
if (!this._method) {
|
||||
this._method = 'reconnect';
|
||||
}
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
}
|
||||
|
||||
if (this.client?.isClosed) {
|
||||
this.tearDownClient();
|
||||
}
|
||||
|
||||
if (!this.connected) {
|
||||
await this.attemptConnect();
|
||||
} else {
|
||||
@@ -470,9 +545,13 @@ export class HookSession extends EventEmitter {
|
||||
// a disconnect, and we must NOT clobber a diagnostic the failed
|
||||
// connect/load already set — settle the status keeping `_error`, or
|
||||
// (when not even injected) leave the status untouched entirely.
|
||||
if (this.injected) this.applyStatus(this.loggedIn, this._error);
|
||||
if (this.injected) {
|
||||
this.applyStatus(this.loggedIn, this._error);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
@@ -483,8 +562,12 @@ export class HookSession extends EventEmitter {
|
||||
]);
|
||||
this.tearDownClient();
|
||||
this.applyStatus(wasLoggedIn);
|
||||
|
||||
try {
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
if (wasLoggedIn) {
|
||||
this.emit('disconnected', true);
|
||||
}
|
||||
|
||||
this.log.trace(() => [
|
||||
'hook_session_disconnect_terminal pid=%d outcome=completed reason=pipe_down wasLoggedIn=%s state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
@@ -508,7 +591,10 @@ export class HookSession extends EventEmitter {
|
||||
// ─────────────── client plumbing ───────────────
|
||||
|
||||
private async attemptConnect(): Promise<void> {
|
||||
if (this.connected) return;
|
||||
if (this.connected) {
|
||||
return;
|
||||
}
|
||||
|
||||
return runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
this.log.trace(() => [
|
||||
@@ -516,25 +602,31 @@ export class HookSession extends EventEmitter {
|
||||
this.pid,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
]);
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
|
||||
if (this.client?.isClosed) {
|
||||
this.tearDownClient();
|
||||
}
|
||||
|
||||
if (!this.client) {
|
||||
this.client = this.makeClient(this.pid);
|
||||
this.sender = new HookPacketClient(
|
||||
this.client,
|
||||
healthy => this.setOutboundHealthy(healthy),
|
||||
this.sender = new HookPacketClient(this.client, (healthy) =>
|
||||
this.setOutboundHealthy(healthy),
|
||||
);
|
||||
this.bound = false;
|
||||
}
|
||||
|
||||
if (!this.bound) {
|
||||
this.bindClient(this.client);
|
||||
this.bound = true;
|
||||
}
|
||||
|
||||
const client = this.client;
|
||||
|
||||
try {
|
||||
await client.connectAll({ recv: true });
|
||||
this.connected = true;
|
||||
const loginState = client.getLoginState();
|
||||
|
||||
// handleLoginState owns the connected+loggedIn → 'online' (+ login
|
||||
// emit) transition; defer to it so the status is set once. Otherwise
|
||||
// we're connected-but-not-logged-in → 'loaded'.
|
||||
@@ -547,6 +639,7 @@ export class HookSession extends EventEmitter {
|
||||
// is missed and we'd wait forever. Actively re-probe until logged in.
|
||||
runWithoutRequestContext(() => this.startLoginReconcile());
|
||||
}
|
||||
|
||||
this.log.info('pipe connected: PID=%d', this.pid);
|
||||
this.log.trace(() => [
|
||||
'hook_session_connect_terminal pid=%d outcome=completed reason=connect_settled state=%s elapsedMs=%d',
|
||||
@@ -572,23 +665,37 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
private bindClient(client: QqHookClient): void {
|
||||
client.on('packet', packet => this.handlePacket(packet));
|
||||
client.on('loginState', state => this.handleLoginState(state));
|
||||
client.on('error', error => {
|
||||
client.on('packet', (packet) => this.handlePacket(packet));
|
||||
client.on('loginState', (state) => this.handleLoginState(state));
|
||||
client.on('error', (error) => {
|
||||
const msg = errMsg(error);
|
||||
this._error = msg;
|
||||
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
|
||||
});
|
||||
client.on('close', () => {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only the currently-registered client should drive a reconcile;
|
||||
// listeners may fire for an already-replaced client.
|
||||
if (this.client !== client) return;
|
||||
if (this.client !== client) {
|
||||
return;
|
||||
}
|
||||
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
if (this.client !== client) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.client !== client) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.reconcilePipeDown();
|
||||
}).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}).catch((err) =>
|
||||
this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -596,10 +703,17 @@ export class HookSession extends EventEmitter {
|
||||
this.stopLoginReconcile();
|
||||
this.resetReceiveWatch();
|
||||
const client = this.client;
|
||||
|
||||
if (client) {
|
||||
client.removeAllListeners();
|
||||
try { client.close(); } catch { /* ignore */ }
|
||||
|
||||
try {
|
||||
client.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
this.client = null;
|
||||
this.sender = null;
|
||||
this.bound = false;
|
||||
@@ -614,9 +728,11 @@ export class HookSession extends EventEmitter {
|
||||
const previousUin = this._uin;
|
||||
this._uin = state.uin || state.uinNumber.toString();
|
||||
this.loggedIn = state.loggedIn && isRealUin(this._uin);
|
||||
|
||||
// Login readiness has now been confirmed, so identity probing is done.
|
||||
if (this.loggedIn) {
|
||||
this.stopLoginReconcile();
|
||||
|
||||
// A PID can switch accounts without an intermediate logout edge. Never
|
||||
// carry the previous account's heartbeat deadline into the new epoch.
|
||||
if (this.receiveWatchUin !== this._uin) {
|
||||
@@ -638,8 +754,13 @@ export class HookSession extends EventEmitter {
|
||||
this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error);
|
||||
}
|
||||
|
||||
if (!this.loggedIn || !this.sender) return;
|
||||
if (wasLoggedIn && previousUin === this._uin) return;
|
||||
if (!this.loggedIn || !this.sender) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (wasLoggedIn && previousUin === this._uin) {
|
||||
return;
|
||||
}
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
@@ -649,6 +770,7 @@ export class HookSession extends EventEmitter {
|
||||
previousUin,
|
||||
this._uin,
|
||||
);
|
||||
|
||||
try {
|
||||
this.emit('login', this._uin, this.sender!);
|
||||
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
|
||||
@@ -679,10 +801,16 @@ export class HookSession extends EventEmitter {
|
||||
// online state from the probe.
|
||||
|
||||
private startLoginReconcile(): void {
|
||||
if (this.loginProbeTimer || this.disposed) return;
|
||||
if (this.loginProbeTimer || this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.log.info('awaiting login: PID=%d', this.pid);
|
||||
void this.probeLoginOnce(); // immediate — catch already-logged-in fast
|
||||
this.loginProbeTimer = setInterval(() => void this.probeLoginOnce(), LOGIN_RECONCILE_INTERVAL_MS);
|
||||
this.loginProbeTimer = setInterval(
|
||||
() => void this.probeLoginOnce(),
|
||||
LOGIN_RECONCILE_INTERVAL_MS,
|
||||
);
|
||||
this.loginProbeTimer.unref?.();
|
||||
}
|
||||
|
||||
@@ -696,52 +824,98 @@ export class HookSession extends EventEmitter {
|
||||
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;
|
||||
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
|
||||
if (Date.now() < this.nextLoginIdentityObservationAt) return;
|
||||
if (this.probing) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.disposed || !this.connected || this.loggedIn) {
|
||||
this.stopLoginReconcile();
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() < this.nextLoginIdentityObservationAt) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.probing = true;
|
||||
|
||||
try {
|
||||
let info: QqPortLoginInfo | null;
|
||||
|
||||
try {
|
||||
info = await this.probeLogin(this.pid);
|
||||
} catch (error) {
|
||||
const message = errMsg(error);
|
||||
const note = `${this.pid}:${message}`;
|
||||
|
||||
if (this.lastProbeFailure !== note) {
|
||||
this.lastProbeFailure = note;
|
||||
this.log.warn('login probe failed: PID=%d err=%s', this.pid, message);
|
||||
}
|
||||
|
||||
return; // best-effort; the interval retries
|
||||
}
|
||||
|
||||
// The await yielded — re-check we still want this before mutating state.
|
||||
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
|
||||
if (info?.identityKnown && isRealUin(info.uin)) {
|
||||
const client = this.client;
|
||||
if (!client) return;
|
||||
if (this.acceptedLoginHintUin === info.uin) {
|
||||
this.nextLoginIdentityObservationAt = Date.now()
|
||||
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
if (this.disposed || !this.connected || this.loggedIn) {
|
||||
this.stopLoginReconcile();
|
||||
return;
|
||||
}
|
||||
|
||||
if (info?.identityKnown && isRealUin(info.uin)) {
|
||||
const client = this.client;
|
||||
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.acceptedLoginHintUin === info.uin) {
|
||||
this.nextLoginIdentityObservationAt =
|
||||
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.loginHintAttemptUin !== info.uin) {
|
||||
this.loginHintAttemptUin = info.uin;
|
||||
this.loginHintAttempts = 0;
|
||||
this.nextLoginHintAt = 0;
|
||||
this.nextLoginIdentityObservationAt = 0;
|
||||
}
|
||||
if (this.loginHintAttempts >= LOGIN_HINT_MAX_ATTEMPTS
|
||||
|| Date.now() < this.nextLoginHintAt) return;
|
||||
|
||||
if (
|
||||
this.loginHintAttempts >= LOGIN_HINT_MAX_ATTEMPTS ||
|
||||
Date.now() < this.nextLoginHintAt
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const attempt = ++this.loginHintAttempts;
|
||||
this.log.info('login identity discovered: PID=%d UIN=%s; awaiting readiness', this.pid, info.uin);
|
||||
this.log.info(
|
||||
'login identity discovered: PID=%d UIN=%s; awaiting readiness',
|
||||
this.pid,
|
||||
info.uin,
|
||||
);
|
||||
|
||||
try {
|
||||
await client.reconcileLoginIdentity(info.uin);
|
||||
if (this.client !== client || this.disposed || !this.connected || this.loggedIn) return;
|
||||
|
||||
if (
|
||||
this.client !== client ||
|
||||
this.disposed ||
|
||||
!this.connected ||
|
||||
this.loggedIn
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.acceptedLoginHintUin = info.uin;
|
||||
this.nextLoginIdentityObservationAt = Date.now()
|
||||
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
this.nextLoginIdentityObservationAt =
|
||||
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
} catch (error) {
|
||||
if (this.client !== client || this.disposed) return;
|
||||
if (this.client !== client || this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (attempt >= LOGIN_HINT_MAX_ATTEMPTS) {
|
||||
this.log.warn(
|
||||
'login identity reconciliation failed: PID=%d UIN=%s attempts=%d err=%s',
|
||||
@@ -750,11 +924,11 @@ export class HookSession extends EventEmitter {
|
||||
attempt,
|
||||
errMsg(error),
|
||||
);
|
||||
this.nextLoginIdentityObservationAt = Date.now()
|
||||
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
this.nextLoginIdentityObservationAt =
|
||||
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
} else {
|
||||
this.nextLoginHintAt = Date.now()
|
||||
+ LOGIN_HINT_RETRY_DELAYS_MS[attempt - 1]!;
|
||||
this.nextLoginHintAt =
|
||||
Date.now() + LOGIN_HINT_RETRY_DELAYS_MS[attempt - 1]!;
|
||||
this.log.trace(
|
||||
'login identity hint failed: PID=%d UIN=%s attempt=%d err=%s',
|
||||
this.pid,
|
||||
@@ -780,15 +954,28 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
private handlePacket(packet: QqHookPacket): void {
|
||||
if (!this.loggedIn) return;
|
||||
if (!this.loggedIn) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uin = packet.uin || this._uin;
|
||||
// Routing requires a real UIN, but even a frame carrying UIN=0 proves the
|
||||
// receive hook is alive. Attribute that evidence to the current epoch
|
||||
// without forwarding the malformed packet into BridgeManager.
|
||||
const receiveUin = isRealUin(uin) ? uin : (this.receiveWatchUin || this._uin);
|
||||
if (isRealUin(receiveUin)) this.noteReceiveActivity(packet.cmd, receiveUin);
|
||||
if (!isRealUin(uin)) return;
|
||||
if (!this.onPacket) return;
|
||||
const receiveUin = isRealUin(uin) ? uin : this.receiveWatchUin || this._uin;
|
||||
|
||||
if (isRealUin(receiveUin)) {
|
||||
this.noteReceiveActivity(packet.cmd, receiveUin);
|
||||
}
|
||||
|
||||
if (!isRealUin(uin)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.onPacket) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
|
||||
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
|
||||
// renaming was that module's entire purpose, so it lives at the source
|
||||
@@ -805,7 +992,10 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
private setStatus(status: HookProcessStatus, error: string): void {
|
||||
if (this._status === status && this._error === error) return;
|
||||
if (this._status === status && this._error === error) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._status = status;
|
||||
this._error = error;
|
||||
this.emit('status-changed', status, error);
|
||||
@@ -814,12 +1004,21 @@ export class HookSession extends EventEmitter {
|
||||
private noteReceiveActivity(cmd: string, uin: string): void {
|
||||
// BridgeManager treats packet.uin as authoritative and may move this PID
|
||||
// before the next loginState edge. Keep the watchdog on that same epoch.
|
||||
if (this.receiveWatchUin !== uin) this.resetReceiveWatch(uin);
|
||||
if (this.receiveWatchUin !== uin) {
|
||||
this.resetReceiveWatch(uin);
|
||||
}
|
||||
|
||||
if (!this.receiveWatchArmed) {
|
||||
if (cmd !== QQ_RECV_HEARTBEAT_CMD) return;
|
||||
if (cmd !== QQ_RECV_HEARTBEAT_CMD) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.receiveWatchArmed = true;
|
||||
this.log.debug('receive health armed by QQ heartbeat: PID=%d UIN=%s', this.pid, this.receiveWatchUin);
|
||||
this.log.debug(
|
||||
'receive health armed by QQ heartbeat: PID=%d UIN=%s',
|
||||
this.pid,
|
||||
this.receiveWatchUin,
|
||||
);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
@@ -839,22 +1038,34 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
private scheduleReceiveStaleCheck(): void {
|
||||
if (this.receiveWatchTimer) clearTimeout(this.receiveWatchTimer);
|
||||
if (this.receiveWatchTimer) {
|
||||
clearTimeout(this.receiveWatchTimer);
|
||||
}
|
||||
|
||||
this.receiveWatchTimer = setTimeout(() => {
|
||||
this.receiveWatchTimer = null;
|
||||
if (!this.shouldWatchReceive()) return;
|
||||
|
||||
if (!this.shouldWatchReceive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A delayed event loop (notably system sleep/resume) lands here long
|
||||
// after the nominal 90s deadline. Do not flip health immediately: give
|
||||
// the real QQ heartbeat one short confirmation window to arrive.
|
||||
this.receiveWatchTimer = setTimeout(() => {
|
||||
this.receiveWatchTimer = null;
|
||||
if (!this.shouldWatchReceive()) return;
|
||||
|
||||
if (!this.shouldWatchReceive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const silentForMs = Date.now() - this.lastReceiveAt;
|
||||
|
||||
if (silentForMs < RECEIVE_STALE_AFTER_MS + RECEIVE_STALE_CONFIRM_MS) {
|
||||
this.scheduleReceiveStaleCheck();
|
||||
return;
|
||||
}
|
||||
|
||||
this.setReceiveHealthy(false);
|
||||
this.log.warn(
|
||||
'receive path stale: PID=%d UIN=%s lastRecvAt=%s silentFor=%dms; reporting good=false',
|
||||
@@ -874,21 +1085,30 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
private setReceiveHealthy(healthy: boolean): void {
|
||||
if (this._receiveHealthy === healthy) return;
|
||||
if (this._receiveHealthy === healthy) {
|
||||
return;
|
||||
}
|
||||
|
||||
const previous = this.receiveHealthy;
|
||||
this._receiveHealthy = healthy;
|
||||
|
||||
if (previous !== this.receiveHealthy) {
|
||||
this.emit('receive-health-changed', this.receiveHealthy);
|
||||
}
|
||||
}
|
||||
|
||||
private setOutboundHealthy(healthy: boolean): void {
|
||||
if (this._outboundHealthy === healthy) return;
|
||||
if (this._outboundHealthy === healthy) {
|
||||
return;
|
||||
}
|
||||
|
||||
const previous = this.receiveHealthy;
|
||||
this._outboundHealthy = healthy;
|
||||
|
||||
if (previous !== this.receiveHealthy) {
|
||||
this.emit('receive-health-changed', this.receiveHealthy);
|
||||
}
|
||||
|
||||
if (healthy) {
|
||||
this.log.info('request path recovered: PID=%d UIN=%s', this.pid, this._uin);
|
||||
} else {
|
||||
@@ -905,6 +1125,7 @@ export class HookSession extends EventEmitter {
|
||||
clearTimeout(this.receiveWatchTimer);
|
||||
this.receiveWatchTimer = null;
|
||||
}
|
||||
|
||||
this.receiveWatchUin = uin;
|
||||
this.receiveWatchArmed = false;
|
||||
this.lastReceiveAt = 0;
|
||||
|
||||
@@ -25,7 +25,13 @@ export interface HookFlags {
|
||||
* here.
|
||||
*/
|
||||
export function statusFor(flags: HookFlags): HookProcessStatus {
|
||||
if (!flags.injected) return 'available';
|
||||
if (flags.connected) return flags.loggedIn ? 'online' : 'loaded';
|
||||
if (!flags.injected) {
|
||||
return 'available';
|
||||
}
|
||||
|
||||
if (flags.connected) {
|
||||
return flags.loggedIn ? 'online' : 'loaded';
|
||||
}
|
||||
|
||||
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
export {
|
||||
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
|
||||
type HookProcessStatus, type QqPortLoginInfo
|
||||
HookManager,
|
||||
type BridgeManagerSink,
|
||||
type HookManagerDeps,
|
||||
type HookProcessBaseInfo,
|
||||
type HookProcessInfo,
|
||||
type HookProcessStatus,
|
||||
type QqPortLoginInfo,
|
||||
} from './hook-manager';
|
||||
|
||||
@@ -42,7 +42,10 @@ 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}`;
|
||||
if (process.platform === 'win32' && process.arch === 'x64') {
|
||||
return `snowluma-win32-x64.${ext}`;
|
||||
}
|
||||
|
||||
return `snowluma-${process.platform}-${process.arch}.${ext}`;
|
||||
}
|
||||
|
||||
@@ -71,20 +74,30 @@ function nativeSearchDirs(): string[] {
|
||||
|
||||
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
|
||||
const fileName = platformBinaryName(ext);
|
||||
|
||||
for (const dir of nativeSearchDirs()) {
|
||||
const fullPath = path.join(dir, fileName);
|
||||
if (existsSync(fullPath)) return fullPath;
|
||||
|
||||
if (existsSync(fullPath)) {
|
||||
return fullPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getNativeHookAddon(): NativeHookAddon | null {
|
||||
if (nativeAddon) return nativeAddon;
|
||||
if (nativeAddon) {
|
||||
return nativeAddon;
|
||||
}
|
||||
|
||||
const addonPath = resolveHookNativePath('node');
|
||||
|
||||
if (!addonPath) {
|
||||
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
nativeAddon = loadNativeAddon(addonPath);
|
||||
nativeLoadError = null;
|
||||
@@ -109,33 +122,44 @@ export function listHookProcesses(): HookProcessBaseInfo[] {
|
||||
if (process.platform === 'darwin') {
|
||||
return [...listSnowlumaPipePidsSync()]
|
||||
.sort((a, b) => a - b)
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) return [];
|
||||
|
||||
if (!addon) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [...new Set(addon.getAllMainProcess())]
|
||||
.filter(pid => Number.isInteger(pid) && pid > 0)
|
||||
.filter((pid) => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
|
||||
export async function injectHookProcess(pid: number): Promise<HookInjectResult> {
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
|
||||
const injectableExt = platformInjectableExt();
|
||||
const dllPath = resolveHookNativePath(injectableExt);
|
||||
|
||||
if (!dllPath) {
|
||||
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
|
||||
}
|
||||
|
||||
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) };
|
||||
}
|
||||
|
||||
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
|
||||
addon.unloadModuleManual(pid, handle);
|
||||
}
|
||||
@@ -76,7 +76,10 @@ export class PipeWatcher extends EventEmitter {
|
||||
* and begin the polling loop. Idempotent.
|
||||
*/
|
||||
start(): Promise<void> {
|
||||
if (this.startPromise) return this.startPromise;
|
||||
if (this.startPromise) {
|
||||
return this.startPromise;
|
||||
}
|
||||
|
||||
this.startPromise = (async () => {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
@@ -89,7 +92,10 @@ export class PipeWatcher extends EventEmitter {
|
||||
|
||||
/** Pull the next scheduled tick forward to the next event-loop turn. */
|
||||
wake(): void {
|
||||
if (this.stopped) return;
|
||||
if (this.stopped) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.scheduleNext(0);
|
||||
}
|
||||
|
||||
@@ -100,6 +106,7 @@ export class PipeWatcher extends EventEmitter {
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
@@ -112,15 +119,22 @@ export class PipeWatcher extends EventEmitter {
|
||||
}
|
||||
|
||||
private scheduleNext(delayMs: number): void {
|
||||
if (this.stopped) return;
|
||||
if (this.stopped) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
this.timer = setTimeout(() => {
|
||||
|
||||
this.timer = setTimeout(
|
||||
() => {
|
||||
this.timer = null;
|
||||
void this.tickAndReschedule();
|
||||
}, Math.max(0, delayMs));
|
||||
},
|
||||
Math.max(0, delayMs),
|
||||
);
|
||||
}
|
||||
|
||||
private async tickAndReschedule(): Promise<void> {
|
||||
@@ -140,15 +154,19 @@ export class PipeWatcher extends EventEmitter {
|
||||
this.pendingWake = true;
|
||||
return;
|
||||
}
|
||||
|
||||
this.ticking = true;
|
||||
|
||||
try {
|
||||
let processes: HookProcessBaseInfo[] | null;
|
||||
|
||||
try {
|
||||
processes = await this.listProcesses();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
processes = null;
|
||||
}
|
||||
|
||||
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
|
||||
// Treating missing data as "everything disappeared" would fire
|
||||
// process-gone for every live PID and dispose healthy sessions — the
|
||||
@@ -159,7 +177,9 @@ export class PipeWatcher extends EventEmitter {
|
||||
this.emit('tick');
|
||||
return;
|
||||
}
|
||||
|
||||
let livePipes: Set<number> | null;
|
||||
|
||||
try {
|
||||
livePipes = await this.listLivePipes(processes);
|
||||
} catch (error) {
|
||||
@@ -168,7 +188,10 @@ export class PipeWatcher extends EventEmitter {
|
||||
}
|
||||
|
||||
const newKnownPids = new Set<number>();
|
||||
for (const proc of processes) newKnownPids.add(proc.pid);
|
||||
|
||||
for (const proc of processes) {
|
||||
newKnownPids.add(proc.pid);
|
||||
}
|
||||
|
||||
// 1. Newly discovered processes.
|
||||
for (const proc of processes) {
|
||||
@@ -180,16 +203,23 @@ export class PipeWatcher extends EventEmitter {
|
||||
// 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);
|
||||
if (newKnownPids.has(pid)) {
|
||||
newLivePipes.add(pid);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const pid of livePipes) {
|
||||
if (!newKnownPids.has(pid)) continue;
|
||||
if (!newKnownPids.has(pid)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
newLivePipes.add(pid);
|
||||
|
||||
if (!this.livePipes.has(pid)) {
|
||||
this.emit('pipe-up', pid);
|
||||
}
|
||||
@@ -216,10 +246,13 @@ export class PipeWatcher extends EventEmitter {
|
||||
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(); });
|
||||
setImmediate(() => {
|
||||
void this.tickOnce();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +110,9 @@ export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): Proce
|
||||
return null;
|
||||
}
|
||||
},
|
||||
dispose() { /* nothing to tear down */ },
|
||||
dispose() {
|
||||
/* nothing to tear down */
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -127,41 +129,67 @@ export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): Proce
|
||||
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 === '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 ?? '');
|
||||
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);
|
||||
|
||||
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;
|
||||
|
||||
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();
|
||||
|
||||
if (worker === w) {
|
||||
teardownWorker();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const teardownWorker = (): void => {
|
||||
const w = worker;
|
||||
worker = null;
|
||||
if (!w) return;
|
||||
|
||||
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 */ });
|
||||
w.once('exit', () => {
|
||||
orphans = Math.max(0, orphans - 1);
|
||||
});
|
||||
void w.terminate().catch(() => {
|
||||
/* already gone */
|
||||
});
|
||||
};
|
||||
|
||||
const syncFallback = (): HookProcessBaseInfo[] | null => {
|
||||
@@ -175,7 +203,9 @@ export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): Proce
|
||||
|
||||
return {
|
||||
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
|
||||
if (disposed || isolationBroken) return syncFallback();
|
||||
if (disposed || isolationBroken) {
|
||||
return syncFallback();
|
||||
}
|
||||
|
||||
if (!worker) {
|
||||
if (orphans >= maxOrphans) {
|
||||
@@ -183,15 +213,21 @@ export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): Proce
|
||||
// don't spawn more; report UNKNOWN and let them drain.
|
||||
return null;
|
||||
}
|
||||
|
||||
spawnWorker();
|
||||
}
|
||||
|
||||
const w = worker;
|
||||
if (!w) return syncFallback();
|
||||
|
||||
if (!w) {
|
||||
return syncFallback();
|
||||
}
|
||||
|
||||
const id = ++seq;
|
||||
const resultPromise = new Promise<number[] | null>((resolve) => {
|
||||
pending.set(id, { resolve });
|
||||
});
|
||||
|
||||
try {
|
||||
w.postMessage({ type: 'enumerate', id });
|
||||
} catch (err) {
|
||||
@@ -206,29 +242,46 @@ export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): Proce
|
||||
timer = setTimeout(() => resolve('timeout'), timeoutMs);
|
||||
});
|
||||
const outcome = await Promise.race([resultPromise, timeout]);
|
||||
if (timer) clearTimeout(timer);
|
||||
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
if (outcome === 'timeout') {
|
||||
pending.delete(id);
|
||||
log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs);
|
||||
log.warn(
|
||||
'process enumeration timed out after %dms (worker abandoned) — keeping prior process set',
|
||||
timeoutMs,
|
||||
);
|
||||
teardownWorker();
|
||||
return null;
|
||||
}
|
||||
|
||||
if (outcome === null) {
|
||||
// Native call threw inside the worker — treat as a transient failure,
|
||||
// keep prior state rather than nuking every session.
|
||||
return null;
|
||||
}
|
||||
|
||||
return mapPids(outcome, deps.processName);
|
||||
},
|
||||
|
||||
dispose() {
|
||||
disposed = true;
|
||||
for (const { resolve } of pending.values()) resolve(null);
|
||||
|
||||
for (const { resolve } of pending.values()) {
|
||||
resolve(null);
|
||||
}
|
||||
|
||||
pending.clear();
|
||||
const w = worker;
|
||||
worker = null;
|
||||
if (w) void w.terminate().catch(() => { /* ignore */ });
|
||||
|
||||
if (w) {
|
||||
void w.terminate().catch(() => {
|
||||
/* ignore */
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -112,11 +112,13 @@ function isMissingDirectoryError(error: unknown): boolean {
|
||||
|
||||
function isUnavailableSocketError(error: unknown): boolean {
|
||||
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
||||
return code === 'ENOENT'
|
||||
|| code === 'ENOTDIR'
|
||||
|| code === 'ENOTSOCK'
|
||||
|| code === 'ECONNREFUSED'
|
||||
|| code === 'ECONNRESET';
|
||||
return (
|
||||
code === 'ENOENT' ||
|
||||
code === 'ENOTDIR' ||
|
||||
code === 'ENOTSOCK' ||
|
||||
code === 'ECONNREFUSED' ||
|
||||
code === 'ECONNRESET'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,30 +134,46 @@ function isUnavailableSocketError(error: unknown): boolean {
|
||||
* sufficient signal for "process exists with our dylib mapped". The async
|
||||
* variant still gates the subsequent `pipe-up` emit via a real connect.
|
||||
*/
|
||||
export function listSnowlumaPipePidsSync(
|
||||
runtimeDir = resolveHookRuntimeDir(),
|
||||
): Set<number> {
|
||||
export function listSnowlumaPipePidsSync(runtimeDir = resolveHookRuntimeDir()): Set<number> {
|
||||
const result = new Set<number>();
|
||||
let names: string[];
|
||||
|
||||
try {
|
||||
names = readdirSync(runtimeDir);
|
||||
} catch (error) {
|
||||
if (isMissingDirectoryError(error)) return result;
|
||||
throw error;
|
||||
}
|
||||
for (const name of names) {
|
||||
const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name);
|
||||
if (!m) continue;
|
||||
const pid = Number(m[1]);
|
||||
if (Number.isInteger(pid) && pid > 0) result.add(pid);
|
||||
}
|
||||
if (isMissingDirectoryError(error)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
function mojoPipeName(pid: number, suffix: string, runtimeDir = resolveHookRuntimeDir(pid)): string {
|
||||
throw error;
|
||||
}
|
||||
|
||||
for (const name of names) {
|
||||
const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name);
|
||||
|
||||
if (!m) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pid = Number(m[1]);
|
||||
|
||||
if (Number.isInteger(pid) && pid > 0) {
|
||||
result.add(pid);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function mojoPipeName(
|
||||
pid: number,
|
||||
suffix: string,
|
||||
runtimeDir = resolveHookRuntimeDir(pid),
|
||||
): string {
|
||||
if (process.platform === 'win32') {
|
||||
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
|
||||
}
|
||||
|
||||
return path.join(runtimeDir, `mojo.${pid}.${suffix}.sock`);
|
||||
}
|
||||
|
||||
@@ -164,37 +182,58 @@ type LinuxPipeProbe = (socketPath: string) => Promise<boolean>;
|
||||
async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
|
||||
try {
|
||||
const stat = await fs.stat(socketPath);
|
||||
if (!stat.isSocket()) return false;
|
||||
|
||||
if (!stat.isSocket()) {
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
if (isUnavailableSocketError(error)) return false;
|
||||
if (isUnavailableSocketError(error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
return new Promise<boolean>((resolve, reject) => {
|
||||
let socket: net.Socket;
|
||||
|
||||
try {
|
||||
socket = net.createConnection(socketPath);
|
||||
} catch (error) {
|
||||
if (isUnavailableSocketError(error)) resolve(false);
|
||||
else reject(error);
|
||||
if (isUnavailableSocketError(error)) {
|
||||
resolve(false);
|
||||
} else {
|
||||
reject(error);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
let done = false;
|
||||
let timer: NodeJS.Timeout;
|
||||
|
||||
const finish = (ok: boolean) => {
|
||||
if (done) return;
|
||||
if (done) {
|
||||
return;
|
||||
}
|
||||
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
socket.removeAllListeners();
|
||||
socket.destroy();
|
||||
resolve(ok);
|
||||
};
|
||||
|
||||
timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS);
|
||||
socket.once('connect', () => finish(true));
|
||||
socket.once('error', error => {
|
||||
if (isUnavailableSocketError(error)) finish(false);
|
||||
else {
|
||||
if (done) return;
|
||||
socket.once('error', (error) => {
|
||||
if (isUnavailableSocketError(error)) {
|
||||
finish(false);
|
||||
} else {
|
||||
if (done) {
|
||||
return;
|
||||
}
|
||||
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
socket.removeAllListeners();
|
||||
@@ -211,29 +250,57 @@ export async function listLiveLinuxPipePids(
|
||||
): Promise<Set<number>> {
|
||||
const result = new Set<number>();
|
||||
let names: string[];
|
||||
|
||||
try {
|
||||
names = await fs.readdir(runtimeDir);
|
||||
} catch (error) {
|
||||
if (isMissingDirectoryError(error)) return result;
|
||||
if (isMissingDirectoryError(error)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
await Promise.all(names.map(async (name) => {
|
||||
await Promise.all(
|
||||
names.map(async (name) => {
|
||||
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
|
||||
if (!m) return;
|
||||
|
||||
if (!m) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pid = Number(m[1]);
|
||||
if (!Number.isInteger(pid) || pid <= 0) return;
|
||||
if (await probe(path.join(runtimeDir, name))) result.add(pid);
|
||||
}));
|
||||
|
||||
if (!Number.isInteger(pid) || pid <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (await probe(path.join(runtimeDir, name))) {
|
||||
result.add(pid);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
|
||||
if (Buffer.isBuffer(body)) return body;
|
||||
if (body instanceof Uint8Array) return Buffer.from(body);
|
||||
if (typeof body === 'string') return Buffer.from(body, 'utf8');
|
||||
if (body == null) return Buffer.alloc(0);
|
||||
if (Buffer.isBuffer(body)) {
|
||||
return body;
|
||||
}
|
||||
|
||||
if (body instanceof Uint8Array) {
|
||||
return Buffer.from(body);
|
||||
}
|
||||
|
||||
if (typeof body === 'string') {
|
||||
return Buffer.from(body, 'utf8');
|
||||
}
|
||||
|
||||
if (body == null) {
|
||||
return Buffer.alloc(0);
|
||||
}
|
||||
|
||||
throw new TypeError('body must be Buffer, Uint8Array, string, or null');
|
||||
}
|
||||
|
||||
@@ -258,20 +325,24 @@ class OperationTimeoutError extends Error {
|
||||
}
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
|
||||
if (!timeoutMs || timeoutMs <= 0) return promise;
|
||||
if (!timeoutMs || timeoutMs <= 0) {
|
||||
return promise;
|
||||
}
|
||||
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
reject(new OperationTimeoutError(label, timeoutMs));
|
||||
}, timeoutMs);
|
||||
promise.then(
|
||||
value => {
|
||||
(value) => {
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
},
|
||||
error => {
|
||||
(error) => {
|
||||
clearTimeout(timer);
|
||||
reject(error);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -290,11 +361,20 @@ function packetFailureReason(
|
||||
error: unknown,
|
||||
requestId: number,
|
||||
): 'ack_timeout' | 'reply_timeout' | 'request_failed' | 'transport_failure' {
|
||||
if (error instanceof HookPipeRequestError) return 'request_failed';
|
||||
if (error instanceof OperationTimeoutError) {
|
||||
if (error.label === `send ack ${requestId}`) return 'ack_timeout';
|
||||
if (error.label === `send reply ${requestId}`) return 'reply_timeout';
|
||||
if (error instanceof HookPipeRequestError) {
|
||||
return 'request_failed';
|
||||
}
|
||||
|
||||
if (error instanceof OperationTimeoutError) {
|
||||
if (error.label === `send ack ${requestId}`) {
|
||||
return 'ack_timeout';
|
||||
}
|
||||
|
||||
if (error.label === `send reply ${requestId}`) {
|
||||
return 'reply_timeout';
|
||||
}
|
||||
}
|
||||
|
||||
return 'transport_failure';
|
||||
}
|
||||
|
||||
@@ -341,6 +421,7 @@ function validatePipeFrameLengths(cmdLen: number, msgLen: number, bodyLen: numbe
|
||||
['message', msgLen, MAX_PIPE_MSG_BYTES],
|
||||
['body', bodyLen, MAX_PIPE_BODY_BYTES],
|
||||
] as const;
|
||||
|
||||
for (const [name, length, limit] of lengths) {
|
||||
if (length > limit) {
|
||||
throw new Error(`pipe frame ${name} length ${length} exceeds limit ${limit}`);
|
||||
@@ -370,24 +451,29 @@ class FrameReader {
|
||||
|
||||
push(chunk: Buffer): void {
|
||||
let chunkOffset = 0;
|
||||
|
||||
while (chunkOffset < chunk.length) {
|
||||
if (!this.pending) {
|
||||
const headerBytes = Math.min(HEADER_SIZE - this.headerBytes, chunk.length - chunkOffset);
|
||||
chunk.copy(
|
||||
this.header,
|
||||
this.headerBytes,
|
||||
chunkOffset,
|
||||
chunkOffset + headerBytes,
|
||||
const headerBytes = Math.min(
|
||||
HEADER_SIZE - this.headerBytes,
|
||||
chunk.length - chunkOffset,
|
||||
);
|
||||
chunk.copy(this.header, this.headerBytes, chunkOffset, chunkOffset + headerBytes);
|
||||
this.headerBytes += headerBytes;
|
||||
chunkOffset += headerBytes;
|
||||
if (this.headerBytes < HEADER_SIZE) return;
|
||||
|
||||
if (this.headerBytes < HEADER_SIZE) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.headerBytes = 0;
|
||||
const magic = this.header.readUInt32LE(0);
|
||||
const version = this.header.readUInt16LE(4);
|
||||
|
||||
if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) {
|
||||
throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`);
|
||||
throw new Error(
|
||||
`bad frame header magic=0x${magic.toString(16)} version=${version}`,
|
||||
);
|
||||
}
|
||||
|
||||
const cmdLen = this.header.readUInt32LE(20);
|
||||
@@ -404,7 +490,8 @@ class FrameReader {
|
||||
cmdLen,
|
||||
msgLen,
|
||||
bodyLen,
|
||||
payload: payloadLength === 0 ? Buffer.alloc(0) : Buffer.allocUnsafe(payloadLength),
|
||||
payload:
|
||||
payloadLength === 0 ? Buffer.alloc(0) : Buffer.allocUnsafe(payloadLength),
|
||||
received: 0,
|
||||
};
|
||||
}
|
||||
@@ -414,6 +501,7 @@ class FrameReader {
|
||||
pending.payload.length - pending.received,
|
||||
chunk.length - chunkOffset,
|
||||
);
|
||||
|
||||
if (payloadBytes > 0) {
|
||||
chunk.copy(
|
||||
pending.payload,
|
||||
@@ -424,7 +512,10 @@ class FrameReader {
|
||||
pending.received += payloadBytes;
|
||||
chunkOffset += payloadBytes;
|
||||
}
|
||||
if (pending.received < pending.payload.length) return;
|
||||
|
||||
if (pending.received < pending.payload.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.pending = null;
|
||||
const frame: PipeFrame = {
|
||||
@@ -471,11 +562,14 @@ export class QqHookClient extends EventEmitter {
|
||||
private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
private loginWaiters: Deferred<QqHookLoginState>[] = [];
|
||||
|
||||
constructor(pid: number, {
|
||||
constructor(
|
||||
pid: number,
|
||||
{
|
||||
ackTimeoutMs = positiveIntEnv('SNOWLUMA_HOOK_ACK_TIMEOUT_MS', DEFAULT_ACK_TIMEOUT_MS),
|
||||
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
|
||||
runtimeDir = resolveHookRuntimeDir(pid),
|
||||
}: QqHookClientOptions = {}) {
|
||||
}: QqHookClientOptions = {},
|
||||
) {
|
||||
super();
|
||||
this.pid = pid;
|
||||
this.runtimeDir = runtimeDir;
|
||||
@@ -511,14 +605,17 @@ export class QqHookClient extends EventEmitter {
|
||||
if (!isRealUin(uin)) {
|
||||
throw new Error(`invalid QQ login identity hint: ${JSON.stringify(uin)}`);
|
||||
}
|
||||
|
||||
await this.sendAckOnly(PipeOp.loginIdentityHint, BigInt(uin), 'login identity hint');
|
||||
}
|
||||
|
||||
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
|
||||
await this.connect();
|
||||
|
||||
if (this.loginState.loggedIn) {
|
||||
return this.getLoginState();
|
||||
}
|
||||
|
||||
const deferred = createDeferred<QqHookLoginState>();
|
||||
this.loginWaiters.push(deferred);
|
||||
return withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
|
||||
@@ -549,23 +646,35 @@ export class QqHookClient extends EventEmitter {
|
||||
*/
|
||||
static async listLivePipes(pids: readonly number[] = []): Promise<Set<number>> {
|
||||
const result = new Set<number>();
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
const names = await fs.readdir('\\\\.\\pipe\\');
|
||||
|
||||
for (const name of names) {
|
||||
const m = /^mojo\.(\d+)\.control$/i.exec(name);
|
||||
if (m) result.add(Number(m[1]));
|
||||
|
||||
if (m) {
|
||||
result.add(Number(m[1]));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const runtimeDirs = new Set<string>();
|
||||
|
||||
if (pids.length === 0) {
|
||||
runtimeDirs.add(resolveHookRuntimeDir());
|
||||
} else {
|
||||
for (const pid of pids) runtimeDirs.add(resolveHookRuntimeDir(pid));
|
||||
for (const pid of pids) {
|
||||
runtimeDirs.add(resolveHookRuntimeDir(pid));
|
||||
}
|
||||
}
|
||||
|
||||
for (const runtimeDir of runtimeDirs) {
|
||||
for (const pid of await listLiveLinuxPipePids(runtimeDir)) result.add(pid);
|
||||
for (const pid of await listLiveLinuxPipePids(runtimeDir)) {
|
||||
result.add(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -573,13 +682,17 @@ export class QqHookClient extends EventEmitter {
|
||||
if (this.closed) {
|
||||
throw new Error('qq_hook client is closed');
|
||||
}
|
||||
|
||||
if (this.controlSocket && this.controlHello) {
|
||||
return this.controlHello;
|
||||
}
|
||||
|
||||
if (this.controlConnectPromise) {
|
||||
return this.controlConnectPromise;
|
||||
}
|
||||
|
||||
this.controlConnectPromise = this.connectPipe('control');
|
||||
|
||||
try {
|
||||
return await this.controlConnectPromise;
|
||||
} finally {
|
||||
@@ -591,16 +704,21 @@ export class QqHookClient extends EventEmitter {
|
||||
if (this.closed) {
|
||||
throw new Error('qq_hook client is closed');
|
||||
}
|
||||
|
||||
if (typeof onPacket === 'function') {
|
||||
this.on('packet', onPacket);
|
||||
}
|
||||
|
||||
if (this.recvSocket && this.recvHello) {
|
||||
return this.recvHello;
|
||||
}
|
||||
|
||||
if (this.recvConnectPromise) {
|
||||
return this.recvConnectPromise;
|
||||
}
|
||||
|
||||
this.recvConnectPromise = this.connectPipe('recv');
|
||||
|
||||
try {
|
||||
return await this.recvConnectPromise;
|
||||
} finally {
|
||||
@@ -608,17 +726,24 @@ export class QqHookClient extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
async connectAll({ recv = true } = {}): Promise<{ control: QqHookHello; recv: QqHookHello | null }> {
|
||||
async connectAll({ recv = true } = {}): Promise<{
|
||||
control: QqHookHello;
|
||||
recv: QqHookHello | null;
|
||||
}> {
|
||||
const control = await this.connect();
|
||||
const recvInfo = recv ? await this.startRecv() : null;
|
||||
return { control, recv: recvInfo };
|
||||
}
|
||||
|
||||
async send(cmd: string, body: Buffer | Uint8Array | string | null | undefined, {
|
||||
async send(
|
||||
cmd: string,
|
||||
body: Buffer | Uint8Array | string | null | undefined,
|
||||
{
|
||||
wantReply = true,
|
||||
ackTimeoutMs = this.defaultAckTimeoutMs,
|
||||
replyTimeoutMs = this.defaultReplyTimeoutMs,
|
||||
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
|
||||
}: QqHookSendOptions = {},
|
||||
): Promise<QqHookSendReply | { requestId: number }> {
|
||||
await this.connect();
|
||||
|
||||
const requestId = this.allocateRequestId();
|
||||
@@ -645,7 +770,9 @@ export class QqHookClient extends EventEmitter {
|
||||
// pending deferred — but the reply is only `await`ed AFTER the ack, so if the
|
||||
// ack fails first the reply promise is rejected with NO awaiter. The real
|
||||
// `await` below still observes the value/rejection (a separate continuation).
|
||||
ackDeferred.promise.catch(() => { /* observed by the await, or harmless */ });
|
||||
ackDeferred.promise.catch(() => {
|
||||
/* observed by the await, or harmless */
|
||||
});
|
||||
this.pendingAcks.set(requestId, {
|
||||
resolve: ackDeferred.resolve,
|
||||
reject: ackDeferred.reject,
|
||||
@@ -653,15 +780,19 @@ export class QqHookClient extends EventEmitter {
|
||||
});
|
||||
|
||||
let replyDeferred: Deferred<QqHookSendReply> | null = null;
|
||||
|
||||
if (wantReply) {
|
||||
replyDeferred = createDeferred<QqHookSendReply>();
|
||||
replyDeferred.promise.catch(() => { /* see note above — prevents unhandled rejection */ });
|
||||
replyDeferred.promise.catch(() => {
|
||||
/* see note above — prevents unhandled rejection */
|
||||
});
|
||||
this.pendingReplies.set(requestId, replyDeferred);
|
||||
}
|
||||
|
||||
try {
|
||||
await this.writeControl(payload);
|
||||
await withTimeout(ackDeferred.promise, ackTimeoutMs, `send ack ${requestId}`);
|
||||
|
||||
if (!wantReply) {
|
||||
packetLog.trace(() => [
|
||||
'packet_terminal serviceCmd=%j requestId=%d outcome=ok reason=ack_received elapsedMs=%d',
|
||||
@@ -671,10 +802,12 @@ export class QqHookClient extends EventEmitter {
|
||||
]);
|
||||
return { requestId };
|
||||
}
|
||||
|
||||
const reply = await withTimeout(
|
||||
replyDeferred!.promise,
|
||||
replyTimeoutMs,
|
||||
`send reply ${requestId}`);
|
||||
`send reply ${requestId}`,
|
||||
);
|
||||
packetLog.trace(() => [
|
||||
'packet_recv serviceCmd=%j requestId=%d error=%d message=%j length=%d body=%s',
|
||||
cmd,
|
||||
@@ -711,20 +844,39 @@ export class QqHookClient extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
async sendNoReply(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit<QqHookSendOptions, 'wantReply'> = {}): Promise<{ requestId: number }> {
|
||||
return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{ requestId: number }>;
|
||||
async sendNoReply(
|
||||
cmd: string,
|
||||
body: Buffer | Uint8Array | string | null | undefined,
|
||||
options: Omit<QqHookSendOptions, 'wantReply'> = {},
|
||||
): Promise<{ requestId: number }> {
|
||||
return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{
|
||||
requestId: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
async sendAndWait(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit<QqHookSendOptions, 'wantReply'> = {}): Promise<QqHookSendReply> {
|
||||
async sendAndWait(
|
||||
cmd: string,
|
||||
body: Buffer | Uint8Array | string | null | undefined,
|
||||
options: Omit<QqHookSendOptions, 'wantReply'> = {},
|
||||
): Promise<QqHookSendReply> {
|
||||
return this.send(cmd, body, { ...options, wantReply: true }) as Promise<QqHookSendReply>;
|
||||
}
|
||||
|
||||
async sendMany(items: Array<{ cmd: string; body?: Buffer | Uint8Array | string | null; wantReply?: boolean; ackTimeoutMs?: number; replyTimeoutMs?: number }>, {
|
||||
async sendMany(
|
||||
items: Array<{
|
||||
cmd: string;
|
||||
body?: Buffer | Uint8Array | string | null;
|
||||
wantReply?: boolean;
|
||||
ackTimeoutMs?: number;
|
||||
replyTimeoutMs?: number;
|
||||
}>,
|
||||
{
|
||||
concurrency = 64,
|
||||
wantReply = true,
|
||||
ackTimeoutMs = this.defaultAckTimeoutMs,
|
||||
replyTimeoutMs = this.defaultReplyTimeoutMs,
|
||||
}: QqHookSendOptions & { concurrency?: number } = {}): Promise<Array<QqHookSendReply | { requestId: number }>> {
|
||||
}: QqHookSendOptions & { concurrency?: number } = {},
|
||||
): Promise<Array<QqHookSendReply | { requestId: number }>> {
|
||||
const results = new Array<QqHookSendReply | { requestId: number }>(items.length);
|
||||
let nextIndex = 0;
|
||||
const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1));
|
||||
@@ -733,7 +885,11 @@ export class QqHookClient extends EventEmitter {
|
||||
for (;;) {
|
||||
const index = nextIndex;
|
||||
nextIndex += 1;
|
||||
if (index >= items.length) return;
|
||||
|
||||
if (index >= items.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const item = items[index];
|
||||
const itemWantReply = item.wantReply ?? wantReply;
|
||||
results[index] = await this.send(item.cmd, item.body, {
|
||||
@@ -748,19 +904,28 @@ export class QqHookClient extends EventEmitter {
|
||||
return results;
|
||||
}
|
||||
|
||||
waitForPacket(predicate: (packet: QqHookPacket) => boolean = () => true, { timeoutMs = 0 } = {}): Promise<QqHookPacket> {
|
||||
waitForPacket(
|
||||
predicate: (packet: QqHookPacket) => boolean = () => true,
|
||||
{ timeoutMs = 0 } = {},
|
||||
): Promise<QqHookPacket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer: NodeJS.Timeout | null = null;
|
||||
|
||||
const cleanup = () => {
|
||||
this.off('packet', onPacket);
|
||||
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const onPacket = (packet: QqHookPacket) => {
|
||||
try {
|
||||
if (!predicate(packet)) return;
|
||||
if (!predicate(packet)) {
|
||||
return;
|
||||
}
|
||||
|
||||
cleanup();
|
||||
resolve(packet);
|
||||
} catch (error) {
|
||||
@@ -768,7 +933,9 @@ export class QqHookClient extends EventEmitter {
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
this.on('packet', onPacket);
|
||||
|
||||
if (timeoutMs > 0) {
|
||||
timer = setTimeout(() => {
|
||||
cleanup();
|
||||
@@ -779,7 +946,10 @@ export class QqHookClient extends EventEmitter {
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.closed = true;
|
||||
this.rejectControlPending(new Error('qq_hook client closed'));
|
||||
this.rejectRecvPending(new Error('qq_hook client closed'));
|
||||
@@ -789,10 +959,12 @@ export class QqHookClient extends EventEmitter {
|
||||
this.controlSocket.destroy();
|
||||
this.controlSocket = null;
|
||||
}
|
||||
|
||||
if (this.recvSocket) {
|
||||
this.recvSocket.destroy();
|
||||
this.recvSocket = null;
|
||||
}
|
||||
|
||||
this.controlHello = null;
|
||||
this.recvHello = null;
|
||||
this.controlWriteChain = Promise.resolve();
|
||||
@@ -801,18 +973,24 @@ export class QqHookClient extends EventEmitter {
|
||||
private rejectLoginWaiters(error: Error): void {
|
||||
const waiters = this.loginWaiters;
|
||||
this.loginWaiters = [];
|
||||
for (const waiter of waiters) waiter.reject(error);
|
||||
|
||||
for (const waiter of waiters) {
|
||||
waiter.reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
private rejectControlPending(error: Error): void {
|
||||
for (const pending of this.pendingAcks.values()) {
|
||||
pending.reject(error);
|
||||
}
|
||||
|
||||
for (const pending of this.pendingReplies.values()) {
|
||||
pending.reject(error);
|
||||
}
|
||||
|
||||
this.pendingAcks.clear();
|
||||
this.pendingReplies.clear();
|
||||
|
||||
if (this.controlHelloResolver) {
|
||||
this.controlHelloResolver.reject(error);
|
||||
this.controlHelloResolver = null;
|
||||
@@ -828,19 +1006,28 @@ export class QqHookClient extends EventEmitter {
|
||||
|
||||
private writeControl(payload: Buffer): Promise<void> {
|
||||
const socket = this.controlSocket;
|
||||
|
||||
if (!socket || socket.destroyed) {
|
||||
return Promise.reject(new Error('control pipe is not connected'));
|
||||
}
|
||||
const writePromise = this.controlWriteChain.then(() => new Promise<void>((resolve, reject) => {
|
||||
|
||||
const writePromise = this.controlWriteChain.then(
|
||||
() =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
if (!this.controlSocket || this.controlSocket.destroyed) {
|
||||
reject(new Error('control pipe is not connected'));
|
||||
return;
|
||||
}
|
||||
socket.write(payload, error => {
|
||||
if (error) reject(error);
|
||||
else resolve();
|
||||
|
||||
socket.write(payload, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}));
|
||||
}),
|
||||
);
|
||||
this.controlWriteChain = writePromise.catch(() => {});
|
||||
return writePromise;
|
||||
}
|
||||
@@ -849,12 +1036,21 @@ export class QqHookClient extends EventEmitter {
|
||||
// Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would lose
|
||||
// precision past Number.MAX_SAFE_INTEGER. Zero remains the wire sentinel.
|
||||
let requestId = this.nextRequestId;
|
||||
|
||||
while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) {
|
||||
requestId = (requestId + 1) >>> 0;
|
||||
if (requestId === 0) requestId = 1;
|
||||
|
||||
if (requestId === 0) {
|
||||
requestId = 1;
|
||||
}
|
||||
}
|
||||
|
||||
this.nextRequestId = (requestId + 1) >>> 0;
|
||||
if (this.nextRequestId === 0) this.nextRequestId = 1;
|
||||
|
||||
if (this.nextRequestId === 0) {
|
||||
this.nextRequestId = 1;
|
||||
}
|
||||
|
||||
return requestId;
|
||||
}
|
||||
|
||||
@@ -862,12 +1058,15 @@ export class QqHookClient extends EventEmitter {
|
||||
await this.connect();
|
||||
const requestId = this.allocateRequestId();
|
||||
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
|
||||
ackDeferred.promise.catch(() => { /* observed by the await below */ });
|
||||
ackDeferred.promise.catch(() => {
|
||||
/* observed by the await below */
|
||||
});
|
||||
this.pendingAcks.set(requestId, {
|
||||
resolve: ackDeferred.resolve,
|
||||
reject: ackDeferred.reject,
|
||||
wantReply: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await this.writeControl(encodeFrame({ op, requestId, value0 }));
|
||||
await withTimeout(
|
||||
@@ -885,7 +1084,8 @@ export class QqHookClient extends EventEmitter {
|
||||
private async connectPipe(kind: 'control' | 'recv'): Promise<QqHookHello> {
|
||||
return runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
const pipeName = kind === 'control'
|
||||
const pipeName =
|
||||
kind === 'control'
|
||||
? QqHookClient.controlPipeName(this.pid, this.runtimeDir)
|
||||
: QqHookClient.recvPipeName(this.pid, this.runtimeDir);
|
||||
let phase: 'connect' | 'hello' = 'connect';
|
||||
@@ -895,16 +1095,24 @@ export class QqHookClient extends EventEmitter {
|
||||
kind,
|
||||
pipeName,
|
||||
);
|
||||
|
||||
try {
|
||||
const socket = await runWithoutRequestContext(() => this.connectSocket(
|
||||
const socket = await runWithoutRequestContext(() =>
|
||||
this.connectSocket(
|
||||
pipeName,
|
||||
kind,
|
||||
kind === 'control'
|
||||
? frame => this.handleControlFrame(frame)
|
||||
: frame => this.handleRecvFrame(frame),
|
||||
));
|
||||
if (kind === 'control') this.controlSocket = socket;
|
||||
else this.recvSocket = socket;
|
||||
? (frame) => this.handleControlFrame(frame)
|
||||
: (frame) => this.handleRecvFrame(frame),
|
||||
),
|
||||
);
|
||||
|
||||
if (kind === 'control') {
|
||||
this.controlSocket = socket;
|
||||
} else {
|
||||
this.recvSocket = socket;
|
||||
}
|
||||
|
||||
runtimeLog.trace(
|
||||
'hook_pipe_branch pid=%d kind=%s branch=socket_connected',
|
||||
this.pid,
|
||||
@@ -912,8 +1120,13 @@ export class QqHookClient extends EventEmitter {
|
||||
);
|
||||
phase = 'hello';
|
||||
const hello = await this.waitForHello(kind === 'recv');
|
||||
if (kind === 'control') this.controlHello = hello;
|
||||
else this.recvHello = hello;
|
||||
|
||||
if (kind === 'control') {
|
||||
this.controlHello = hello;
|
||||
} else {
|
||||
this.recvHello = hello;
|
||||
}
|
||||
|
||||
runtimeLog.trace(() => [
|
||||
'hook_pipe_terminal pid=%d kind=%s outcome=completed reason=hello_received hello=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
@@ -936,7 +1149,11 @@ export class QqHookClient extends EventEmitter {
|
||||
});
|
||||
}
|
||||
|
||||
private connectSocket(pipeName: string, kind: 'control' | 'recv', onFrame: (frame: PipeFrame) => void): Promise<net.Socket> {
|
||||
private connectSocket(
|
||||
pipeName: string,
|
||||
kind: 'control' | 'recv',
|
||||
onFrame: (frame: PipeFrame) => void,
|
||||
): Promise<net.Socket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = net.createConnection(pipeName);
|
||||
const reader = new FrameReader(onFrame);
|
||||
@@ -944,7 +1161,7 @@ export class QqHookClient extends EventEmitter {
|
||||
socket.once('error', onInitialError);
|
||||
socket.once('connect', () => {
|
||||
socket.off('error', onInitialError);
|
||||
socket.on('data', chunk => {
|
||||
socket.on('data', (chunk) => {
|
||||
try {
|
||||
reader.push(chunk);
|
||||
} catch (error) {
|
||||
@@ -952,7 +1169,7 @@ export class QqHookClient extends EventEmitter {
|
||||
socket.destroy();
|
||||
}
|
||||
});
|
||||
socket.on('error', error => {
|
||||
socket.on('error', (error) => {
|
||||
this.emit('error', error);
|
||||
});
|
||||
socket.on('close', () => {
|
||||
@@ -968,19 +1185,29 @@ export class QqHookClient extends EventEmitter {
|
||||
|
||||
private waitForHello(recvPipe: boolean): Promise<QqHookHello> {
|
||||
const deferred = createDeferred<QqHookHello>();
|
||||
|
||||
if (recvPipe) {
|
||||
this.recvHelloResolver = deferred;
|
||||
} else {
|
||||
this.controlHelloResolver = deferred;
|
||||
}
|
||||
|
||||
return deferred.promise;
|
||||
}
|
||||
|
||||
private resolveHello(frame: PipeFrame, recvPipe: boolean): void {
|
||||
const resolver = recvPipe ? this.recvHelloResolver : this.controlHelloResolver;
|
||||
if (!resolver) return;
|
||||
if (recvPipe) this.recvHelloResolver = null;
|
||||
else this.controlHelloResolver = null;
|
||||
|
||||
if (!resolver) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (recvPipe) {
|
||||
this.recvHelloResolver = null;
|
||||
} else {
|
||||
this.controlHelloResolver = null;
|
||||
}
|
||||
|
||||
resolver.resolve({
|
||||
pipeName: frame.msg,
|
||||
pid: Number(frame.value0),
|
||||
@@ -996,12 +1223,14 @@ export class QqHookClient extends EventEmitter {
|
||||
this.loginState.loggedIn,
|
||||
this.loginState.uin,
|
||||
);
|
||||
|
||||
if (kind === 'control') {
|
||||
this.controlSocket = null;
|
||||
this.controlHello = null;
|
||||
this.rejectControlPending(new Error('control pipe closed'));
|
||||
return;
|
||||
}
|
||||
|
||||
this.recvSocket = null;
|
||||
this.recvHello = null;
|
||||
this.rejectRecvPending(new Error('recv pipe closed'));
|
||||
@@ -1019,10 +1248,12 @@ export class QqHookClient extends EventEmitter {
|
||||
private applyLoginState(next: QqHookLoginState): void {
|
||||
const previous = this.loginState;
|
||||
this.loginState = next;
|
||||
|
||||
if (previous.loggedIn === next.loggedIn && previous.uin === next.uin) {
|
||||
this.emit('loginState', next);
|
||||
return;
|
||||
}
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
runtimeLog.trace(
|
||||
'hook_runtime_fact pid=%d event=login_state_changed previousLoggedIn=%s previousUin=%j loggedIn=%s uin=%j',
|
||||
@@ -1033,10 +1264,14 @@ export class QqHookClient extends EventEmitter {
|
||||
next.uin,
|
||||
);
|
||||
this.emit('loginState', next);
|
||||
|
||||
if (next.loggedIn) {
|
||||
const waiters = this.loginWaiters;
|
||||
this.loginWaiters = [];
|
||||
for (const waiter of waiters) waiter.resolve({ ...next });
|
||||
|
||||
for (const waiter of waiters) {
|
||||
waiter.resolve({ ...next });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1046,20 +1281,31 @@ export class QqHookClient extends EventEmitter {
|
||||
this.resolveHello(frame, false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.op === PipeOp.loginState) {
|
||||
this.applyLoginStateFrame(frame);
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.op === PipeOp.sendAck) {
|
||||
const pending = this.pendingAcks.get(frame.requestId);
|
||||
if (!pending) return;
|
||||
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.pendingAcks.delete(frame.requestId);
|
||||
pending.resolve({ requestId: frame.requestId, wantReply: pending.wantReply });
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.op === PipeOp.sendReply) {
|
||||
const pending = this.pendingReplies.get(frame.requestId);
|
||||
if (!pending) return;
|
||||
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.pendingReplies.delete(frame.requestId);
|
||||
pending.resolve({
|
||||
requestId: frame.requestId,
|
||||
@@ -1069,6 +1315,7 @@ export class QqHookClient extends EventEmitter {
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.op === PipeOp.error) {
|
||||
const error = new HookPipeRequestError(
|
||||
frame.msg || `pipe error ${frame.status}`,
|
||||
@@ -1076,11 +1323,14 @@ export class QqHookClient extends EventEmitter {
|
||||
frame.requestId,
|
||||
);
|
||||
const ack = this.pendingAcks.get(frame.requestId);
|
||||
|
||||
if (ack) {
|
||||
this.pendingAcks.delete(frame.requestId);
|
||||
ack.reject(error);
|
||||
}
|
||||
|
||||
const reply = this.pendingReplies.get(frame.requestId);
|
||||
|
||||
if (reply) {
|
||||
this.pendingReplies.delete(frame.requestId);
|
||||
reply.reject(error);
|
||||
@@ -1093,11 +1343,16 @@ export class QqHookClient extends EventEmitter {
|
||||
this.resolveHello(frame, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.op === PipeOp.loginState) {
|
||||
this.applyLoginStateFrame(frame);
|
||||
return;
|
||||
}
|
||||
if (frame.op !== PipeOp.recvPacket) return;
|
||||
|
||||
if (frame.op !== PipeOp.recvPacket) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.emit('packet', {
|
||||
seq: Number(frame.value0),
|
||||
error: frame.status,
|
||||
|
||||
@@ -11,7 +11,11 @@ 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;
|
||||
|
||||
if (probeNotes.get(pid) === message) {
|
||||
return;
|
||||
}
|
||||
|
||||
probeNotes.set(pid, message);
|
||||
log.info(message);
|
||||
}
|
||||
@@ -67,7 +71,9 @@ async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin
|
||||
|
||||
const handleResponse = (res: http.IncomingMessage) => {
|
||||
let text = '';
|
||||
res.on('data', (chunk) => { text += chunk.toString(); });
|
||||
res.on('data', (chunk) => {
|
||||
text += chunk.toString();
|
||||
});
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const inner = text.split('[')[1].split(']')[0];
|
||||
@@ -80,7 +86,11 @@ async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin
|
||||
};
|
||||
|
||||
const req = useHttps
|
||||
? https.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false }, handleResponse)
|
||||
? 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));
|
||||
@@ -97,7 +107,9 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
|
||||
const res1 = await fetchPtlogin(port, useHttps);
|
||||
const res2 = await fetchPtlogin(port, useHttps);
|
||||
|
||||
if (res1 === null && res2 === null) return 'fallback';
|
||||
if (res1 === null && res2 === null) {
|
||||
return 'fallback';
|
||||
}
|
||||
|
||||
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
|
||||
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
|
||||
@@ -115,7 +127,6 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
|
||||
return 'fallback';
|
||||
}
|
||||
|
||||
|
||||
async function getQqProcessCount(): Promise<number> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
@@ -123,7 +134,10 @@ async function getQqProcessCount(): Promise<number> {
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh',
|
||||
EXEC_OPTIONS,
|
||||
);
|
||||
return stdout.toLowerCase().split('\n').filter(line => line.includes('qq.exe')).length;
|
||||
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;
|
||||
@@ -141,29 +155,48 @@ async function getProcessPorts(pid: number): Promise<number[] | null> {
|
||||
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;
|
||||
|
||||
if (parts.length < 5) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const owningPid = parts[parts.length - 1];
|
||||
if (owningPid !== String(pid)) continue;
|
||||
|
||||
if (owningPid !== String(pid)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const localAddr = parts[1];
|
||||
const portMatch = localAddr.match(/:(\d+)$/);
|
||||
if (!portMatch) continue;
|
||||
|
||||
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;
|
||||
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 {
|
||||
@@ -173,6 +206,7 @@ async function getProcessPorts(pid: number): Promise<number[] | null> {
|
||||
|
||||
async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
|
||||
if (ports === null) {
|
||||
noteProbe(pid, 'unavailable', 0, null);
|
||||
return null;
|
||||
@@ -180,20 +214,24 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
|
||||
|
||||
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));
|
||||
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) {
|
||||
@@ -203,12 +241,14 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
|
||||
if (ptPortsToTry.length > 0) {
|
||||
for (const port of ptPortsToTry) {
|
||||
const ptResult = await tryPtloginMethod(port);
|
||||
|
||||
if (ptResult !== 'fallback') {
|
||||
return ptResult;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const totalPids = await getQqProcessCount();
|
||||
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
noteProbe(pid, 'no-ports', ports.length, totalPids);
|
||||
return {
|
||||
@@ -217,6 +257,7 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
|
||||
identityKnown: false,
|
||||
};
|
||||
}
|
||||
|
||||
noteProbe(pid, 'inconclusive', ports.length, totalPids);
|
||||
return null;
|
||||
}
|
||||
@@ -230,17 +271,24 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
|
||||
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let timedOut = false;
|
||||
const timeout = new Promise<null>(resolve => {
|
||||
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);
|
||||
|
||||
if (timedOut) {
|
||||
log.warn('login check timed out: PID=%d', pid);
|
||||
}
|
||||
|
||||
return result;
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,7 @@
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
export type HookProcessStatus =
|
||||
| 'available'
|
||||
| 'loading'
|
||||
| 'connecting'
|
||||
| 'loaded'
|
||||
| 'online'
|
||||
| 'error'
|
||||
| 'disconnected';
|
||||
'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected';
|
||||
|
||||
/** Public-facing snapshot of a per-PID HookSession. */
|
||||
export interface HookProcessInfo extends HookProcessBaseInfo {
|
||||
|
||||
@@ -13,7 +13,7 @@ import type { QqHookClient } from '../src/qq-hook-client';
|
||||
// browser without REST polling.
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
interface Harness {
|
||||
manager: HookManager;
|
||||
@@ -29,7 +29,7 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
|
||||
let pids = opts.processes ?? [];
|
||||
let live = new Set<number>(opts.livePipes ?? []);
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
@@ -38,8 +38,15 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { /* succeed without doing anything */ };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
|
||||
(c as any).connectAll = async () => {
|
||||
/* succeed without doing anything */
|
||||
};
|
||||
|
||||
(c as any).close = () => {
|
||||
(c as any).isClosed = true;
|
||||
};
|
||||
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
@@ -57,7 +64,7 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: clientFactory,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
onSessionsChanged,
|
||||
});
|
||||
return {
|
||||
@@ -66,8 +73,12 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
|
||||
bridgeManager,
|
||||
onSessionsChanged,
|
||||
clientFactory,
|
||||
setProcesses: (next) => { pids = next; },
|
||||
setLivePipes: (next) => { live = new Set(next); },
|
||||
setProcesses: (next) => {
|
||||
pids = next;
|
||||
},
|
||||
setLivePipes: (next) => {
|
||||
live = new Set(next);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -120,7 +131,9 @@ describe('HookManager.onSessionsChanged', () => {
|
||||
|
||||
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
ctx.onSessionsChanged.mockImplementation(() => { throw new Error('listener boom'); });
|
||||
ctx.onSessionsChanged.mockImplementation(() => {
|
||||
throw new Error('listener boom');
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
ctx.setProcesses([4242]);
|
||||
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
|
||||
@@ -139,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: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
@@ -151,18 +164,26 @@ describe('HookManager.onSessionsChanged', () => {
|
||||
} as unknown as BridgeManagerSink,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: vi.fn(() => {
|
||||
const c = new EventEmitter() as any;
|
||||
c.isClosed = false; c.isLoggedIn = false;
|
||||
c.isClosed = false;
|
||||
c.isLoggedIn = false;
|
||||
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
c.connectAll = async () => undefined;
|
||||
c.close = () => { c.isClosed = true; };
|
||||
|
||||
c.close = () => {
|
||||
c.isClosed = true;
|
||||
};
|
||||
|
||||
return c;
|
||||
}),
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
// onSessionsChanged deliberately omitted
|
||||
});
|
||||
await pipeWatcher.start();
|
||||
@@ -187,6 +208,7 @@ describe('HookManager receive-health wiring (#233)', () => {
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
|
||||
try {
|
||||
client.emit('packet', {
|
||||
seq: 1,
|
||||
@@ -206,7 +228,10 @@ describe('HookManager receive-health wiring (#233)', () => {
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(4242, true);
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(
|
||||
4242,
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
ctx.manager.dispose();
|
||||
|
||||
@@ -17,13 +17,11 @@ import {
|
||||
} from '@snowluma/common/logger';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function managerTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter(
|
||||
(entry) => entry.level === 'trace' && entry.scope === 'Hook',
|
||||
);
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Hook');
|
||||
}
|
||||
|
||||
function makeManager(opts: {
|
||||
@@ -34,13 +32,16 @@ function makeManager(opts: {
|
||||
}) {
|
||||
let pids = opts.processes ?? [];
|
||||
const live = new Set<number>();
|
||||
const inject = vi.fn(opts.inject ?? (() => ({
|
||||
const inject = vi.fn(
|
||||
opts.inject ??
|
||||
(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})));
|
||||
})),
|
||||
);
|
||||
const unload = vi.fn();
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
@@ -51,8 +52,15 @@ function makeManager(opts: {
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { throw new Error('test: never really connect'); };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
|
||||
(c as any).connectAll = async () => {
|
||||
throw new Error('test: never really connect');
|
||||
};
|
||||
|
||||
(c as any).close = () => {
|
||||
(c as any).isClosed = true;
|
||||
};
|
||||
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
@@ -67,13 +75,15 @@ function makeManager(opts: {
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
onSessionsChanged: opts.onSessionsChanged,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
inject,
|
||||
pipeWatcher,
|
||||
setProcesses: (next: number[]) => { pids = next; },
|
||||
setProcesses: (next: number[]) => {
|
||||
pids = next;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -92,6 +102,7 @@ describe('HookManager runtime TRACE', () => {
|
||||
processes: [],
|
||||
onSessionsChanged: sessionsChanged,
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
const baseline = managerTrace(entries).length;
|
||||
@@ -105,8 +116,8 @@ describe('HookManager runtime TRACE', () => {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
|
||||
const facts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_manager_fact '),
|
||||
const facts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_manager_fact '),
|
||||
);
|
||||
expect(facts.map((entry) => entry.message)).toEqual([
|
||||
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
|
||||
@@ -134,6 +145,7 @@ describe('HookManager runtime TRACE', () => {
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
}));
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
@@ -142,14 +154,18 @@ describe('HookManager runtime TRACE', () => {
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_'),
|
||||
const attempts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/),
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/,
|
||||
),
|
||||
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
|
||||
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/),
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
expect(attempts[2]!.req).toBe(attempts[3]!.req);
|
||||
@@ -173,6 +189,7 @@ describe('HookManager runtime TRACE', () => {
|
||||
processes: [4242],
|
||||
inject: () => injection,
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
@@ -181,8 +198,8 @@ describe('HookManager runtime TRACE', () => {
|
||||
await manualLoad;
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_'),
|
||||
const attempts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
@@ -217,22 +234,26 @@ describe('HookManager runtime TRACE', () => {
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => { throw new Error(error); });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error(error);
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
for (let tick = 0; tick < ticks; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
|
||||
const starts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_start '),
|
||||
const starts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_start '),
|
||||
);
|
||||
const terminals = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_terminal '),
|
||||
const terminals = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_terminal '),
|
||||
);
|
||||
expect(starts).toHaveLength(attempts);
|
||||
expect(terminals).toHaveLength(attempts);
|
||||
@@ -276,7 +297,9 @@ describe('HookManager.autoLoadOnDiscovery', () => {
|
||||
|
||||
it('swallows inject errors so the watcher keeps running', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); });
|
||||
ctx.inject.mockImplementationOnce(() => {
|
||||
throw new Error('ptrace denied');
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
@@ -316,7 +339,9 @@ describe('HookManager.autoLoadOnDiscovery', () => {
|
||||
|
||||
it('does not retry permanent auto-load errors', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => { throw new Error('ptrace denied'); });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error('ptrace denied');
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
@@ -347,6 +372,7 @@ describe('HookManager.autoLoadOnDiscovery', () => {
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(3);
|
||||
|
||||
ctx.manager.dispose();
|
||||
@@ -368,11 +394,19 @@ describe('shouldAutoLoadPid', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((p: string, ...rest: unknown[]) => {
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((
|
||||
p: string,
|
||||
...rest: unknown[]
|
||||
) => {
|
||||
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
|
||||
|
||||
if (match) {
|
||||
return originalReadFileSync(path.join(tmpProc, match[1], 'cmdline'), ...(rest as [BufferEncoding]));
|
||||
return originalReadFileSync(
|
||||
path.join(tmpProc, match[1], 'cmdline'),
|
||||
...(rest as [BufferEncoding]),
|
||||
);
|
||||
}
|
||||
|
||||
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
|
||||
}) as typeof fs.readFileSync;
|
||||
});
|
||||
@@ -380,8 +414,13 @@ describe('shouldAutoLoadPid', () => {
|
||||
afterEach(() => {
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
|
||||
if (originalAutoLoadAll === undefined) delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
else process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
|
||||
|
||||
if (originalAutoLoadAll === undefined) {
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
|
||||
}
|
||||
|
||||
fs.rmSync(tmpProc, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
@@ -404,7 +443,11 @@ describe('shouldAutoLoadPid', () => {
|
||||
it('rejects renderer/gpu/utility children', () => {
|
||||
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
|
||||
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
|
||||
writeCmdline(72, ['/opt/QQ/qq', '--type=utility', '--utility-sub-type=network.mojom.NetworkService']);
|
||||
writeCmdline(72, [
|
||||
'/opt/QQ/qq',
|
||||
'--type=utility',
|
||||
'--utility-sub-type=network.mojom.NetworkService',
|
||||
]);
|
||||
expect(shouldAutoLoadPid(70, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(71, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(72, log)).toBe(false);
|
||||
|
||||
@@ -18,16 +18,20 @@ describe('HookPacketClient outbound health', () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValueOnce(new HookPipeRequestError(
|
||||
.mockRejectedValueOnce(
|
||||
new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
1,
|
||||
))
|
||||
.mockRejectedValueOnce(new HookPipeRequestError(
|
||||
),
|
||||
)
|
||||
.mockRejectedValueOnce(
|
||||
new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
2,
|
||||
))
|
||||
),
|
||||
)
|
||||
.mockResolvedValueOnce({
|
||||
requestId: 3,
|
||||
error: 0,
|
||||
@@ -36,24 +40,30 @@ describe('HookPacketClient outbound health', () => {
|
||||
});
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: false, gotResponse: false });
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
});
|
||||
await sender.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: true, gotResponse: true });
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
});
|
||||
|
||||
expect(healthChanged.mock.calls).toEqual([[false], [true]]);
|
||||
});
|
||||
|
||||
it('does not classify ordinary request rejection as connection loss', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi.fn<QqHookClient['send']>().mockRejectedValue(
|
||||
new HookPipeRequestError('This request is not valid.', -38, 1),
|
||||
);
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValue(new HookPipeRequestError('This request is not valid.', -38, 1));
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: false, gotResponse: false });
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
});
|
||||
|
||||
expect(healthChanged).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -13,17 +13,24 @@ import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
async connectAll(_opts: { recv: boolean }) {
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
if (this.isClosed) {
|
||||
throw new Error('client is closed');
|
||||
}
|
||||
}
|
||||
getLoginState() {
|
||||
return { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
}
|
||||
getLoginState() { return { loggedIn: false, uin: '0', uinNumber: 0n }; }
|
||||
close() {
|
||||
if (this.isClosed) return;
|
||||
if (this.isClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
@@ -51,7 +58,10 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
@@ -71,6 +81,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
// Drive 50 pipe up/down cycles with the QQ process staying alive but
|
||||
// the pipe (= QQ control socket) bouncing every "tick".
|
||||
const CYCLES = 50;
|
||||
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
liveSet.delete(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
@@ -87,8 +98,11 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
|
||||
|
||||
// Hook layer should hold at most one live client.
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
expect(alive.length, `live clients after ${CYCLES} cycles: ${alive.length}`).toBeLessThanOrEqual(1);
|
||||
const alive = clients.filter((c) => !c.isClosed);
|
||||
expect(
|
||||
alive.length,
|
||||
`live clients after ${CYCLES} cycles: ${alive.length}`,
|
||||
).toBeLessThanOrEqual(1);
|
||||
|
||||
// Total clients minted = roughly one per up cycle. Sanity bound:
|
||||
// we must have actually exercised the reconnect path.
|
||||
|
||||
@@ -29,11 +29,18 @@ class FakeClient extends EventEmitter {
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
if (this.isClosed) {
|
||||
throw new Error('client is closed');
|
||||
}
|
||||
}
|
||||
getLoginState() {
|
||||
return { ...this.loginState };
|
||||
}
|
||||
getLoginState() { return { ...this.loginState }; }
|
||||
close(): void {
|
||||
if (this.isClosed) return;
|
||||
if (this.isClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
@@ -43,7 +50,7 @@ function totalListenerCount(emitter: EventEmitter): number {
|
||||
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
|
||||
}
|
||||
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
|
||||
@@ -51,7 +58,10 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
@@ -67,6 +77,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
await flush();
|
||||
|
||||
const CYCLES = 50;
|
||||
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
@@ -76,10 +87,12 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
await flush();
|
||||
}
|
||||
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
const alive = clients.filter((c) => !c.isClosed);
|
||||
expect.soft(clients.length).toBeGreaterThan(1);
|
||||
expect(alive.length, `expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`)
|
||||
.toBeLessThanOrEqual(1);
|
||||
expect(
|
||||
alive.length,
|
||||
`expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`,
|
||||
).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('drops all listeners from each torn-down client', async () => {
|
||||
@@ -87,7 +100,10 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
@@ -103,6 +119,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
await flush();
|
||||
|
||||
const CYCLES = 20;
|
||||
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
@@ -116,8 +133,10 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
// (HookSession.tearDownClient does client.removeAllListeners().)
|
||||
for (let i = 0; i < clients.length - 1; i++) {
|
||||
const lc = totalListenerCount(clients[i]);
|
||||
expect(lc, `client #${i} of ${clients.length} still has ${lc} listeners after teardown`)
|
||||
.toBe(0);
|
||||
expect(
|
||||
lc,
|
||||
`client #${i} of ${clients.length} still has ${lc} listeners after teardown`,
|
||||
).toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,14 +4,19 @@ import { resolveHookRuntimeDir } from '../src/hook-runtime-dir';
|
||||
function procReader(files: Record<string, string>) {
|
||||
return (file: string): string => {
|
||||
const value = files[file];
|
||||
if (value === undefined) throw new Error(`missing fixture: ${file}`);
|
||||
|
||||
if (value === undefined) {
|
||||
throw new Error(`missing fixture: ${file}`);
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
describe('resolveHookRuntimeDir — Linux target process ownership', () => {
|
||||
it('uses the QQ process runtime directory instead of the supervisor user directory', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
@@ -19,11 +24,13 @@ describe('resolveHookRuntimeDir — Linux target process ownership', () => {
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0XDG_RUNTIME_DIR=/run/user/1000\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/run/user/1000');
|
||||
}),
|
||||
).toBe('/run/user/1000');
|
||||
});
|
||||
|
||||
it('falls back to the QQ process uid when its environment has no runtime directory', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
@@ -31,30 +38,40 @@ describe('resolveHookRuntimeDir — Linux target process ownership', () => {
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/tmp/snowluma-1000');
|
||||
}),
|
||||
).toBe('/tmp/snowluma-1000');
|
||||
});
|
||||
|
||||
it('fails visibly when target ownership cannot be determined', () => {
|
||||
expect(() => resolveHookRuntimeDir(46301, {
|
||||
expect(() =>
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => { throw new Error('permission denied'); },
|
||||
})).toThrow(/cannot resolve hook runtime directory.*permission denied/);
|
||||
readText: () => {
|
||||
throw new Error('permission denied');
|
||||
},
|
||||
}),
|
||||
).toThrow(/cannot resolve hook runtime directory.*permission denied/);
|
||||
});
|
||||
|
||||
it('uses the current convention when the target disappears during discovery', () => {
|
||||
const gone = Object.assign(new Error('process disappeared'), { code: 'ENOENT' });
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => { throw gone; },
|
||||
})).toBe('/run/user/0');
|
||||
readText: () => {
|
||||
throw gone;
|
||||
},
|
||||
}),
|
||||
).toBe('/run/user/0');
|
||||
});
|
||||
|
||||
it('honours an explicit runtime directory inherited by the QQ process', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
expect(
|
||||
resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: {},
|
||||
ownUid: 0,
|
||||
@@ -62,6 +79,7 @@ describe('resolveHookRuntimeDir — Linux target process ownership', () => {
|
||||
'/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0',
|
||||
'/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/srv/snowluma-hook');
|
||||
}),
|
||||
).toBe('/srv/snowluma-hook');
|
||||
});
|
||||
});
|
||||
@@ -11,19 +11,12 @@ import {
|
||||
import type { QqPortLoginInfo } from '../src/qq-port-probe';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
import {
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function sessionTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter(
|
||||
(entry) => entry.level === 'trace' && entry.scope === 'HookSession',
|
||||
);
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'HookSession');
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
@@ -46,10 +39,17 @@ class FakeClient extends EventEmitter {
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
if (this.shouldFailConnect) throw new Error('connect failed');
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
if (this.shouldFailConnect) {
|
||||
throw new Error('connect failed');
|
||||
}
|
||||
|
||||
if (this.isClosed) {
|
||||
throw new Error('client is closed');
|
||||
}
|
||||
}
|
||||
getLoginState() {
|
||||
return { ...this.loginState };
|
||||
}
|
||||
getLoginState() { return { ...this.loginState }; }
|
||||
reconcileLoginState(state: { loggedIn: boolean; uin: string; uinNumber: bigint }): void {
|
||||
this.isLoggedIn = state.loggedIn;
|
||||
this.loginState = { ...state };
|
||||
@@ -57,14 +57,21 @@ class FakeClient extends EventEmitter {
|
||||
}
|
||||
async reconcileLoginIdentity(uin: string): Promise<void> {
|
||||
this.loginIdentityHints.push(uin);
|
||||
|
||||
if (this.identityHintFailures > 0) {
|
||||
this.identityHintFailures--;
|
||||
throw new Error('identity hint unavailable');
|
||||
}
|
||||
if (this.nativeReadyOnIdentityHint) this.fireLogin(uin);
|
||||
|
||||
if (this.nativeReadyOnIdentityHint) {
|
||||
this.fireLogin(uin);
|
||||
}
|
||||
}
|
||||
async send(serviceCmd: string, body: Buffer) {
|
||||
if (this.sendError) throw this.sendError;
|
||||
if (this.sendError) {
|
||||
throw this.sendError;
|
||||
}
|
||||
|
||||
this.sentPackets.push({ serviceCmd, body: Buffer.from(body) });
|
||||
return {
|
||||
requestId: this.sentPackets.length,
|
||||
@@ -74,7 +81,10 @@ class FakeClient extends EventEmitter {
|
||||
};
|
||||
}
|
||||
close(): void {
|
||||
if (this.isClosed) return;
|
||||
if (this.isClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
@@ -88,7 +98,8 @@ class FakeClient extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
function makeSession(opts: {
|
||||
function makeSession(
|
||||
opts: {
|
||||
pid?: number;
|
||||
pipeLive?: boolean;
|
||||
clientFailsConnect?: boolean;
|
||||
@@ -96,7 +107,8 @@ function makeSession(opts: {
|
||||
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
|
||||
nativeReadyOnIdentityHint?: boolean;
|
||||
identityHintFailures?: number;
|
||||
} = {}) {
|
||||
} = {},
|
||||
) {
|
||||
const pid = opts.pid ?? 1234;
|
||||
let pipeLive = opts.pipeLive ?? false;
|
||||
const clients: FakeClient[] = [];
|
||||
@@ -106,13 +118,18 @@ function makeSession(opts: {
|
||||
};
|
||||
// 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 probeLogin =
|
||||
opts.probeLogin ?? (async () => ({ port: 0, uin: '', identityKnown: false }));
|
||||
|
||||
const session = new HookSession(pid, {
|
||||
injector,
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
if (opts.clientFailsConnect) c.shouldFailConnect = true;
|
||||
|
||||
if (opts.clientFailsConnect) {
|
||||
c.shouldFailConnect = true;
|
||||
}
|
||||
|
||||
c.nativeReadyOnIdentityHint = opts.nativeReadyOnIdentityHint ?? false;
|
||||
c.identityHintFailures = opts.identityHintFailures ?? 0;
|
||||
clients.push(c);
|
||||
@@ -129,17 +146,20 @@ function makeSession(opts: {
|
||||
injector,
|
||||
clients,
|
||||
currentClient: () => clients[clients.length - 1]!,
|
||||
setPipeLive: (v: boolean) => { pipeLive = v; },
|
||||
setPipeLive: (v: boolean) => {
|
||||
pipeLive = v;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
describe('HookSession — runtime TRACE', () => {
|
||||
it('records injection and existing-pipe load branches with unique terminals', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
|
||||
try {
|
||||
const injected = makeSession({ pid: 7101, pipeLive: false });
|
||||
const reconnect = makeSession({ pid: 7102, pipeLive: true });
|
||||
@@ -147,19 +167,28 @@ describe('HookSession — runtime TRACE', () => {
|
||||
await reconnect.session.load();
|
||||
|
||||
const messages = sessionTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect(messages).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining('hook_session_start pid=7101 operation=load'),
|
||||
'hook_session_branch pid=7101 operation=load branch=inject_begin',
|
||||
'hook_session_branch pid=7101 operation=load branch=inject_completed method="loadModuleManual"',
|
||||
expect.stringMatching(/^hook_session_terminal pid=7101 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/),
|
||||
expect.stringMatching(
|
||||
/^hook_session_terminal pid=7101 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
expect.stringContaining('hook_session_start pid=7102 operation=load'),
|
||||
'hook_session_branch pid=7102 operation=load branch=existing_pipe method="reconnect"',
|
||||
expect.stringMatching(/^hook_session_terminal pid=7102 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/),
|
||||
]));
|
||||
expect.stringMatching(
|
||||
/^hook_session_terminal pid=7102 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
]),
|
||||
);
|
||||
|
||||
for (const pid of [7101, 7102]) {
|
||||
expect(messages.filter(
|
||||
(message) => message.startsWith(`hook_session_terminal pid=${pid} operation=load `),
|
||||
)).toHaveLength(1);
|
||||
expect(
|
||||
messages.filter((message) =>
|
||||
message.startsWith(`hook_session_terminal pid=${pid} operation=load `),
|
||||
),
|
||||
).toHaveLength(1);
|
||||
}
|
||||
} finally {
|
||||
unsubscribe();
|
||||
@@ -170,9 +199,12 @@ describe('HookSession — runtime TRACE', () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
|
||||
try {
|
||||
const injector = {
|
||||
inject: vi.fn(() => { throw new Error('fixture inject failure'); }),
|
||||
inject: vi.fn(() => {
|
||||
throw new Error('fixture inject failure');
|
||||
}),
|
||||
unload: vi.fn(),
|
||||
};
|
||||
const failedLoad = new HookSession(7103, {
|
||||
@@ -192,14 +224,22 @@ describe('HookSession — runtime TRACE', () => {
|
||||
await flush();
|
||||
|
||||
const messages = sessionTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringMatching(/^hook_session_terminal pid=7103 operation=load outcome=failed reason=load_failed error="fixture inject failure" state=.*elapsedMs=\d+$/),
|
||||
expect(messages).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringMatching(
|
||||
/^hook_session_terminal pid=7103 operation=load outcome=failed reason=load_failed error="fixture inject failure" state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
expect.stringContaining('hook_session_connect_start pid=7104'),
|
||||
expect.stringMatching(/^hook_session_connect_terminal pid=7104 outcome=failed reason=connect_failed error="connect failed" state=.*elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(messages.filter(
|
||||
(message) => message.startsWith('hook_session_connect_terminal pid=7104 '),
|
||||
)).toHaveLength(1);
|
||||
expect.stringMatching(
|
||||
/^hook_session_connect_terminal pid=7104 outcome=failed reason=connect_failed error="connect failed" state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
messages.filter((message) =>
|
||||
message.startsWith('hook_session_connect_terminal pid=7104 '),
|
||||
),
|
||||
).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
@@ -239,6 +279,7 @@ describe('HookSession — runtime TRACE', () => {
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeSession({ pid: 7105, pipeLive: true });
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
@@ -253,20 +294,34 @@ describe('HookSession — runtime TRACE', () => {
|
||||
await flush();
|
||||
|
||||
const messages = sessionTrace(entries).map((entry) => entry.message);
|
||||
expect(messages.filter(
|
||||
(message) => message.startsWith('hook_session_login_terminal pid=7105 '),
|
||||
)).toHaveLength(1);
|
||||
expect(messages.filter(
|
||||
(message) => message.startsWith('hook_session_disconnect_terminal pid=7105 '),
|
||||
)).toHaveLength(1);
|
||||
expect(messages.filter(
|
||||
(message) => message.startsWith('hook_session_process_terminal pid=7105 '),
|
||||
)).toHaveLength(1);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringMatching(/^hook_session_login_terminal pid=7105 outcome=completed reason=login_detected previousUin="0" uin="10001" state=.*elapsedMs=\d+$/),
|
||||
expect.stringMatching(/^hook_session_disconnect_terminal pid=7105 outcome=completed reason=pipe_down wasLoggedIn=true state=.*elapsedMs=\d+$/),
|
||||
expect.stringMatching(/^hook_session_process_terminal pid=7105 outcome=completed reason=process_gone wasLoggedIn=false state=.*elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(
|
||||
messages.filter((message) =>
|
||||
message.startsWith('hook_session_login_terminal pid=7105 '),
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
messages.filter((message) =>
|
||||
message.startsWith('hook_session_disconnect_terminal pid=7105 '),
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
messages.filter((message) =>
|
||||
message.startsWith('hook_session_process_terminal pid=7105 '),
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(messages).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringMatching(
|
||||
/^hook_session_login_terminal pid=7105 outcome=completed reason=login_detected previousUin="0" uin="10001" state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
expect.stringMatching(
|
||||
/^hook_session_disconnect_terminal pid=7105 outcome=completed reason=pipe_down wasLoggedIn=true state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
expect.stringMatching(
|
||||
/^hook_session_process_terminal pid=7105 outcome=completed reason=process_gone wasLoggedIn=false state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
]),
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.session.dispose();
|
||||
@@ -280,37 +335,59 @@ describe('HookSession — runtime TRACE', () => {
|
||||
const login = makeSession({ pid: 7107, pipeLive: true });
|
||||
const disconnect = makeSession({ pid: 7108, pipeLive: true });
|
||||
const processGone = makeSession({ pid: 7109, pipeLive: true });
|
||||
|
||||
try {
|
||||
await login.session.load();
|
||||
login.session.onPipeUp();
|
||||
await flush();
|
||||
login.session.on('login', () => { throw new Error('login listener boom'); });
|
||||
login.session.on('login', () => {
|
||||
throw new Error('login listener boom');
|
||||
});
|
||||
expect(() => login.currentClient().fireLogin('10001')).toThrow('login listener boom');
|
||||
|
||||
await disconnect.session.load();
|
||||
disconnect.session.onPipeUp();
|
||||
await flush();
|
||||
disconnect.currentClient().fireLogin('10002');
|
||||
disconnect.session.on('disconnected', () => { throw new Error('disconnect listener boom'); });
|
||||
disconnect.session.on('disconnected', () => {
|
||||
throw new Error('disconnect listener boom');
|
||||
});
|
||||
disconnect.session.onPipeDown();
|
||||
await flush();
|
||||
|
||||
processGone.session.on('disposed', () => { throw new Error('dispose listener boom'); });
|
||||
processGone.session.on('disposed', () => {
|
||||
throw new Error('dispose listener boom');
|
||||
});
|
||||
processGone.session.notifyProcessGone();
|
||||
await flush();
|
||||
|
||||
const messages = sessionTrace(entries).map((entry) => entry.message);
|
||||
expect(messages.filter((message) =>
|
||||
message.startsWith('hook_session_login_terminal pid=7107 '))).toEqual([
|
||||
expect.stringMatching(/^hook_session_login_terminal pid=7107 outcome=failed reason=listener_failed error="login listener boom" state=.*elapsedMs=\d+$/),
|
||||
expect(
|
||||
messages.filter((message) =>
|
||||
message.startsWith('hook_session_login_terminal pid=7107 '),
|
||||
),
|
||||
).toEqual([
|
||||
expect.stringMatching(
|
||||
/^hook_session_login_terminal pid=7107 outcome=failed reason=listener_failed error="login listener boom" state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(messages.filter((message) =>
|
||||
message.startsWith('hook_session_disconnect_terminal pid=7108 '))).toEqual([
|
||||
expect.stringMatching(/^hook_session_disconnect_terminal pid=7108 outcome=failed reason=listener_failed error="disconnect listener boom" state=.*elapsedMs=\d+$/),
|
||||
expect(
|
||||
messages.filter((message) =>
|
||||
message.startsWith('hook_session_disconnect_terminal pid=7108 '),
|
||||
),
|
||||
).toEqual([
|
||||
expect.stringMatching(
|
||||
/^hook_session_disconnect_terminal pid=7108 outcome=failed reason=listener_failed error="disconnect listener boom" state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(messages.filter((message) =>
|
||||
message.startsWith('hook_session_process_terminal pid=7109 '))).toEqual([
|
||||
expect.stringMatching(/^hook_session_process_terminal pid=7109 outcome=failed reason=listener_failed error="dispose listener boom" state=.*elapsedMs=\d+$/),
|
||||
expect(
|
||||
messages.filter((message) =>
|
||||
message.startsWith('hook_session_process_terminal pid=7109 '),
|
||||
),
|
||||
).toEqual([
|
||||
expect.stringMatching(
|
||||
/^hook_session_process_terminal pid=7109 outcome=failed reason=listener_failed error="dispose listener boom" state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
@@ -325,13 +402,14 @@ describe('HookSession — runtime TRACE', () => {
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeSession({ pid: 7106, pipeLive: false });
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.setPipeLive(true);
|
||||
await ctx.session.unload();
|
||||
|
||||
const terminals = sessionTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_session_terminal pid=7106 operation=unload '),
|
||||
const terminals = sessionTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_session_terminal pid=7106 operation=unload '),
|
||||
);
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toMatch(
|
||||
@@ -365,10 +443,15 @@ describe('HookSession — load', () => {
|
||||
});
|
||||
|
||||
it('keeps loading pending until asynchronous component loading completes', async () => {
|
||||
let finishLoading!: (result: { method: 'loadModuleManual'; handle: ManualMapHandle }) => void;
|
||||
const loading = new Promise<{ method: 'loadModuleManual'; handle: ManualMapHandle }>(resolve => {
|
||||
let finishLoading!: (result: {
|
||||
method: 'loadModuleManual';
|
||||
handle: ManualMapHandle;
|
||||
}) => void;
|
||||
const loading = new Promise<{ method: 'loadModuleManual'; handle: ManualMapHandle }>(
|
||||
(resolve) => {
|
||||
finishLoading = resolve;
|
||||
});
|
||||
},
|
||||
);
|
||||
const injector = {
|
||||
inject: vi.fn(() => loading),
|
||||
unload: vi.fn(),
|
||||
@@ -393,7 +476,9 @@ describe('HookSession — load', () => {
|
||||
|
||||
it('inject failure → status error, error message captured', async () => {
|
||||
const injector = {
|
||||
inject: vi.fn(() => { throw new Error('inject boom'); }),
|
||||
inject: vi.fn(() => {
|
||||
throw new Error('inject boom');
|
||||
}),
|
||||
unload: vi.fn(),
|
||||
};
|
||||
const session = new HookSession(1234, {
|
||||
@@ -589,11 +674,16 @@ describe('HookSession — unload', () => {
|
||||
// the snapshot first and verification correctly sees the pipe down.
|
||||
const pid = 5555;
|
||||
let pipeLive = true; // initial cached state: pipe is live
|
||||
const tickNow = vi.fn(async () => { pipeLive = false; }); // OS poll says: gone now
|
||||
const tickNow = vi.fn(async () => {
|
||||
pipeLive = false;
|
||||
}); // OS poll says: gone now
|
||||
|
||||
const session = new HookSession(pid, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => new FakeClient() as unknown as QqHookClient,
|
||||
@@ -776,7 +866,9 @@ 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(() => { throw new Error('inject boom'); }),
|
||||
inject: vi.fn(() => {
|
||||
throw new Error('inject boom');
|
||||
}),
|
||||
unload: vi.fn(),
|
||||
};
|
||||
const session = new HookSession(1234, {
|
||||
@@ -841,7 +933,11 @@ describe('HookSession — packet forwarding', () => {
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 1, error: 0, cmd: 'foo', uin: '', body: Buffer.alloc(0),
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'foo',
|
||||
uin: '',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
|
||||
expect(onPacket.mock.calls[0]![0].uin).toBe('10001');
|
||||
@@ -856,7 +952,11 @@ describe('HookSession — packet forwarding', () => {
|
||||
// No login fired yet.
|
||||
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.alloc(0),
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'foo',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
@@ -874,7 +974,11 @@ describe('HookSession — packet forwarding', () => {
|
||||
// Force a bad uin via the packet AND null out session uin by simulating
|
||||
// a logout? Simpler: send a packet with uin '42' (numeric but <5 chars).
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 1, error: 0, cmd: 'foo', uin: '42', body: Buffer.alloc(0),
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'foo',
|
||||
uin: '42',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
@@ -889,7 +993,11 @@ describe('HookSession — packet forwarding', () => {
|
||||
|
||||
// Should not throw / crash.
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.from([7]),
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'foo',
|
||||
uin: '10001',
|
||||
body: Buffer.from([7]),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -952,6 +1060,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
@@ -972,6 +1081,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin, identityKnown: true }),
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
@@ -997,6 +1107,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
|
||||
identityHintFailures: 3,
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
@@ -1026,7 +1137,8 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
ctx.session.on('login', loginSpy);
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); await flush();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
@@ -1041,7 +1153,8 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
ctx.session.on('login', loginSpy);
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); await flush();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -1049,13 +1162,16 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
it('tolerates a throwing probe (best-effort, no crash/login)', async () => {
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => { throw new Error('port scan failed'); },
|
||||
probeLogin: async () => {
|
||||
throw new Error('port scan failed');
|
||||
},
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); await flush();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
@@ -1063,6 +1179,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
|
||||
it('detects a login that lands on a LATER interval probe', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
let identityKnown = false;
|
||||
const ctx = makeSession({
|
||||
@@ -1300,10 +1417,16 @@ describe('HookSession — end-to-end receive health (#233)', () => {
|
||||
describe('HookSession — login reconcile does not stack concurrent probes', () => {
|
||||
it('skips overlapping ticks while a slow probe is in flight', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
// A probe that never resolves — simulates a slow port scan spanning
|
||||
// multiple intervals. The in-flight guard must call it only once.
|
||||
const probeLogin = vi.fn(() => new Promise<never>(() => { /* pending */ }));
|
||||
const probeLogin = vi.fn(
|
||||
() =>
|
||||
new Promise<never>(() => {
|
||||
/* pending */
|
||||
}),
|
||||
);
|
||||
const ctx = makeSession({ pipeLive: true, probeLogin });
|
||||
|
||||
await ctx.session.load();
|
||||
|
||||
@@ -3,14 +3,20 @@ import { statusFor, type HookFlags } from '../src/hook-status';
|
||||
import type { HookProcessStatus } from '../src/types';
|
||||
|
||||
const F = (o: Partial<HookFlags>): HookFlags => ({
|
||||
injected: false, connected: false, loggedIn: false, wasLoggedIn: false, ...o,
|
||||
injected: false,
|
||||
connected: false,
|
||||
loggedIn: false,
|
||||
wasLoggedIn: false,
|
||||
...o,
|
||||
});
|
||||
|
||||
describe('statusFor — settled HookProcessStatus derivation', () => {
|
||||
it('not injected → available (regardless of other flags)', () => {
|
||||
expect(statusFor(F({ injected: false }))).toBe('available');
|
||||
// !injected dominates: stale connected/loggedIn bits must not leak through.
|
||||
expect(statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true }))).toBe('available');
|
||||
expect(
|
||||
statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true })),
|
||||
).toBe('available');
|
||||
});
|
||||
|
||||
it('injected, connected, loggedIn → online', () => {
|
||||
@@ -22,11 +28,15 @@ describe('statusFor — settled HookProcessStatus derivation', () => {
|
||||
});
|
||||
|
||||
it('injected, not connected, had logged in → disconnected', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe('disconnected');
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe(
|
||||
'disconnected',
|
||||
);
|
||||
});
|
||||
|
||||
it('injected, not connected, never logged in → connecting', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe('connecting');
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe(
|
||||
'connecting',
|
||||
);
|
||||
});
|
||||
|
||||
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
|
||||
@@ -37,6 +47,7 @@ describe('statusFor — settled HookProcessStatus derivation', () => {
|
||||
|
||||
it('covers exactly the five settled states across the flag space', () => {
|
||||
const seen = new Set<HookProcessStatus>();
|
||||
|
||||
for (const injected of [false, true]) {
|
||||
for (const connected of [false, true]) {
|
||||
for (const loggedIn of [false, true]) {
|
||||
@@ -46,6 +57,7 @@ describe('statusFor — settled HookProcessStatus derivation', () => {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect([...seen].sort()).toEqual(
|
||||
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
|
||||
);
|
||||
|
||||
@@ -59,11 +59,13 @@ function allowExisting(paths: readonly string[]): void {
|
||||
existsSyncMock.mockImplementation((target) => allowed.has(target));
|
||||
}
|
||||
|
||||
function fakeAddon(overrides: {
|
||||
function fakeAddon(
|
||||
overrides: {
|
||||
getAllMainProcess?: number[];
|
||||
loadModuleManual?: (pid: number, dylibPath: string) => unknown;
|
||||
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
|
||||
} = {}) {
|
||||
} = {},
|
||||
) {
|
||||
return {
|
||||
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []),
|
||||
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
|
||||
@@ -158,7 +160,12 @@ describe('resolveHookNativePath', () => {
|
||||
it('re-reads process.cwd() for the dist/native fallback', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
|
||||
const winner = path.join('/tmp/sl-injector-cwd', 'dist', 'native', 'snowluma-darwin-arm64.node');
|
||||
const winner = path.join(
|
||||
'/tmp/sl-injector-cwd',
|
||||
'dist',
|
||||
'native',
|
||||
'snowluma-darwin-arm64.node',
|
||||
);
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
@@ -276,9 +283,11 @@ describe('listHookProcesses', () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
installDlopen(fakeAddon({
|
||||
installDlopen(
|
||||
fakeAddon({
|
||||
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
|
||||
}));
|
||||
}),
|
||||
);
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
@@ -293,9 +302,7 @@ describe('listHookProcesses', () => {
|
||||
installDlopen(fakeAddon({ getAllMainProcess: [9] }));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 9, name: 'QQ.exe', path: '' },
|
||||
]);
|
||||
expect(listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -303,7 +310,9 @@ describe('injectHookProcess', () => {
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow('No hook native addon found for linux-x64');
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow(
|
||||
'No hook native addon found for linux-x64',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when the addon exists but the injectable is missing', async () => {
|
||||
@@ -372,9 +381,11 @@ describe('injectHookProcess', () => {
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.so', 0),
|
||||
]);
|
||||
installDlopen(fakeAddon({
|
||||
installDlopen(
|
||||
fakeAddon({
|
||||
loadModuleManual: () => Promise.reject(new Error('map failed')),
|
||||
}));
|
||||
}),
|
||||
);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(7)).rejects.toThrow('map failed');
|
||||
@@ -385,7 +396,9 @@ describe('unloadHookProcess', () => {
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
expect(() => unloadHookProcess(4242, HANDLE)).toThrow('No hook native addon found for linux-x64');
|
||||
expect(() => unloadHookProcess(4242, HANDLE)).toThrow(
|
||||
'No hook native addon found for linux-x64',
|
||||
);
|
||||
});
|
||||
|
||||
it('forwards pid and handle to unloadModuleManual', async () => {
|
||||
|
||||
@@ -13,8 +13,12 @@ function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<num
|
||||
});
|
||||
return {
|
||||
watcher,
|
||||
setProcesses: (p: HookProcessBaseInfo[]) => { processes = p; },
|
||||
setLive: (s: Set<number>) => { live = s; },
|
||||
setProcesses: (p: HookProcessBaseInfo[]) => {
|
||||
processes = p;
|
||||
},
|
||||
setLive: (s: Set<number>) => {
|
||||
live = s;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,10 +26,12 @@ type EventRow = [string, unknown];
|
||||
|
||||
function captureEvents(watcher: PipeWatcher): EventRow[] {
|
||||
const events: EventRow[] = [];
|
||||
watcher.on('process-discovered', info => events.push(['discovered', (info as HookProcessBaseInfo).pid]));
|
||||
watcher.on('process-gone', pid => events.push(['gone', pid]));
|
||||
watcher.on('pipe-up', pid => events.push(['up', pid]));
|
||||
watcher.on('pipe-down', pid => events.push(['down', pid]));
|
||||
watcher.on('process-discovered', (info) =>
|
||||
events.push(['discovered', (info as HookProcessBaseInfo).pid]),
|
||||
);
|
||||
watcher.on('process-gone', (pid) => events.push(['gone', pid]));
|
||||
watcher.on('pipe-up', (pid) => events.push(['up', pid]));
|
||||
watcher.on('pipe-down', (pid) => events.push(['down', pid]));
|
||||
return events;
|
||||
}
|
||||
|
||||
@@ -38,7 +44,7 @@ describe('PipeWatcher', () => {
|
||||
let observed: readonly HookProcessBaseInfo[] | undefined;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
listLivePipes: async current => {
|
||||
listLivePipes: async (current) => {
|
||||
observed = current;
|
||||
return new Set();
|
||||
},
|
||||
@@ -131,11 +137,18 @@ describe('PipeWatcher', () => {
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234], ['down', 1234]]);
|
||||
expect(events).toEqual([
|
||||
['up', 1234],
|
||||
['down', 1234],
|
||||
]);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234], ['down', 1234], ['up', 1234]]);
|
||||
expect(events).toEqual([
|
||||
['up', 1234],
|
||||
['down', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
@@ -158,7 +171,9 @@ describe('PipeWatcher', () => {
|
||||
it('emits "tick" after every poll', async () => {
|
||||
const ctx = setupWatcher({ processes: [], live: new Set() });
|
||||
let ticks = 0;
|
||||
ctx.watcher.on('tick', () => { ticks++; });
|
||||
ctx.watcher.on('tick', () => {
|
||||
ticks++;
|
||||
});
|
||||
|
||||
await ctx.watcher.start();
|
||||
expect(ticks).toBe(1);
|
||||
@@ -179,7 +194,7 @@ describe('PipeWatcher', () => {
|
||||
|
||||
// Wait on 'tick' rather than guessing how many event-loop turns
|
||||
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
|
||||
const nextTick = new Promise<void>(resolve => ctx.watcher.once('tick', () => resolve()));
|
||||
const nextTick = new Promise<void>((resolve) => ctx.watcher.once('tick', () => resolve()));
|
||||
ctx.setLive(new Set([1234]));
|
||||
ctx.watcher.wake();
|
||||
await nextTick;
|
||||
@@ -194,7 +209,10 @@ describe('PipeWatcher', () => {
|
||||
let shouldThrow = true;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => {
|
||||
if (shouldThrow) throw new Error('boom');
|
||||
if (shouldThrow) {
|
||||
throw new Error('boom');
|
||||
}
|
||||
|
||||
return processes;
|
||||
},
|
||||
listLivePipes: async () => new Set(live),
|
||||
@@ -210,7 +228,10 @@ describe('PipeWatcher', () => {
|
||||
const events = captureEvents(watcher);
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
|
||||
expect(events).toEqual([
|
||||
['discovered', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
@@ -220,7 +241,10 @@ describe('PipeWatcher', () => {
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
listLivePipes: async () => {
|
||||
if (failPipeDiscovery) throw new Error('permission denied');
|
||||
if (failPipeDiscovery) {
|
||||
throw new Error('permission denied');
|
||||
}
|
||||
|
||||
return new Set([1234]);
|
||||
},
|
||||
intervalMs: 60_000,
|
||||
@@ -240,7 +264,10 @@ describe('PipeWatcher', () => {
|
||||
processes = [];
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
expect(watcher.isPipeLive(1234)).toBe(false);
|
||||
watcher.stop();
|
||||
@@ -278,7 +305,10 @@ describe('PipeWatcher', () => {
|
||||
result = [];
|
||||
live = new Set();
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
watcher.stop();
|
||||
});
|
||||
});
|
||||
@@ -19,7 +19,9 @@ describe('createNativeProcessEnumerator', () => {
|
||||
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => { throw new Error('boom'); },
|
||||
fallbackSync: () => {
|
||||
throw new Error('boom');
|
||||
},
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toBeNull();
|
||||
|
||||
@@ -87,7 +87,9 @@ function mockControlPipe(
|
||||
): ReturnType<typeof vi.spyOn> {
|
||||
return vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
const socket = new Duplex({
|
||||
read() { /* peer data is injected with emit('data') */ },
|
||||
read() {
|
||||
/* peer data is injected with emit('data') */
|
||||
},
|
||||
write(chunk, _encoding, callback) {
|
||||
onWrite(socket, Buffer.from(chunk));
|
||||
callback();
|
||||
@@ -95,10 +97,15 @@ function mockControlPipe(
|
||||
}) as net.Socket;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('connect');
|
||||
queueMicrotask(() => socket.emit('data', pipeFrame({
|
||||
queueMicrotask(() =>
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.hello,
|
||||
value0: BigInt(pid),
|
||||
})));
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
return socket;
|
||||
}) as typeof net.createConnection);
|
||||
@@ -111,15 +118,17 @@ function traceMessages(entries: LogEntry[]): string[] {
|
||||
}
|
||||
|
||||
function runtimeTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter(
|
||||
(entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime',
|
||||
);
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime');
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
setLogLevel(previousLogLevel);
|
||||
vi.restoreAllMocks();
|
||||
if (!tmpDir) return;
|
||||
|
||||
if (!tmpDir) {
|
||||
return;
|
||||
}
|
||||
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
tmpDir = null;
|
||||
});
|
||||
@@ -142,7 +151,9 @@ describe('listLiveLinuxPipePids', () => {
|
||||
await writeFile(path.join(runtimeDir, 'mojo.56.recv.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.not-a-pid.control.sock'), '');
|
||||
|
||||
const probe = vi.fn(async (socketPath: string) => socketPath.endsWith('mojo.56.control.sock'));
|
||||
const probe = vi.fn(async (socketPath: string) =>
|
||||
socketPath.endsWith('mojo.56.control.sock'),
|
||||
);
|
||||
const pids = await listLiveLinuxPipePids(runtimeDir, probe);
|
||||
|
||||
expect([...pids]).toEqual([56]);
|
||||
@@ -157,12 +168,18 @@ describe('QqHookClient — pipe frame limits', () => {
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
writes.push(Buffer.from(payload));
|
||||
const requestId = payload.readUInt32LE(8);
|
||||
queueMicrotask(() => socket.emit('data', pipeFrame({
|
||||
queueMicrotask(() =>
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.sendAck,
|
||||
requestId,
|
||||
})));
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
await client.reconcileLoginIdentity('10001');
|
||||
|
||||
@@ -190,7 +207,11 @@ describe('QqHookClient — pipe frame limits', () => {
|
||||
const pid = 778830;
|
||||
let socket: net.Socket | null = null;
|
||||
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
|
||||
socket = new Duplex({
|
||||
read() {
|
||||
/* peer data is injected with emit('data') */
|
||||
},
|
||||
}) as net.Socket;
|
||||
queueMicrotask(() => {
|
||||
socket!.emit('connect');
|
||||
const header = Buffer.alloc(HEADER_SIZE);
|
||||
@@ -204,6 +225,7 @@ describe('QqHookClient — pipe frame limits', () => {
|
||||
}) as typeof net.createConnection);
|
||||
const client = new QqHookClient(pid);
|
||||
const connecting = client.connect().catch(() => undefined);
|
||||
|
||||
try {
|
||||
const error = await new Promise<Error>((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
@@ -225,19 +247,23 @@ describe('QqHookClient — pipe frame limits', () => {
|
||||
await connecting;
|
||||
createConnection.mockRestore();
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects an oversized outbound command before writing to the pipe', async () => {
|
||||
const pid = 778831;
|
||||
const onWrite = vi.fn();
|
||||
const connection = mockControlPipe(pid, onWrite);
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
|
||||
await expect(client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES + 1), Buffer.alloc(0), {
|
||||
await expect(
|
||||
client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES + 1), Buffer.alloc(0), {
|
||||
ackTimeoutMs: 25,
|
||||
})).rejects.toThrow(
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
`pipe frame command length ${MAX_PIPE_CMD_BYTES + 1} exceeds limit ${MAX_PIPE_CMD_BYTES}`,
|
||||
);
|
||||
expect(onWrite).not.toHaveBeenCalled();
|
||||
@@ -252,13 +278,13 @@ describe('QqHookClient — pipe frame limits', () => {
|
||||
const onWrite = vi.fn();
|
||||
const connection = mockControlPipe(pid, onWrite);
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
|
||||
await expect(client.sendNoReply(
|
||||
'test.command',
|
||||
Buffer.alloc(MAX_PIPE_BODY_BYTES + 1),
|
||||
)).rejects.toThrow(
|
||||
await expect(
|
||||
client.sendNoReply('test.command', Buffer.alloc(MAX_PIPE_BODY_BYTES + 1)),
|
||||
).rejects.toThrow(
|
||||
`pipe frame body length ${MAX_PIPE_BODY_BYTES + 1} exceeds limit ${MAX_PIPE_BODY_BYTES}`,
|
||||
);
|
||||
expect(onWrite).not.toHaveBeenCalled();
|
||||
@@ -272,15 +298,22 @@ describe('QqHookClient — pipe frame limits', () => {
|
||||
const pid = 778833;
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
const requestId = payload.readUInt32LE(8);
|
||||
queueMicrotask(() => socket.emit('data', pipeFrame({
|
||||
queueMicrotask(() =>
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.sendAck,
|
||||
requestId,
|
||||
})));
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
await expect(client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES), Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ requestId: 1 });
|
||||
await expect(
|
||||
client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES), Buffer.alloc(0)),
|
||||
).resolves.toMatchObject({ requestId: 1 });
|
||||
} finally {
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
@@ -296,14 +329,22 @@ describe('QqHookClient — pipe frame limits', () => {
|
||||
pipeFrame({ op: PipeOp.loginState, status: 1, value0: 10002n, message: '10002' }),
|
||||
]);
|
||||
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
const socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
|
||||
const socket = new Duplex({
|
||||
read() {
|
||||
/* peer data is injected with emit('data') */
|
||||
},
|
||||
}) as net.Socket;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('connect');
|
||||
queueMicrotask(() => {
|
||||
const cuts = [1, 7, 39, 40, 44, 83, wire.length - 1, wire.length];
|
||||
let offset = 0;
|
||||
|
||||
for (const end of cuts) {
|
||||
if (end > offset) socket.emit('data', wire.subarray(offset, end));
|
||||
if (end > offset) {
|
||||
socket.emit('data', wire.subarray(offset, end));
|
||||
}
|
||||
|
||||
offset = end;
|
||||
}
|
||||
});
|
||||
@@ -311,7 +352,8 @@ describe('QqHookClient — pipe frame limits', () => {
|
||||
return socket;
|
||||
}) as typeof net.createConnection);
|
||||
const client = new QqHookClient(pid);
|
||||
client.on('loginState', state => states.push(state.uin));
|
||||
client.on('loginState', (state) => states.push(state.uin));
|
||||
|
||||
try {
|
||||
const hello = await client.connect();
|
||||
|
||||
@@ -328,7 +370,11 @@ describe('QqHookClient — pipe frame limits', () => {
|
||||
const message = 'x'.repeat(MAX_PIPE_MSG_BYTES);
|
||||
const frame = pipeFrame({ op: PipeOp.hello, value0: BigInt(pid), message });
|
||||
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
const socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
|
||||
const socket = new Duplex({
|
||||
read() {
|
||||
/* peer data is injected with emit('data') */
|
||||
},
|
||||
}) as net.Socket;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('connect');
|
||||
queueMicrotask(() => {
|
||||
@@ -340,6 +386,7 @@ describe('QqHookClient — pipe frame limits', () => {
|
||||
return socket;
|
||||
}) as typeof net.createConnection);
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
await expect(client.connect()).resolves.toMatchObject({ pipeName: message, pid });
|
||||
} finally {
|
||||
@@ -360,19 +407,27 @@ describe('QqHookClient — runtime TRACE', () => {
|
||||
const kind = connectionIndex === 0 ? 'control' : 'recv';
|
||||
connectionIndex += 1;
|
||||
const socket = new Duplex({
|
||||
read() { /* peer data is injected with emit('data') */ },
|
||||
read() {
|
||||
/* peer data is injected with emit('data') */
|
||||
},
|
||||
}) as net.Socket;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('connect');
|
||||
queueMicrotask(() => socket.emit('data', pipeFrame({
|
||||
queueMicrotask(() =>
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.hello,
|
||||
value0: BigInt(pid),
|
||||
message: `${kind}-fixture`,
|
||||
})));
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
return socket;
|
||||
}) as typeof net.createConnection);
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
await runWithRequestId(4201, () => client.connectAll());
|
||||
|
||||
@@ -381,11 +436,19 @@ describe('QqHookClient — runtime TRACE', () => {
|
||||
expect(trace.every((entry) => entry.req === 4201)).toBe(true);
|
||||
expect(trace.map((entry) => entry.message)).toEqual([
|
||||
expect.stringMatching(/^hook_pipe_start pid=778820 kind=control pipeName=.*$/),
|
||||
expect.stringMatching(/^hook_pipe_branch pid=778820 kind=control branch=socket_connected$/),
|
||||
expect.stringMatching(/^hook_pipe_terminal pid=778820 kind=control outcome=completed reason=hello_received hello=\{pipeName:"control-fixture",pid:778820,recvPipe:false\} elapsedMs=\d+$/),
|
||||
expect.stringMatching(
|
||||
/^hook_pipe_branch pid=778820 kind=control branch=socket_connected$/,
|
||||
),
|
||||
expect.stringMatching(
|
||||
/^hook_pipe_terminal pid=778820 kind=control outcome=completed reason=hello_received hello=\{pipeName:"control-fixture",pid:778820,recvPipe:false\} elapsedMs=\d+$/,
|
||||
),
|
||||
expect.stringMatching(/^hook_pipe_start pid=778820 kind=recv pipeName=.*$/),
|
||||
expect.stringMatching(/^hook_pipe_branch pid=778820 kind=recv branch=socket_connected$/),
|
||||
expect.stringMatching(/^hook_pipe_terminal pid=778820 kind=recv outcome=completed reason=hello_received hello=\{pipeName:"recv-fixture",pid:778820,recvPipe:true\} elapsedMs=\d+$/),
|
||||
expect.stringMatching(
|
||||
/^hook_pipe_branch pid=778820 kind=recv branch=socket_connected$/,
|
||||
),
|
||||
expect.stringMatching(
|
||||
/^hook_pipe_terminal pid=778820 kind=recv outcome=completed reason=hello_received hello=\{pipeName:"recv-fixture",pid:778820,recvPipe:true\} elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
@@ -400,11 +463,16 @@ describe('QqHookClient — runtime TRACE', () => {
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
const socket = new Duplex({ read() { /* no peer */ } }) as net.Socket;
|
||||
const socket = new Duplex({
|
||||
read() {
|
||||
/* no peer */
|
||||
},
|
||||
}) as net.Socket;
|
||||
queueMicrotask(() => socket.emit('error', new Error('fixture connect failure')));
|
||||
return socket;
|
||||
}) as typeof net.createConnection);
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
await expect(client.connect()).rejects.toThrow('fixture connect failure');
|
||||
|
||||
@@ -414,7 +482,9 @@ describe('QqHookClient — runtime TRACE', () => {
|
||||
expect(trace[0]!.req).toBe(trace[1]!.req);
|
||||
expect(trace.map((entry) => entry.message)).toEqual([
|
||||
expect.stringMatching(/^hook_pipe_start pid=778821 kind=control pipeName=.*$/),
|
||||
expect.stringMatching(/^hook_pipe_terminal pid=778821 kind=control outcome=failed reason=connect_failed error="fixture connect failure" elapsedMs=\d+$/),
|
||||
expect.stringMatching(
|
||||
/^hook_pipe_terminal pid=778821 kind=control outcome=failed reason=connect_failed error="fixture connect failure" elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(trace.map((entry) => entry.message).join('\n')).not.toContain('requestId=');
|
||||
} finally {
|
||||
@@ -429,7 +499,9 @@ describe('QqHookClient — runtime TRACE', () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const connection = mockControlPipe(pid, () => { /* no packet writes */ });
|
||||
const connection = mockControlPipe(pid, () => {
|
||||
/* no packet writes */
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
const eventRequestIds: Array<{ event: 'login' | 'close'; req: number | undefined }> = [];
|
||||
client.on('loginState', () => {
|
||||
@@ -438,26 +510,33 @@ describe('QqHookClient — runtime TRACE', () => {
|
||||
client.on('close', () => {
|
||||
eventRequestIds.push({ event: 'close', req: currentRequestId() });
|
||||
});
|
||||
|
||||
try {
|
||||
await runWithRequestId(4202, () => client.connect());
|
||||
const controlSocket = connection.mock.results[0]!.value as net.Socket;
|
||||
controlSocket.emit('data', pipeFrame({
|
||||
controlSocket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.loginState,
|
||||
status: 1,
|
||||
value0: 123456n,
|
||||
message: '123456',
|
||||
}));
|
||||
controlSocket.emit('data', pipeFrame({
|
||||
}),
|
||||
);
|
||||
controlSocket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.loginState,
|
||||
status: 1,
|
||||
value0: 123456n,
|
||||
message: '123456',
|
||||
}));
|
||||
}),
|
||||
);
|
||||
controlSocket.destroy();
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
const facts = runtimeTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_runtime_fact pid=778822 '),
|
||||
const facts = runtimeTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_runtime_fact pid=778822 '),
|
||||
);
|
||||
expect(facts).toHaveLength(2);
|
||||
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
|
||||
@@ -483,7 +562,9 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
it('records complete request and reply bodies with the real pipe request id', async () => {
|
||||
const pid = 778810;
|
||||
const requestBody = Buffer.from([
|
||||
0x00, 0xff, ...Array.from({ length: 160 }, (_, index) => index & 0xff),
|
||||
0x00,
|
||||
0xff,
|
||||
...Array.from({ length: 160 }, (_, index) => index & 0xff),
|
||||
]);
|
||||
const replyBody = Buffer.from([0xff, 0x00, 0x7f]);
|
||||
const entries: LogEntry[] = [];
|
||||
@@ -497,20 +578,23 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
traceCountAtWrite = traceMessages(entries).length;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId: frame.requestId }));
|
||||
socket.emit('data', pipeFrame({
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.sendReply,
|
||||
requestId: frame.requestId,
|
||||
status: 27,
|
||||
message: 'fixture reply',
|
||||
body: replyBody,
|
||||
}));
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
const reply = await runWithRequestId(
|
||||
4101,
|
||||
() => client.sendAndWait('OidbSvcTrpcTcp.0x1234_1', requestBody),
|
||||
const reply = await runWithRequestId(4101, () =>
|
||||
client.sendAndWait('OidbSvcTrpcTcp.0x1234_1', requestBody),
|
||||
);
|
||||
|
||||
const sent = readSendFrame(writes[0]);
|
||||
@@ -526,8 +610,8 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
body: replyBody,
|
||||
});
|
||||
expect(traceCountAtWrite).toBe(1);
|
||||
expect(entries.filter((entry) => entry.scope === 'QQHook.Packet'))
|
||||
.toEqual(expect.arrayContaining([
|
||||
expect(entries.filter((entry) => entry.scope === 'QQHook.Packet')).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
req: 4101,
|
||||
message: `packet_send serviceCmd="OidbSvcTrpcTcp.0x1234_1" requestId=1 length=${requestBody.length} body=${requestBody.toString('hex')}`,
|
||||
@@ -538,10 +622,16 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
}),
|
||||
expect.objectContaining({
|
||||
req: 4101,
|
||||
message: expect.stringMatching(/^packet_terminal serviceCmd="OidbSvcTrpcTcp\.0x1234_1" requestId=1 outcome=failed reason=reply_error error=27 elapsedMs=\d+$/),
|
||||
message: expect.stringMatching(
|
||||
/^packet_terminal serviceCmd="OidbSvcTrpcTcp\.0x1234_1" requestId=1 outcome=failed reason=reply_error error=27 elapsedMs=\d+$/,
|
||||
),
|
||||
}),
|
||||
]));
|
||||
for (const message of traceMessages(entries)) expect(message).not.toContain('...');
|
||||
]),
|
||||
);
|
||||
|
||||
for (const message of traceMessages(entries)) {
|
||||
expect(message).not.toContain('...');
|
||||
}
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
@@ -562,13 +652,16 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
});
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
await client.sendAndWait('Empty.Command', Buffer.alloc(0));
|
||||
|
||||
expect(traceMessages(entries)).toEqual([
|
||||
'packet_send serviceCmd="Empty.Command" requestId=1 length=0 body=',
|
||||
'packet_recv serviceCmd="Empty.Command" requestId=1 error=0 message="" length=0 body=',
|
||||
expect.stringMatching(/^packet_terminal serviceCmd="Empty\.Command" requestId=1 outcome=ok reason=reply_received error=0 elapsedMs=\d+$/),
|
||||
expect.stringMatching(
|
||||
/^packet_terminal serviceCmd="Empty\.Command" requestId=1 outcome=ok reason=reply_received error=0 elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
@@ -589,12 +682,15 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
});
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
await client.sendNoReply('NoReply.Command', Buffer.from([0x00, 0xff]));
|
||||
|
||||
expect(traceMessages(entries)).toEqual([
|
||||
'packet_send serviceCmd="NoReply.Command" requestId=1 length=2 body=00ff',
|
||||
expect.stringMatching(/^packet_terminal serviceCmd="NoReply\.Command" requestId=1 outcome=ok reason=ack_received elapsedMs=\d+$/),
|
||||
expect.stringMatching(
|
||||
/^packet_terminal serviceCmd="NoReply\.Command" requestId=1 outcome=ok reason=ack_received elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
@@ -613,16 +709,21 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
const { requestId } = readSendFrame(payload);
|
||||
writeCount += 1;
|
||||
|
||||
if (writeCount === 1) {
|
||||
queueMicrotask(() => {
|
||||
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
queueMicrotask(() => socket.destroy());
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
client.on('error', () => { /* expected transport failure */ });
|
||||
client.on('error', () => {
|
||||
/* expected transport failure */
|
||||
});
|
||||
|
||||
try {
|
||||
const timedOut = client.sendAndWait('Timeout.Command', Buffer.from([0xff]), {
|
||||
ackTimeoutMs: 50,
|
||||
@@ -643,10 +744,16 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
});
|
||||
await expect(failed).rejects.toThrow('control pipe closed');
|
||||
|
||||
expect(traceMessages(entries)).toEqual(expect.arrayContaining([
|
||||
expect.stringMatching(/^packet_terminal serviceCmd="Timeout\.Command" requestId=1 outcome=timeout reason=reply_timeout error="send reply 1 timed out after 50 ms" elapsedMs=\d+$/),
|
||||
expect.stringMatching(/^packet_terminal serviceCmd="Closed\.Command" requestId=2 outcome=failed reason=transport_failure error="control pipe closed" elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(traceMessages(entries)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringMatching(
|
||||
/^packet_terminal serviceCmd="Timeout\.Command" requestId=1 outcome=timeout reason=reply_timeout error="send reply 1 timed out after 50 ms" elapsedMs=\d+$/,
|
||||
),
|
||||
expect.stringMatching(
|
||||
/^packet_terminal serviceCmd="Closed\.Command" requestId=2 outcome=failed reason=transport_failure error="control pipe closed" elapsedMs=\d+$/,
|
||||
),
|
||||
]),
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
@@ -665,16 +772,23 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
const { requestId } = readSendFrame(payload);
|
||||
writeCount += 1;
|
||||
|
||||
if (writeCount === 2) {
|
||||
queueMicrotask(() => socket.emit('data', pipeFrame({
|
||||
queueMicrotask(() =>
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.error,
|
||||
requestId,
|
||||
status: 12,
|
||||
message: 'send ack 2 timed out after 25 ms',
|
||||
})));
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
const timedOut = client.sendNoReply('Ack.Timeout', Buffer.from([0x00]), {
|
||||
ackTimeoutMs: 25,
|
||||
@@ -688,10 +802,7 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
message: 'send ack 1 timed out after 25 ms',
|
||||
});
|
||||
|
||||
const requestError = await client.sendAndWait(
|
||||
'Pipe.Error',
|
||||
Buffer.from([0xff]),
|
||||
).then(
|
||||
const requestError = await client.sendAndWait('Pipe.Error', Buffer.from([0xff])).then(
|
||||
() => null,
|
||||
(error: unknown) => error,
|
||||
);
|
||||
@@ -702,10 +813,16 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
requestId: 2,
|
||||
});
|
||||
|
||||
expect(traceMessages(entries)).toEqual(expect.arrayContaining([
|
||||
expect.stringMatching(/^packet_terminal serviceCmd="Ack\.Timeout" requestId=1 outcome=timeout reason=ack_timeout error="send ack 1 timed out after 25 ms" elapsedMs=\d+$/),
|
||||
expect.stringMatching(/^packet_terminal serviceCmd="Pipe\.Error" requestId=2 outcome=failed reason=request_failed error="send ack 2 timed out after 25 ms" elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(traceMessages(entries)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringMatching(
|
||||
/^packet_terminal serviceCmd="Ack\.Timeout" requestId=1 outcome=timeout reason=ack_timeout error="send ack 1 timed out after 25 ms" elapsedMs=\d+$/,
|
||||
),
|
||||
expect.stringMatching(
|
||||
/^packet_terminal serviceCmd="Pipe\.Error" requestId=2 outcome=failed reason=request_failed error="send ack 2 timed out after 25 ms" elapsedMs=\d+$/,
|
||||
),
|
||||
]),
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
@@ -722,26 +839,35 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
writes.push(readSendFrame(payload));
|
||||
if (writes.length !== 2) return;
|
||||
|
||||
if (writes.length !== 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
queueMicrotask(() => {
|
||||
for (const frame of [...writes].reverse()) {
|
||||
socket.emit('data', pipeFrame({
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.sendAck,
|
||||
requestId: frame.requestId,
|
||||
}));
|
||||
socket.emit('data', pipeFrame({
|
||||
}),
|
||||
);
|
||||
socket.emit(
|
||||
'data',
|
||||
pipeFrame({
|
||||
op: PipeOp.sendReply,
|
||||
requestId: frame.requestId,
|
||||
body: Buffer.from(frame.body).reverse(),
|
||||
}));
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
const firstBody = Buffer.from([0x00, 0xff]);
|
||||
const secondBody = Buffer.from(
|
||||
Array.from({ length: 160 }, (_, index) => index & 0xff),
|
||||
);
|
||||
const secondBody = Buffer.from(Array.from({ length: 160 }, (_, index) => index & 0xff));
|
||||
|
||||
try {
|
||||
const [first, second] = await Promise.all([
|
||||
client.sendAndWait('First\nCommand', firstBody),
|
||||
@@ -753,13 +879,17 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
const messages = traceMessages(entries);
|
||||
expect(messages).toHaveLength(6);
|
||||
expect(messages.every((message) => !message.includes('\n'))).toBe(true);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect(messages).toEqual(
|
||||
expect.arrayContaining([
|
||||
`packet_send serviceCmd="First\\nCommand" requestId=1 length=2 body=${firstBody.toString('hex')}`,
|
||||
`packet_recv serviceCmd="First\\nCommand" requestId=1 error=0 message="" length=2 body=${Buffer.from(firstBody).reverse().toString('hex')}`,
|
||||
`packet_send serviceCmd="Second.Command" requestId=2 length=${secondBody.length} body=${secondBody.toString('hex')}`,
|
||||
`packet_recv serviceCmd="Second.Command" requestId=2 error=0 message="" length=${secondBody.length} body=${Buffer.from(secondBody).reverse().toString('hex')}`,
|
||||
]));
|
||||
expect(messages.filter((message) => message.startsWith('packet_terminal'))).toHaveLength(2);
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
messages.filter((message) => message.startsWith('packet_terminal')),
|
||||
).toHaveLength(2);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
@@ -779,6 +909,7 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
});
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
|
||||
try {
|
||||
await client.sendAndWait('Disabled.Command', Buffer.from([0x00, 0xff]));
|
||||
|
||||
@@ -802,6 +933,7 @@ describe('QqHookClient — pipe close mid-send', () => {
|
||||
// unhandledRejection assertion below.
|
||||
it('does not raise an unhandled rejection', async () => {
|
||||
const PID = 778899;
|
||||
|
||||
const helloFrame = (): Buffer => {
|
||||
const h = Buffer.alloc(40);
|
||||
h.writeUInt32LE(0x31504851, 0); // PIPE_MAGIC
|
||||
@@ -813,10 +945,14 @@ describe('QqHookClient — pipe close mid-send', () => {
|
||||
|
||||
let controlConn: net.Socket | null = null;
|
||||
let signalControlWrite!: () => void;
|
||||
const controlWriteStarted = new Promise<void>((resolve) => { signalControlWrite = resolve; });
|
||||
const controlWriteStarted = new Promise<void>((resolve) => {
|
||||
signalControlWrite = resolve;
|
||||
});
|
||||
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
const socket = new Duplex({
|
||||
read() { /* peer data is injected with emit('data') */ },
|
||||
read() {
|
||||
/* peer data is injected with emit('data') */
|
||||
},
|
||||
write(_chunk, _encoding, callback) {
|
||||
signalControlWrite();
|
||||
callback();
|
||||
@@ -831,18 +967,29 @@ describe('QqHookClient — pipe close mid-send', () => {
|
||||
}) as typeof net.createConnection);
|
||||
|
||||
const unhandled: unknown[] = [];
|
||||
const onUnhandled = (reason: unknown): void => { unhandled.push(reason); };
|
||||
|
||||
const onUnhandled = (reason: unknown): void => {
|
||||
unhandled.push(reason);
|
||||
};
|
||||
|
||||
process.on('unhandledRejection', onUnhandled);
|
||||
|
||||
const client = new QqHookClient(PID);
|
||||
client.on('error', () => { /* socket reset on destroy — ignore */ });
|
||||
client.on('error', () => {
|
||||
/* socket reset on destroy — ignore */
|
||||
});
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
|
||||
// Start a reply-expecting send, let it reach the in-flight (awaiting-ack)
|
||||
// state, then have the "hook" drop the pipe before it answers.
|
||||
const sent = client.send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 })
|
||||
.then(() => 'resolved' as const, (e: unknown) => e);
|
||||
const sent = client
|
||||
.send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 })
|
||||
.then(
|
||||
() => 'resolved' as const,
|
||||
(e: unknown) => e,
|
||||
);
|
||||
await controlWriteStarted;
|
||||
controlConn?.destroy();
|
||||
|
||||
@@ -851,7 +998,10 @@ describe('QqHookClient — pipe close mid-send', () => {
|
||||
|
||||
expect(outcome).toBeInstanceOf(Error);
|
||||
expect((outcome as Error).message).toBe('control pipe closed');
|
||||
expect(unhandled, `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`).toHaveLength(0);
|
||||
expect(
|
||||
unhandled,
|
||||
`unhandled rejections leaked: ${unhandled.map(String).join(', ')}`,
|
||||
).toHaveLength(0);
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled);
|
||||
client.close();
|
||||
|
||||
@@ -36,14 +36,17 @@ function setPlatform(platform: string): void {
|
||||
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: '' });
|
||||
});
|
||||
}
|
||||
@@ -72,12 +75,20 @@ function requestStub(): RequestLike {
|
||||
}
|
||||
|
||||
function replyBody(body: string | ReadonlyArray<string | Buffer>) {
|
||||
return (_url: string, _options: unknown, onResponse: (res: EventEmitter) => void): RequestLike => {
|
||||
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);
|
||||
|
||||
for (const chunk of chunks) {
|
||||
res.emit('data', chunk);
|
||||
}
|
||||
|
||||
res.emit('end');
|
||||
return req;
|
||||
};
|
||||
@@ -180,10 +191,7 @@ describe('probeQqLoginInfo — unix listing', () => {
|
||||
|
||||
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'),
|
||||
'ss -tlnp': [ssLine(9218, 4410), ssLine(18000, 4410)].join('\n'),
|
||||
'pgrep -c qq': ' 4 \n',
|
||||
});
|
||||
|
||||
@@ -236,12 +244,18 @@ describe('probeQqLoginInfo — unix listing', () => {
|
||||
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([{
|
||||
httpsGetMock.mockImplementation(
|
||||
replyBody(
|
||||
jsonp([
|
||||
{
|
||||
uin: 319427101,
|
||||
account: 1,
|
||||
nickname: 'Snow',
|
||||
extra: 'ignored',
|
||||
}])));
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
await expect(probeQqLoginInfo(5501)).resolves.toEqual({
|
||||
port: 4301,
|
||||
@@ -260,9 +274,15 @@ describe('probeQqLoginInfo — Ptlogin identity', () => {
|
||||
|
||||
it('reads a single account from an even Ptlogin port over http', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4302, 5502) });
|
||||
httpGetMock.mockImplementation(replyBody(jsonp([{
|
||||
httpGetMock.mockImplementation(
|
||||
replyBody(
|
||||
jsonp([
|
||||
{
|
||||
account: '2880036470',
|
||||
}])));
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
await expect(probeQqLoginInfo(5502)).resolves.toEqual({
|
||||
port: 4302,
|
||||
@@ -377,8 +397,12 @@ describe('probeQqLoginInfo — Ptlogin identity', () => {
|
||||
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' }])));
|
||||
.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,
|
||||
@@ -403,10 +427,14 @@ describe('probeQqLoginInfo — Ptlogin identity', () => {
|
||||
it('keeps the shorter of the two pt_get_uins snapshots', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5540) });
|
||||
httpsGetMock
|
||||
.mockImplementationOnce(replyBody(jsonp([
|
||||
.mockImplementationOnce(
|
||||
replyBody(
|
||||
jsonp([
|
||||
{ uin: '11', nickname: 'A' },
|
||||
{ uin: '22', nickname: 'B' },
|
||||
])))
|
||||
]),
|
||||
),
|
||||
)
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '33', nickname: 'Cora' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5540)).resolves.toEqual({
|
||||
@@ -455,10 +483,7 @@ describe('probeQqLoginInfo — Ptlogin identity', () => {
|
||||
|
||||
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' },
|
||||
])));
|
||||
httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '1' }, { uin: '2' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5551)).resolves.toBeNull();
|
||||
});
|
||||
@@ -495,11 +520,13 @@ describe('probeQqLoginInfo — Ptlogin identity', () => {
|
||||
|
||||
it('joins chunked pt_get_uins bodies including Buffer pieces', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5560) });
|
||||
httpsGetMock.mockImplementation(replyBody([
|
||||
httpsGetMock.mockImplementation(
|
||||
replyBody([
|
||||
'ptui_getuins_CB([',
|
||||
Buffer.from('{"uin":"10001","nickname":"Ada"}'),
|
||||
']);',
|
||||
]));
|
||||
]),
|
||||
);
|
||||
|
||||
await expect(probeQqLoginInfo(5560)).resolves.toEqual({
|
||||
port: 4301,
|
||||
@@ -511,7 +538,9 @@ describe('probeQqLoginInfo — Ptlogin identity', () => {
|
||||
|
||||
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"}]);'));
|
||||
httpsGetMock.mockImplementation(
|
||||
replyBody('ptui_getuins_CB([{"nickname":"a]b","uin":"1"}]);'),
|
||||
);
|
||||
|
||||
await expect(probeQqLoginInfo(5561)).resolves.toBeNull();
|
||||
});
|
||||
@@ -550,10 +579,7 @@ describe('probeQqLoginInfo — win32 listing', () => {
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
expect(execCommands()).toEqual([
|
||||
'netstat -ano',
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh',
|
||||
]);
|
||||
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 () => {
|
||||
@@ -667,7 +693,9 @@ describe('probeQqLoginInfo — overall deadline', () => {
|
||||
setLogLevel('info');
|
||||
const warnings: string[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => {
|
||||
if (entry.scope === 'LoginProbe') warnings.push(entry.message);
|
||||
if (entry.scope === 'LoginProbe') {
|
||||
warnings.push(entry.message);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const execMock = vi.hoisted(() => vi.fn());
|
||||
const socketCtorMock = vi.hoisted(() => vi.fn(function MockSocket() {
|
||||
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', () => ({
|
||||
|
||||
@@ -5,11 +5,7 @@ import { translations } from '@zxcvbn-ts/language-en';
|
||||
export const ACCESS_TOKEN_MIN_LENGTH = 16;
|
||||
export const ACCESS_TOKEN_MIN_SCORE = 3;
|
||||
|
||||
export type AccessTokenAssessmentReason =
|
||||
| 'empty'
|
||||
| 'too-short'
|
||||
| 'guessable'
|
||||
| 'acceptable';
|
||||
export type AccessTokenAssessmentReason = 'empty' | 'too-short' | 'guessable' | 'acceptable';
|
||||
|
||||
export interface AccessTokenAssessment {
|
||||
acceptable: boolean;
|
||||
@@ -25,14 +21,23 @@ const checker = new ZxcvbnFactory({
|
||||
|
||||
function normalizeUserInputs(values: readonly (string | number)[]): Array<string | number> {
|
||||
const unique = new Set<string | number>(['SnowLuma', 'OneBot']);
|
||||
|
||||
for (const value of values) {
|
||||
if (typeof value === 'number') {
|
||||
if (Number.isFinite(value)) unique.add(value);
|
||||
if (Number.isFinite(value)) {
|
||||
unique.add(value);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
const trimmed = value.trim();
|
||||
if (trimmed) unique.add(trimmed.slice(0, 256));
|
||||
|
||||
if (trimmed) {
|
||||
unique.add(trimmed.slice(0, 256));
|
||||
}
|
||||
}
|
||||
|
||||
return [...unique].slice(0, 24);
|
||||
}
|
||||
|
||||
@@ -45,14 +50,19 @@ export function assessAccessToken(
|
||||
token: string,
|
||||
userInputs: readonly (string | number)[] = [],
|
||||
): AccessTokenAssessment {
|
||||
if (!token) return { acceptable: false, reason: 'empty', score: 0 };
|
||||
if (!token) {
|
||||
return { acceptable: false, reason: 'empty', score: 0 };
|
||||
}
|
||||
|
||||
if (token.length < ACCESS_TOKEN_MIN_LENGTH) {
|
||||
return { acceptable: false, reason: 'too-short', score: 0 };
|
||||
}
|
||||
|
||||
const score = checker.check(token, normalizeUserInputs(userInputs)).score;
|
||||
|
||||
if (score < ACCESS_TOKEN_MIN_SCORE) {
|
||||
return { acceptable: false, reason: 'guessable', score };
|
||||
}
|
||||
|
||||
return { acceptable: true, reason: 'acceptable', score };
|
||||
}
|
||||
@@ -20,7 +20,11 @@ export function boolOr(value: unknown, fallback: boolean): boolean {
|
||||
* the fallback. Fractional precision is preserved — use `clampInt` to floor. */
|
||||
export function clampNum(value: unknown, min: number, max: number, fallback: number): number {
|
||||
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
|
||||
if (!Number.isFinite(n)) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return Math.min(max, Math.max(min, n));
|
||||
}
|
||||
|
||||
|
||||
@@ -18,10 +18,15 @@ export async function mapWithConcurrency<T, R>(
|
||||
): Promise<R[]> {
|
||||
const limit = Math.max(1, Math.trunc(concurrency));
|
||||
const results = new Array<R>(items.length);
|
||||
|
||||
for (let i = 0; i < items.length; i += limit) {
|
||||
const batch = items.slice(i, i + limit);
|
||||
const settled = await Promise.all(batch.map((item, j) => fn(item, i + j)));
|
||||
for (let j = 0; j < settled.length; j++) results[i + j] = settled[j]!;
|
||||
|
||||
for (let j = 0; j < settled.length; j++) {
|
||||
results[i + j] = settled[j]!;
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
@@ -17,12 +17,18 @@ export function positiveIntEnv(
|
||||
): number {
|
||||
const max = options?.max ?? MAX_POSITIVE_INT;
|
||||
const raw = (options?.env ?? process.env)[name];
|
||||
if (typeof raw !== 'string' || !raw.trim()) return fallback;
|
||||
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const value = raw.trim();
|
||||
const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN;
|
||||
|
||||
if (!Number.isSafeInteger(parsed) || parsed > max) {
|
||||
log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
@@ -3,19 +3,23 @@ const HEX_CHARS_UPPER = '0123456789ABCDEF';
|
||||
|
||||
export function toHex(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS[b >> 4];
|
||||
h += HEX_CHARS[b & 0xf];
|
||||
}
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
export function toHexUpper(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS_UPPER[b >> 4];
|
||||
h += HEX_CHARS_UPPER[b & 0xf];
|
||||
}
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
@@ -26,10 +30,15 @@ export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
|
||||
}
|
||||
|
||||
export function fromHex(hex: string): Buffer {
|
||||
if (hex.length % 2 !== 0) throw new Error('Invalid hex string length');
|
||||
if (hex.length % 2 !== 0) {
|
||||
throw new Error('Invalid hex string length');
|
||||
}
|
||||
|
||||
const buf = Buffer.alloc(hex.length / 2);
|
||||
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
|
||||
return buf;
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { sanitizeLogLine } from './log-sanitize';
|
||||
import {
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
} from './runtime';
|
||||
import { MAX_LOG_RETAIN_DAYS, MAX_LOG_TOTAL_MB } from './runtime';
|
||||
|
||||
const DEFAULT_DIR = 'logs';
|
||||
const DEFAULT_MAX_MB = 50;
|
||||
@@ -50,12 +47,20 @@ function parseNonNegativeInt(
|
||||
max: number,
|
||||
field?: string,
|
||||
): number {
|
||||
if (value === undefined || value.trim() === '') return fallback;
|
||||
if (value === undefined || value.trim() === '') {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const parsed = Number(value.trim());
|
||||
if (Number.isSafeInteger(parsed) && parsed >= 0 && parsed <= max) return parsed;
|
||||
|
||||
if (Number.isSafeInteger(parsed) && parsed >= 0 && parsed <= max) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
if (field) {
|
||||
throw new RangeError(`${field} must be an integer in 0..${String(max)}`);
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
@@ -65,21 +70,34 @@ function parseRequiredPositiveInt(
|
||||
max: number,
|
||||
field: string,
|
||||
): number {
|
||||
if (value === undefined || value.trim() === '') return fallback;
|
||||
if (value === undefined || value.trim() === '') {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const parsed = Number(value.trim());
|
||||
if (Number.isSafeInteger(parsed) && parsed > 0 && parsed <= max) return parsed;
|
||||
|
||||
if (Number.isSafeInteger(parsed) && parsed > 0 && parsed <= max) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
throw new RangeError(`${field} must be an integer in 1..${String(max)}`);
|
||||
}
|
||||
|
||||
function parseRequiredBool(
|
||||
value: string | undefined,
|
||||
fallback: boolean,
|
||||
field: string,
|
||||
): boolean {
|
||||
if (value === undefined || value.trim() === '') return fallback;
|
||||
function parseRequiredBool(value: string | undefined, fallback: boolean, field: string): boolean {
|
||||
if (value === undefined || value.trim() === '') {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (['1', 'true', 'yes', 'on'].includes(normalized)) return true;
|
||||
if (['0', 'false', 'no', 'off'].includes(normalized)) return false;
|
||||
|
||||
if (['1', 'true', 'yes', 'on'].includes(normalized)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (['0', 'false', 'no', 'off'].includes(normalized)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
}
|
||||
|
||||
@@ -132,6 +150,7 @@ class LogQuota {
|
||||
maintainOnLoad = true,
|
||||
) {
|
||||
this.loadManagedFiles();
|
||||
|
||||
if (maintainOnLoad) {
|
||||
this.cleanupExpired();
|
||||
this.ensureCapacity(0);
|
||||
@@ -141,12 +160,15 @@ class LogQuota {
|
||||
activate(filePath: string): number | null {
|
||||
const normalized = path.resolve(filePath);
|
||||
const known = this.files.get(normalized);
|
||||
|
||||
if (known) {
|
||||
this.active.add(normalized);
|
||||
return known.bytes;
|
||||
}
|
||||
|
||||
let bytes = 0;
|
||||
let mtimeMs = Date.now();
|
||||
|
||||
try {
|
||||
const stat = fs.statSync(normalized);
|
||||
bytes = stat.size;
|
||||
@@ -159,6 +181,7 @@ class LogQuota {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const date = FILE_RE.exec(path.basename(normalized))?.[1] ?? todayString();
|
||||
this.files.set(normalized, { path: normalized, bytes, mtimeMs, date });
|
||||
this.usedBytes += bytes;
|
||||
@@ -168,26 +191,38 @@ class LogQuota {
|
||||
|
||||
deactivate(filePath: string): void {
|
||||
this.active.delete(path.resolve(filePath));
|
||||
if (this.maintenanceSuspensions > 0) return;
|
||||
|
||||
if (this.maintenanceSuspensions > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.maintainAfterClose();
|
||||
}
|
||||
|
||||
suspendMaintenance(): () => void {
|
||||
this.maintenanceSuspensions += 1;
|
||||
let resumed = false;
|
||||
|
||||
return () => {
|
||||
if (resumed) return;
|
||||
if (resumed) {
|
||||
return;
|
||||
}
|
||||
|
||||
resumed = true;
|
||||
this.maintenanceSuspensions = Math.max(0, this.maintenanceSuspensions - 1);
|
||||
};
|
||||
}
|
||||
|
||||
reserve(filePath: string, bytes: number): boolean {
|
||||
if (bytes <= 0) return true;
|
||||
if (bytes <= 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.degraded && !this.retry(false)) {
|
||||
this.droppedLines += 1;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!this.ensureCapacity(bytes)) {
|
||||
this.droppedLines += 1;
|
||||
return false;
|
||||
@@ -195,13 +230,16 @@ class LogQuota {
|
||||
|
||||
const normalized = path.resolve(filePath);
|
||||
const file = this.files.get(normalized);
|
||||
|
||||
if (!file) {
|
||||
if (this.activate(normalized) === null) {
|
||||
this.droppedLines += 1;
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.reserve(normalized, bytes);
|
||||
}
|
||||
|
||||
file.bytes += bytes;
|
||||
file.mtimeMs = Date.now();
|
||||
this.usedBytes += bytes;
|
||||
@@ -216,7 +254,10 @@ class LogQuota {
|
||||
this.enterDegraded(`${operation}: ${errorMessage(error)}`);
|
||||
}
|
||||
|
||||
snapshot(): Omit<LogStorageStatus, 'directory' | 'maxTotalBytes' | 'retainDays' | 'perUinEnabled'> {
|
||||
snapshot(): Omit<
|
||||
LogStorageStatus,
|
||||
'directory' | 'maxTotalBytes' | 'retainDays' | 'perUinEnabled'
|
||||
> {
|
||||
return {
|
||||
state: this.degraded ? 'degraded' : this.lastError ? 'warning' : 'healthy',
|
||||
totalBytes: this.usedBytes,
|
||||
@@ -233,6 +274,7 @@ class LogQuota {
|
||||
this.degraded = false;
|
||||
this.lastError = null;
|
||||
this.nextRetryAt = 0;
|
||||
|
||||
try {
|
||||
this.refreshClosedFiles();
|
||||
this.cleanupExpired();
|
||||
@@ -251,8 +293,10 @@ class LogQuota {
|
||||
const candidates = [...this.files.values()]
|
||||
.filter((file) => !this.active.has(file.path))
|
||||
.sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path));
|
||||
|
||||
for (const file of candidates) {
|
||||
const bytes = file.bytes;
|
||||
|
||||
if (this.deleteManagedFile(file, 'capacity')) {
|
||||
deletedFiles += 1;
|
||||
freedBytes += bytes;
|
||||
@@ -263,28 +307,38 @@ class LogQuota {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.length === 0) {
|
||||
this.degraded = false;
|
||||
this.lastError = null;
|
||||
this.nextRetryAt = 0;
|
||||
} else if (this.usedBytes > this.maxTotalBytes) {
|
||||
this.enterDegraded(
|
||||
`managed logs still use ${String(this.usedBytes)} bytes after manual cleanup, `
|
||||
+ `exceeding the ${String(this.maxTotalBytes)} byte limit`,
|
||||
`managed logs still use ${String(this.usedBytes)} bytes after manual cleanup, ` +
|
||||
`exceeding the ${String(this.maxTotalBytes)} byte limit`,
|
||||
);
|
||||
}
|
||||
|
||||
this.ensureCapacity(0);
|
||||
return { deletedFiles, freedBytes, failures };
|
||||
}
|
||||
|
||||
private retry(force: boolean): boolean {
|
||||
if (!force && Date.now() < this.nextRetryAt) return false;
|
||||
if (!force && Date.now() < this.nextRetryAt) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.degraded = false;
|
||||
this.lastError = null;
|
||||
|
||||
try {
|
||||
this.refreshClosedFiles();
|
||||
const recovered = this.ensureCapacity(0);
|
||||
if (recovered) this.nextRetryAt = 0;
|
||||
|
||||
if (recovered) {
|
||||
this.nextRetryAt = 0;
|
||||
}
|
||||
|
||||
return recovered;
|
||||
} catch (error) {
|
||||
this.enterDegraded(`failed to refresh managed logs: ${errorMessage(error)}`);
|
||||
@@ -296,28 +350,45 @@ class LogQuota {
|
||||
try {
|
||||
this.refreshClosedFiles();
|
||||
this.cleanupExpired();
|
||||
if (this.degraded) this.retry(true);
|
||||
else this.ensureCapacity(0);
|
||||
|
||||
if (this.degraded) {
|
||||
this.retry(true);
|
||||
} else {
|
||||
this.ensureCapacity(0);
|
||||
}
|
||||
} catch (error) {
|
||||
this.enterDegraded(`failed to maintain managed logs after rotation: ${errorMessage(error)}`);
|
||||
this.enterDegraded(
|
||||
`failed to maintain managed logs after rotation: ${errorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private ensureCapacity(incomingBytes: number): boolean {
|
||||
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) return true;
|
||||
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const candidates = [...this.files.values()]
|
||||
.filter((file) => !this.active.has(file.path))
|
||||
.sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path));
|
||||
|
||||
for (const file of candidates) {
|
||||
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) break;
|
||||
if (!this.deleteManagedFile(file, 'capacity')) break;
|
||||
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (!this.deleteManagedFile(file, 'capacity')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.usedBytes + incomingBytes <= this.maxTotalBytes) return true;
|
||||
this.enterDegraded(
|
||||
`managed logs require ${String(this.usedBytes + incomingBytes)} bytes, `
|
||||
+ `exceeding the ${String(this.maxTotalBytes)} byte limit; no closed log can be reclaimed`,
|
||||
`managed logs require ${String(this.usedBytes + incomingBytes)} bytes, ` +
|
||||
`exceeding the ${String(this.maxTotalBytes)} byte limit; no closed log can be reclaimed`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
@@ -327,19 +398,26 @@ class LogQuota {
|
||||
this.degraded = true;
|
||||
this.lastError = message;
|
||||
this.nextRetryAt = Date.now() + QUOTA_RETRY_MS;
|
||||
if (shouldReport) reportStorageError(message);
|
||||
|
||||
if (shouldReport) {
|
||||
reportStorageError(message);
|
||||
}
|
||||
}
|
||||
|
||||
private cleanupExpired(): void {
|
||||
if (this.retainDays === 0) return;
|
||||
if (this.retainDays === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cutoff = Date.now() - this.retainDays * 24 * 60 * 60 * 1000;
|
||||
const expired = [...this.files.values()]
|
||||
.filter(
|
||||
(file) => !this.active.has(file.path) && dateOf(file.date).getTime() < cutoff,
|
||||
)
|
||||
.filter((file) => !this.active.has(file.path) && dateOf(file.date).getTime() < cutoff)
|
||||
.sort((a, b) => a.mtimeMs - b.mtimeMs || a.path.localeCompare(b.path));
|
||||
|
||||
for (const file of expired) {
|
||||
if (!this.deleteManagedFile(file, 'retention')) break;
|
||||
if (!this.deleteManagedFile(file, 'retention')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -350,8 +428,7 @@ class LogQuota {
|
||||
this.usedBytes = Math.max(0, this.usedBytes - file.bytes);
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.lastError =
|
||||
`${reason} cleanup failed for ${file.path}: ${error instanceof Error ? error.message : String(error)}`;
|
||||
this.lastError = `${reason} cleanup failed for ${file.path}: ${error instanceof Error ? error.message : String(error)}`;
|
||||
reportStorageError(this.lastError);
|
||||
return false;
|
||||
}
|
||||
@@ -368,10 +445,15 @@ class LogQuota {
|
||||
* may be newer than fs.stat while the WriteStream buffer is still flushing. */
|
||||
private refreshClosedFiles(): void {
|
||||
const disk = new Map(listManagedLogFiles(this.root).map((file) => [file.path, file]));
|
||||
|
||||
for (const [filePath, file] of this.files) {
|
||||
if (this.active.has(filePath)) continue;
|
||||
if (this.active.has(filePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const next = disk.get(filePath);
|
||||
this.usedBytes -= file.bytes;
|
||||
|
||||
if (next) {
|
||||
this.files.set(filePath, next);
|
||||
this.usedBytes += next.bytes;
|
||||
@@ -380,8 +462,12 @@ class LogQuota {
|
||||
this.files.delete(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
for (const file of disk.values()) {
|
||||
if (this.files.has(file.path)) continue;
|
||||
if (this.files.has(file.path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
this.files.set(file.path, file);
|
||||
this.usedBytes += file.bytes;
|
||||
}
|
||||
@@ -390,23 +476,35 @@ class LogQuota {
|
||||
|
||||
function listManagedLogFiles(root: string): ManagedLogFile[] {
|
||||
const out: ManagedLogFile[] = [];
|
||||
|
||||
const readDirectory = (dir: string): fs.Dirent[] | null => {
|
||||
try {
|
||||
return fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (isMissing(error)) return null;
|
||||
throw new Error(
|
||||
`failed to read managed log directory ${dir}: ${errorMessage(error)}`,
|
||||
{ cause: error },
|
||||
);
|
||||
if (isMissing(error)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw new Error(`failed to read managed log directory ${dir}: ${errorMessage(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const visit = (dir: string, entries: fs.Dirent[]): void => {
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile()) continue;
|
||||
if (!entry.isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const match = FILE_RE.exec(entry.name);
|
||||
if (!match) continue;
|
||||
|
||||
if (!match) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const filePath = path.resolve(dir, entry.name);
|
||||
|
||||
try {
|
||||
const stat = fs.statSync(filePath);
|
||||
out.push({
|
||||
@@ -416,25 +514,36 @@ function listManagedLogFiles(root: string): ManagedLogFile[] {
|
||||
date: match[1]!,
|
||||
});
|
||||
} catch (error) {
|
||||
if (isMissing(error)) continue;
|
||||
throw new Error(
|
||||
`failed to stat managed log ${filePath}: ${errorMessage(error)}`,
|
||||
{ cause: error },
|
||||
);
|
||||
if (isMissing(error)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new Error(`failed to stat managed log ${filePath}: ${errorMessage(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const rootEntries = readDirectory(root);
|
||||
if (!rootEntries) return out;
|
||||
|
||||
if (!rootEntries) {
|
||||
return out;
|
||||
}
|
||||
|
||||
visit(root, rootEntries);
|
||||
|
||||
for (const entry of rootEntries) {
|
||||
if (entry.isDirectory() && ACCOUNT_DIR_RE.test(entry.name)) {
|
||||
const accountDir = path.join(root, entry.name);
|
||||
const accountEntries = readDirectory(accountDir);
|
||||
if (accountEntries) visit(accountDir, accountEntries);
|
||||
|
||||
if (accountEntries) {
|
||||
visit(accountDir, accountEntries);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -477,35 +586,51 @@ class FileWriter {
|
||||
async prepare(): Promise<void> {
|
||||
this.ensureForToday(todayString());
|
||||
const stream = this.file?.stream;
|
||||
|
||||
if (!stream) {
|
||||
throw new Error(`failed to prepare log writer in ${this.dir}`);
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const opened = () => {
|
||||
stream.off('error', failed);
|
||||
resolve();
|
||||
};
|
||||
|
||||
const failed = (error: Error) => {
|
||||
stream.off('open', opened);
|
||||
reject(error);
|
||||
};
|
||||
|
||||
stream.once('open', opened);
|
||||
stream.once('error', failed);
|
||||
});
|
||||
}
|
||||
|
||||
write(data: string, bytes: number): boolean {
|
||||
if (this.disabled) return false;
|
||||
if (this.disabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const today = todayString();
|
||||
this.ensureForToday(today);
|
||||
if (!this.file) return false;
|
||||
|
||||
if (!this.file) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) {
|
||||
this.rotateBySize();
|
||||
if (!this.file) return false;
|
||||
|
||||
if (!this.file) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.quota.reserve(this.file.path, bytes)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!this.quota.reserve(this.file.path, bytes)) return false;
|
||||
try {
|
||||
this.file.stream.write(data);
|
||||
} catch (error) {
|
||||
@@ -513,6 +638,7 @@ class FileWriter {
|
||||
this.quota.writeFailed(this.file.path, error);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.file.bytes += bytes;
|
||||
return true;
|
||||
}
|
||||
@@ -523,7 +649,9 @@ class FileWriter {
|
||||
}
|
||||
|
||||
private ensureForToday(today: string): void {
|
||||
if (this.file && this.file.date === today) return;
|
||||
if (this.file && this.file.date === today) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.file) {
|
||||
this.closeCurrent();
|
||||
@@ -532,30 +660,48 @@ class FileWriter {
|
||||
// Resume from the highest existing split index for today (so two
|
||||
// process starts on the same day share files / don't clobber).
|
||||
let idx = 0;
|
||||
while (fs.existsSync(this.pathFor(today, idx + 1))) idx++;
|
||||
|
||||
while (fs.existsSync(this.pathFor(today, idx + 1))) {
|
||||
idx++;
|
||||
}
|
||||
|
||||
this.file = this.openFile(today, idx);
|
||||
}
|
||||
|
||||
private rotateBySize(): void {
|
||||
if (!this.file) return;
|
||||
if (!this.file) {
|
||||
return;
|
||||
}
|
||||
|
||||
const date = this.file.date;
|
||||
const previousIndex = this.file.splitIndex;
|
||||
this.closeCurrent();
|
||||
let next = previousIndex + 1;
|
||||
while (fs.existsSync(this.pathFor(date, next))) next++;
|
||||
|
||||
while (fs.existsSync(this.pathFor(date, next))) {
|
||||
next++;
|
||||
}
|
||||
|
||||
this.file = this.openFile(date, next);
|
||||
}
|
||||
|
||||
private closeCurrent(): void {
|
||||
const file = this.file;
|
||||
this.file = null;
|
||||
if (!file) return;
|
||||
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
|
||||
let finish!: () => void;
|
||||
const closed = new Promise<void>((resolve) => {
|
||||
let settled = false;
|
||||
|
||||
finish = () => {
|
||||
if (settled) return;
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
this.quota.deactivate(file.path);
|
||||
resolve();
|
||||
@@ -565,6 +711,7 @@ class FileWriter {
|
||||
void closed.finally(() => this.pendingCloses.delete(closed));
|
||||
|
||||
file.stream.once('error', finish);
|
||||
|
||||
try {
|
||||
file.stream.end(finish);
|
||||
} catch (error) {
|
||||
@@ -576,12 +723,20 @@ class FileWriter {
|
||||
private openFile(date: string, splitIndex: number): OpenFile | null {
|
||||
const p = this.pathFor(date, splitIndex);
|
||||
const existingBytes = this.quota.activate(p);
|
||||
if (existingBytes === null) return null;
|
||||
|
||||
if (existingBytes === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const stream = fs.createWriteStream(p, { flags: 'a' });
|
||||
stream.on('error', (err) => {
|
||||
this.disabled = true;
|
||||
if (this.file?.stream === stream) this.file = null;
|
||||
|
||||
if (this.file?.stream === stream) {
|
||||
this.file = null;
|
||||
}
|
||||
|
||||
this.quota.deactivate(p);
|
||||
this.quota.writeFailed(p, err);
|
||||
});
|
||||
@@ -614,7 +769,10 @@ export class FileTransport {
|
||||
private perUin = new Map<number, FileWriter>();
|
||||
|
||||
constructor(policy?: LogStoragePolicy) {
|
||||
if (policy) validatePolicy(policy);
|
||||
if (policy) {
|
||||
validatePolicy(policy);
|
||||
}
|
||||
|
||||
this.dir = path.resolve(process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR);
|
||||
this.maxBytes =
|
||||
parseRequiredPositiveInt(
|
||||
@@ -622,31 +780,35 @@ export class FileTransport {
|
||||
DEFAULT_MAX_MB,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'SNOWLUMA_LOG_MAX_MB',
|
||||
) * 1024 * 1024;
|
||||
) *
|
||||
1024 *
|
||||
1024;
|
||||
this.maxTotalBytes =
|
||||
(policy?.maxTotalMb
|
||||
?? parseRequiredPositiveInt(
|
||||
(policy?.maxTotalMb ??
|
||||
parseRequiredPositiveInt(
|
||||
process.env.SNOWLUMA_LOG_MAX_TOTAL_MB,
|
||||
DEFAULT_MAX_TOTAL_MB,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'SNOWLUMA_LOG_MAX_TOTAL_MB',
|
||||
)) * 1024 * 1024;
|
||||
this.retainDays = policy?.retainDays
|
||||
?? parseNonNegativeInt(
|
||||
)) *
|
||||
1024 *
|
||||
1024;
|
||||
this.retainDays =
|
||||
policy?.retainDays ??
|
||||
parseNonNegativeInt(
|
||||
process.env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
DEFAULT_RETAIN_DAYS,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
);
|
||||
this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0';
|
||||
this.perUinEnabled = policy?.perUinEnabled
|
||||
?? parseRequiredBool(
|
||||
process.env.SNOWLUMA_LOG_PER_UIN,
|
||||
false,
|
||||
'SNOWLUMA_LOG_PER_UIN',
|
||||
);
|
||||
this.perUinEnabled =
|
||||
policy?.perUinEnabled ??
|
||||
parseRequiredBool(process.env.SNOWLUMA_LOG_PER_UIN, false, 'SNOWLUMA_LOG_PER_UIN');
|
||||
|
||||
if (this.enabled) this.initialize();
|
||||
if (this.enabled) {
|
||||
this.initialize();
|
||||
}
|
||||
}
|
||||
|
||||
/** True when no file output will happen (env disable or init failure). */
|
||||
@@ -679,6 +841,7 @@ export class FileTransport {
|
||||
...(this.initializationError ? { lastError: this.initializationError } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...this.quota.snapshot(),
|
||||
directory: this.dir,
|
||||
@@ -695,20 +858,29 @@ export class FileTransport {
|
||||
|
||||
const disablingPerUin = this.perUinEnabled && !policy.perUinEnabled;
|
||||
this.perUinEnabled = policy.perUinEnabled;
|
||||
|
||||
if (disablingPerUin) {
|
||||
const writers = [...this.perUin.values()];
|
||||
this.perUin.clear();
|
||||
await Promise.all(writers.map((writer) => writer.close()));
|
||||
}
|
||||
if (this.quota) this.quota.updatePolicy(this.maxTotalBytes, this.retainDays);
|
||||
|
||||
if (this.quota) {
|
||||
this.quota.updatePolicy(this.maxTotalBytes, this.retainDays);
|
||||
}
|
||||
|
||||
if (this.enabled && (!this.quota || !this.shared || this.shared.isDisabled)) {
|
||||
await this.recoverSharedWriter(true);
|
||||
}
|
||||
|
||||
return this.getStorageStatus();
|
||||
}
|
||||
|
||||
async clearManagedLogs(): Promise<LogCleanupResult> {
|
||||
if (!this.enabled) return this.clearLogsWhileDisabled();
|
||||
if (!this.enabled) {
|
||||
return this.clearLogsWhileDisabled();
|
||||
}
|
||||
|
||||
if (!this.quota) {
|
||||
try {
|
||||
this.quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays);
|
||||
@@ -716,6 +888,7 @@ export class FileTransport {
|
||||
this.recordWriterRecoveryFailure(error);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.quota) {
|
||||
return {
|
||||
deletedFiles: 0,
|
||||
@@ -729,13 +902,11 @@ export class FileTransport {
|
||||
|
||||
const quota = this.quota;
|
||||
const accountUins = [...this.perUin.keys()];
|
||||
const writers = [
|
||||
...(this.shared ? [this.shared] : []),
|
||||
...this.perUin.values(),
|
||||
];
|
||||
const writers = [...(this.shared ? [this.shared] : []), ...this.perUin.values()];
|
||||
this.shared = null;
|
||||
this.perUin.clear();
|
||||
const resumeMaintenance = quota.suspendMaintenance();
|
||||
|
||||
try {
|
||||
await Promise.all(writers.map((writer) => writer.close()));
|
||||
} finally {
|
||||
@@ -745,6 +916,7 @@ export class FileTransport {
|
||||
const result = quota.clearClosedFiles();
|
||||
|
||||
const shared = new FileWriter(this.dir, this.maxBytes, quota);
|
||||
|
||||
try {
|
||||
await shared.prepare();
|
||||
this.shared = shared;
|
||||
@@ -757,15 +929,27 @@ export class FileTransport {
|
||||
message: this.initializationError ?? 'failed to reopen the shared log writer',
|
||||
});
|
||||
}
|
||||
|
||||
if (this.perUinEnabled) {
|
||||
for (const uin of accountUins) {
|
||||
const writer = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, quota);
|
||||
if (writer.isDisabled) continue;
|
||||
const writer = new FileWriter(
|
||||
path.join(this.dir, String(uin)),
|
||||
this.maxBytes,
|
||||
quota,
|
||||
);
|
||||
|
||||
if (writer.isDisabled) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await writer.prepare();
|
||||
this.perUin.set(uin, writer);
|
||||
} catch (error) {
|
||||
quota.storageFailed(`failed to reopen account log writer for ${String(uin)}`, error);
|
||||
quota.storageFailed(
|
||||
`failed to reopen account log writer for ${String(uin)}`,
|
||||
error,
|
||||
);
|
||||
result.failures.push({
|
||||
file: String(uin),
|
||||
message: `failed to reopen account log writer: ${errorMessage(error)}`,
|
||||
@@ -778,11 +962,20 @@ export class FileTransport {
|
||||
}
|
||||
|
||||
write(line: string, uin?: number): void {
|
||||
if (!this.enabled) return;
|
||||
if (!this.shared || this.shared.isDisabled) {
|
||||
if (!this.recoverSharedWriterForWrite()) return;
|
||||
if (!this.enabled) {
|
||||
return;
|
||||
}
|
||||
if (!this.shared) return;
|
||||
|
||||
if (!this.shared || this.shared.isDisabled) {
|
||||
if (!this.recoverSharedWriterForWrite()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.shared) {
|
||||
return;
|
||||
}
|
||||
|
||||
const data = sanitizeLogLine(line) + '\n';
|
||||
const bytes = Buffer.byteLength(data, 'utf8');
|
||||
|
||||
@@ -791,53 +984,86 @@ export class FileTransport {
|
||||
this.shared = null;
|
||||
this.nextWriterRetryAt = Date.now() + QUOTA_RETRY_MS;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (uin !== undefined && this.perUinEnabled && this.quota) {
|
||||
let w = this.perUin.get(uin);
|
||||
|
||||
if (w?.isDisabled) {
|
||||
this.perUin.delete(uin);
|
||||
w = undefined;
|
||||
}
|
||||
|
||||
if (!w) {
|
||||
w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.quota);
|
||||
if (w.isDisabled) return;
|
||||
|
||||
if (w.isDisabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.perUin.set(uin, w);
|
||||
}
|
||||
|
||||
w.write(data, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
const closes: Promise<void>[] = [];
|
||||
if (this.shared) closes.push(this.shared.close());
|
||||
for (const w of this.perUin.values()) closes.push(w.close());
|
||||
|
||||
if (this.shared) {
|
||||
closes.push(this.shared.close());
|
||||
}
|
||||
|
||||
for (const w of this.perUin.values()) {
|
||||
closes.push(w.close());
|
||||
}
|
||||
|
||||
this.shared = null;
|
||||
this.perUin.clear();
|
||||
await Promise.all(closes);
|
||||
}
|
||||
|
||||
private async recoverSharedWriter(force: boolean): Promise<void> {
|
||||
if (!this.enabled) return;
|
||||
if (!this.enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!force && Date.now() < this.nextWriterRetryAt) {
|
||||
throw new Error(this.initializationError ?? 'log writer retry is rate-limited');
|
||||
}
|
||||
if (this.shared?.isDisabled) this.shared = null;
|
||||
if (!this.quota) this.initialize();
|
||||
|
||||
if (this.shared?.isDisabled) {
|
||||
this.shared = null;
|
||||
}
|
||||
|
||||
if (!this.quota) {
|
||||
this.initialize();
|
||||
}
|
||||
|
||||
if (!this.shared && this.quota) {
|
||||
const writer = new FileWriter(this.dir, this.maxBytes, this.quota);
|
||||
if (!writer.isDisabled) this.shared = writer;
|
||||
|
||||
if (!writer.isDisabled) {
|
||||
this.shared = writer;
|
||||
}
|
||||
}
|
||||
|
||||
const writer = this.shared;
|
||||
|
||||
if (!writer) {
|
||||
throw new Error(this.initializationError ?? 'failed to create the shared log writer');
|
||||
}
|
||||
|
||||
try {
|
||||
await writer.prepare();
|
||||
|
||||
if (writer.isDisabled || !writer.currentPath) {
|
||||
throw new Error('the shared log writer did not open a file');
|
||||
}
|
||||
|
||||
this.initializationError = null;
|
||||
this.nextWriterRetryAt = 0;
|
||||
} catch (error) {
|
||||
@@ -848,18 +1074,32 @@ export class FileTransport {
|
||||
}
|
||||
|
||||
private recoverSharedWriterForWrite(): boolean {
|
||||
if (!this.enabled || Date.now() < this.nextWriterRetryAt) return false;
|
||||
if (this.shared?.isDisabled) this.shared = null;
|
||||
if (!this.quota) this.initialize();
|
||||
if (!this.enabled || Date.now() < this.nextWriterRetryAt) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.shared?.isDisabled) {
|
||||
this.shared = null;
|
||||
}
|
||||
|
||||
if (!this.quota) {
|
||||
this.initialize();
|
||||
}
|
||||
|
||||
if (!this.shared && this.quota) {
|
||||
const writer = new FileWriter(this.dir, this.maxBytes, this.quota);
|
||||
if (!writer.isDisabled) this.shared = writer;
|
||||
|
||||
if (!writer.isDisabled) {
|
||||
this.shared = writer;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.shared) {
|
||||
this.initializationError = null;
|
||||
this.nextWriterRetryAt = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -903,8 +1143,7 @@ export class FileTransport {
|
||||
}
|
||||
|
||||
private recordWriterRecoveryFailure(error: unknown): void {
|
||||
this.initializationError =
|
||||
`failed to initialize log storage ${this.dir}: ${errorMessage(error)}`;
|
||||
this.initializationError = `failed to initialize log storage ${this.dir}: ${errorMessage(error)}`;
|
||||
this.nextWriterRetryAt = Date.now() + QUOTA_RETRY_MS;
|
||||
reportStorageError(this.initializationError);
|
||||
}
|
||||
@@ -914,9 +1153,11 @@ export class FileTransport {
|
||||
fs.mkdirSync(this.dir, { recursive: true });
|
||||
const quota = new LogQuota(this.dir, this.maxTotalBytes, this.retainDays);
|
||||
const writer = new FileWriter(this.dir, this.maxBytes, quota);
|
||||
|
||||
if (writer.isDisabled) {
|
||||
throw new Error(`failed to create shared log writer in ${this.dir}`);
|
||||
}
|
||||
|
||||
this.quota = quota;
|
||||
this.shared = writer;
|
||||
this.initializationError = null;
|
||||
@@ -931,23 +1172,21 @@ export class FileTransport {
|
||||
|
||||
function validatePolicy(policy: LogStoragePolicy): void {
|
||||
if (
|
||||
!Number.isSafeInteger(policy.maxTotalMb)
|
||||
|| policy.maxTotalMb <= 0
|
||||
|| policy.maxTotalMb > MAX_LOG_TOTAL_MB
|
||||
!Number.isSafeInteger(policy.maxTotalMb) ||
|
||||
policy.maxTotalMb <= 0 ||
|
||||
policy.maxTotalMb > MAX_LOG_TOTAL_MB
|
||||
) {
|
||||
throw new RangeError(
|
||||
`maxTotalMb must be an integer in 1..${String(MAX_LOG_TOTAL_MB)}`,
|
||||
);
|
||||
throw new RangeError(`maxTotalMb must be an integer in 1..${String(MAX_LOG_TOTAL_MB)}`);
|
||||
}
|
||||
|
||||
if (
|
||||
!Number.isSafeInteger(policy.retainDays)
|
||||
|| policy.retainDays < 0
|
||||
|| policy.retainDays > MAX_LOG_RETAIN_DAYS
|
||||
!Number.isSafeInteger(policy.retainDays) ||
|
||||
policy.retainDays < 0 ||
|
||||
policy.retainDays > MAX_LOG_RETAIN_DAYS
|
||||
) {
|
||||
throw new RangeError(
|
||||
`retainDays must be an integer in 0..${String(MAX_LOG_RETAIN_DAYS)}`,
|
||||
);
|
||||
throw new RangeError(`retainDays must be an integer in 0..${String(MAX_LOG_RETAIN_DAYS)}`);
|
||||
}
|
||||
|
||||
if (typeof policy.perUinEnabled !== 'boolean') {
|
||||
throw new TypeError('perUinEnabled must be a boolean');
|
||||
}
|
||||
@@ -957,15 +1196,23 @@ let singleton: FileTransport | null = null;
|
||||
let configuredPolicy: LogStoragePolicy | null = null;
|
||||
|
||||
export function getFileTransport(): FileTransport {
|
||||
if (!singleton) singleton = new FileTransport(configuredPolicy ?? undefined);
|
||||
if (!singleton) {
|
||||
singleton = new FileTransport(configuredPolicy ?? undefined);
|
||||
}
|
||||
|
||||
return singleton;
|
||||
}
|
||||
|
||||
export async function configureFileTransport(policy: LogStoragePolicy): Promise<LogStorageStatus> {
|
||||
validatePolicy(policy);
|
||||
configuredPolicy = { ...policy };
|
||||
if (!singleton) singleton = new FileTransport(configuredPolicy);
|
||||
else await singleton.updatePolicy(configuredPolicy);
|
||||
|
||||
if (!singleton) {
|
||||
singleton = new FileTransport(configuredPolicy);
|
||||
} else {
|
||||
await singleton.updatePolicy(configuredPolicy);
|
||||
}
|
||||
|
||||
return singleton.getStorageStatus();
|
||||
}
|
||||
|
||||
@@ -979,7 +1226,10 @@ export function clearManagedLogs(): Promise<LogCleanupResult> {
|
||||
|
||||
/** Reset state between tests. Closes all active file handles. */
|
||||
export async function _resetFileTransportForTesting(): Promise<void> {
|
||||
if (singleton) await singleton.close();
|
||||
if (singleton) {
|
||||
await singleton.close();
|
||||
}
|
||||
|
||||
singleton = null;
|
||||
configuredPolicy = null;
|
||||
}
|
||||
|
||||
@@ -8,37 +8,66 @@ const C1_STRING_STARTERS = new Set([0x90, 0x98, 0x9e, 0x9f]);
|
||||
function skipCsi(line: string, start: number): number {
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (code >= 0x40 && code <= 0x7e) return i + 1;
|
||||
|
||||
if (code >= 0x40 && code <= 0x7e) {
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return line.length;
|
||||
}
|
||||
|
||||
function skipControlString(line: string, start: number, allowBell: boolean): number {
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (allowBell && code === BEL) return i + 1;
|
||||
if (code === C1_ST) return i + 1;
|
||||
if (code === ESC && line.charCodeAt(i + 1) === 0x5c) return i + 2;
|
||||
|
||||
if (allowBell && code === BEL) {
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
if (code === C1_ST) {
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
if (code === ESC && line.charCodeAt(i + 1) === 0x5c) {
|
||||
return i + 2;
|
||||
}
|
||||
}
|
||||
|
||||
return line.length;
|
||||
}
|
||||
|
||||
function skipEscSequence(line: string, start: number): number {
|
||||
if (start >= line.length) return line.length;
|
||||
if (start >= line.length) {
|
||||
return line.length;
|
||||
}
|
||||
|
||||
const first = line.charCodeAt(start);
|
||||
if (first === 0x5b) return skipCsi(line, start + 1);
|
||||
if (first === 0x5d) return skipControlString(line, start + 1, true);
|
||||
|
||||
if (first === 0x5b) {
|
||||
return skipCsi(line, start + 1);
|
||||
}
|
||||
|
||||
if (first === 0x5d) {
|
||||
return skipControlString(line, start + 1, true);
|
||||
}
|
||||
|
||||
if (first === 0x50 || first === 0x58 || first === 0x5e || first === 0x5f) {
|
||||
return skipControlString(line, start + 1, false);
|
||||
}
|
||||
|
||||
let i = start;
|
||||
|
||||
while (i < line.length) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (code < 0x20 || code > 0x2f) break;
|
||||
|
||||
if (code < 0x20 || code > 0x2f) {
|
||||
break;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
const final = line.charCodeAt(i);
|
||||
return final >= 0x30 && final <= 0x7e ? i + 1 : start;
|
||||
}
|
||||
@@ -54,6 +83,7 @@ function skipEscSequence(line: string, start: number): number {
|
||||
*/
|
||||
export function sanitizeLogLine(line: string): string {
|
||||
let plain = '';
|
||||
|
||||
for (let i = 0; i < line.length;) {
|
||||
const code = line.charCodeAt(i);
|
||||
|
||||
@@ -61,14 +91,17 @@ export function sanitizeLogLine(line: string): string {
|
||||
i = skipEscSequence(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (code === C1_CSI) {
|
||||
i = skipCsi(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
|
||||
i = skipControlString(line, i + 1, code === C1_OSC);
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) {
|
||||
i += 1;
|
||||
continue;
|
||||
@@ -77,5 +110,6 @@ export function sanitizeLogLine(line: string): string {
|
||||
plain += line[i];
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return plain;
|
||||
}
|
||||
@@ -22,20 +22,30 @@ function isSensitiveKey(key: string): boolean {
|
||||
.map((segment) => segment.toLowerCase());
|
||||
|
||||
return segments.some((segment, index) => {
|
||||
if (SENSITIVE_SEGMENTS.has(segment)) return true;
|
||||
if (SENSITIVE_SEGMENTS.has(segment)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const next = segments[index + 1];
|
||||
return next === 'key' && (
|
||||
segment === 'api'
|
||||
|| segment === 'private'
|
||||
|| segment === 'session'
|
||||
return (
|
||||
next === 'key' && (segment === 'api' || segment === 'private' || segment === 'session')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function valueRepr(v: unknown, key?: string): string {
|
||||
if (key !== undefined && isSensitiveKey(key)) return '"***"';
|
||||
if (v === null) return 'null';
|
||||
if (v === undefined) return 'undefined';
|
||||
if (key !== undefined && isSensitiveKey(key)) {
|
||||
return '"***"';
|
||||
}
|
||||
|
||||
if (v === null) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
if (v === undefined) {
|
||||
return 'undefined';
|
||||
}
|
||||
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
|
||||
@@ -44,7 +54,10 @@ function valueRepr(v: unknown, key?: string): string {
|
||||
case 'bigint':
|
||||
return String(v);
|
||||
case 'object':
|
||||
if (Array.isArray(v)) return `[len=${v.length}]`;
|
||||
if (Array.isArray(v)) {
|
||||
return `[len=${v.length}]`;
|
||||
}
|
||||
|
||||
return '{...}';
|
||||
default:
|
||||
return typeof v;
|
||||
@@ -60,20 +73,26 @@ function valueRepr(v: unknown, key?: string): string {
|
||||
* replaced with `...` so the next field doesn't get half-rendered.
|
||||
*/
|
||||
export function summarizeParams(params: unknown): string {
|
||||
if (params === null || params === undefined) return '{}';
|
||||
if (params === null || params === undefined) {
|
||||
return '{}';
|
||||
}
|
||||
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL
|
||||
? `${s.slice(0, MAX_TOTAL - 3)}...`
|
||||
: s;
|
||||
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL - 3)}...` : s;
|
||||
}
|
||||
|
||||
if (Array.isArray(params)) {
|
||||
return `[len=${params.length}]`;
|
||||
}
|
||||
if (Array.isArray(params)) return `[len=${params.length}]`;
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v, k)}`;
|
||||
const separatorLength = out.length > 0 ? 1 : 0;
|
||||
|
||||
if (total + separatorLength + entry.length > MAX_TOTAL) {
|
||||
if (out.length === 0) {
|
||||
return `${entry.slice(0, MAX_TOTAL - 3)}...`;
|
||||
@@ -84,13 +103,16 @@ export function summarizeParams(params: unknown): string {
|
||||
? `${rendered} ...`
|
||||
: `${rendered.slice(0, MAX_TOTAL - 3)}...`;
|
||||
}
|
||||
|
||||
out.push(entry);
|
||||
total += separatorLength + entry.length;
|
||||
}
|
||||
|
||||
return out.join(' ');
|
||||
}
|
||||
|
||||
const ASSIGNMENT_START = /(^|[^A-Za-z0-9_-])(["']?)([-_]*(?=[A-Za-z0-9_.-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9_.-]*)\2(\s*[:=]\s*)/gi;
|
||||
const ASSIGNMENT_START =
|
||||
/(^|[^A-Za-z0-9_-])(["']?)([-_]*(?=[A-Za-z0-9_.-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9_.-]*)\2(\s*[:=]\s*)/gi;
|
||||
const AUTHORIZATION_BOUNDARY_SEGMENTS = new Set([
|
||||
'authorization',
|
||||
'cookie',
|
||||
@@ -118,19 +140,23 @@ function isKeyKind(key: string, kind: 'authorization' | 'cookie'): boolean {
|
||||
function isAuthorizationBoundaryKey(key: string): boolean {
|
||||
const segments = keySegments(key);
|
||||
return segments.some((segment, index) => {
|
||||
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) return true;
|
||||
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const next = segments[index + 1];
|
||||
return next === 'key' && (
|
||||
segment === 'api'
|
||||
|| segment === 'private'
|
||||
|| segment === 'session'
|
||||
return (
|
||||
next === 'key' && (segment === 'api' || segment === 'private' || segment === 'session')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function quotedValueEnd(message: string, start: number): number | undefined {
|
||||
const quote = message[start];
|
||||
if (quote !== '"' && quote !== "'") return undefined;
|
||||
|
||||
if (quote !== '"' && quote !== "'") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
for (let index = start + 1; index < message.length; index += 1) {
|
||||
if (message[index] === '\\') {
|
||||
@@ -139,16 +165,19 @@ function quotedValueEnd(message: string, start: number): number | undefined {
|
||||
return index + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return message.length;
|
||||
}
|
||||
|
||||
function cookieValueEnd(message: string, start: number): number {
|
||||
const initialQuotedEnd = quotedValueEnd(message, start);
|
||||
let end: number;
|
||||
|
||||
if (initialQuotedEnd !== undefined) {
|
||||
end = initialQuotedEnd;
|
||||
} else {
|
||||
end = start;
|
||||
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
@@ -156,25 +185,41 @@ function cookieValueEnd(message: string, start: number): number {
|
||||
|
||||
while (end < message.length) {
|
||||
let semicolon: number = end;
|
||||
|
||||
while (message[semicolon] === ' ' || message[semicolon] === '\t') {
|
||||
semicolon += 1;
|
||||
}
|
||||
if (message[semicolon] !== ';') break;
|
||||
|
||||
if (message[semicolon] !== ';') {
|
||||
break;
|
||||
}
|
||||
|
||||
let nameStart = semicolon + 1;
|
||||
|
||||
while (message[nameStart] === ' ' || message[nameStart] === '\t') {
|
||||
nameStart += 1;
|
||||
}
|
||||
|
||||
let nameEnd = nameStart;
|
||||
while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) nameEnd += 1;
|
||||
if (nameEnd === nameStart) break;
|
||||
|
||||
while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) {
|
||||
nameEnd += 1;
|
||||
}
|
||||
|
||||
if (nameEnd === nameStart) {
|
||||
break;
|
||||
}
|
||||
|
||||
end = nameEnd;
|
||||
if (message[end] !== '=') continue;
|
||||
|
||||
if (message[end] !== '=') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const attribute = message.slice(nameStart, nameEnd).toLowerCase();
|
||||
const valueStart = end + 1;
|
||||
const quotedEnd = quotedValueEnd(message, valueStart);
|
||||
|
||||
if (quotedEnd !== undefined) {
|
||||
end = quotedEnd;
|
||||
continue;
|
||||
@@ -182,42 +227,54 @@ function cookieValueEnd(message: string, start: number): number {
|
||||
|
||||
if (attribute !== 'expires') {
|
||||
end = valueStart;
|
||||
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
end = valueStart;
|
||||
|
||||
while (end < message.length && !/[;}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
assignments.lastIndex = valueStart;
|
||||
const nextField = assignments.exec(message);
|
||||
if (nextField && nextField.index < end) end = nextField.index;
|
||||
|
||||
if (nextField && nextField.index < end) {
|
||||
end = nextField.index;
|
||||
}
|
||||
}
|
||||
|
||||
return end;
|
||||
}
|
||||
|
||||
function genericValueEnd(message: string, start: number): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
if (quotedEnd !== undefined) return quotedEnd;
|
||||
|
||||
if (quotedEnd !== undefined) {
|
||||
return quotedEnd;
|
||||
}
|
||||
|
||||
let end = start;
|
||||
|
||||
while (end < message.length && !/[\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
return end;
|
||||
}
|
||||
|
||||
function authorizationValueEnd(
|
||||
message: string,
|
||||
start: number,
|
||||
query: boolean,
|
||||
): number {
|
||||
function authorizationValueEnd(message: string, start: number, query: boolean): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
if (quotedEnd !== undefined) return quotedEnd;
|
||||
|
||||
if (quotedEnd !== undefined) {
|
||||
return quotedEnd;
|
||||
}
|
||||
|
||||
if (query) {
|
||||
const queryEnd = message.indexOf('&', start);
|
||||
@@ -226,16 +283,21 @@ function authorizationValueEnd(
|
||||
|
||||
let end = message.length;
|
||||
const structural = message.slice(start).search(/[\r\n}\]]/);
|
||||
if (structural >= 0) end = start + structural;
|
||||
|
||||
if (structural >= 0) {
|
||||
end = start + structural;
|
||||
}
|
||||
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
const remaining = message.slice(start, end);
|
||||
|
||||
for (let match = assignments.exec(remaining); match; match = assignments.exec(remaining)) {
|
||||
if (isAuthorizationBoundaryKey(match[3]!)) {
|
||||
end = start + match.index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return end;
|
||||
}
|
||||
|
||||
@@ -245,23 +307,21 @@ export function redactLogMessage(message: string): string {
|
||||
let cursor = 0;
|
||||
ASSIGNMENT_START.lastIndex = 0;
|
||||
|
||||
for (let match = ASSIGNMENT_START.exec(message); match; match = ASSIGNMENT_START.exec(message)) {
|
||||
for (
|
||||
let match = ASSIGNMENT_START.exec(message);
|
||||
match;
|
||||
match = ASSIGNMENT_START.exec(message)
|
||||
) {
|
||||
const key = match[3]!;
|
||||
|
||||
if (!isSensitiveKey(key)) {
|
||||
ASSIGNMENT_START.lastIndex = Math.max(
|
||||
match.index + 1,
|
||||
ASSIGNMENT_START.lastIndex - 1,
|
||||
);
|
||||
ASSIGNMENT_START.lastIndex = Math.max(match.index + 1, ASSIGNMENT_START.lastIndex - 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
const valueStart = ASSIGNMENT_START.lastIndex;
|
||||
const valueEnd = isKeyKind(key, 'authorization')
|
||||
? authorizationValueEnd(
|
||||
message,
|
||||
valueStart,
|
||||
match[1] === '?' || match[1] === '&',
|
||||
)
|
||||
? authorizationValueEnd(message, valueStart, match[1] === '?' || match[1] === '&')
|
||||
: isKeyKind(key, 'cookie')
|
||||
? cookieValueEnd(message, valueStart)
|
||||
: genericValueEnd(message, valueStart);
|
||||
@@ -283,8 +343,13 @@ export function renderParamsVerbose(params: unknown): string {
|
||||
const seen = new WeakSet<object>();
|
||||
|
||||
const walk = (value: unknown): string => {
|
||||
if (value === null) return 'null';
|
||||
if (value === undefined) return 'undefined';
|
||||
if (value === null) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
if (value === undefined) {
|
||||
return 'undefined';
|
||||
}
|
||||
|
||||
switch (typeof value) {
|
||||
case 'string':
|
||||
@@ -293,8 +358,12 @@ export function renderParamsVerbose(params: unknown): string {
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(value);
|
||||
|
||||
case 'object': {
|
||||
if (seen.has(value as object)) return '"[circular]"';
|
||||
if (seen.has(value as object)) {
|
||||
return '"[circular]"';
|
||||
}
|
||||
|
||||
seen.add(value as object);
|
||||
const out = Array.isArray(value)
|
||||
? `[${value.map((item) => walk(item)).join(',')}]`
|
||||
@@ -304,6 +373,7 @@ export function renderParamsVerbose(params: unknown): string {
|
||||
seen.delete(value as object);
|
||||
return out;
|
||||
}
|
||||
|
||||
default:
|
||||
return typeof value;
|
||||
}
|
||||
|
||||
@@ -73,6 +73,7 @@ function resolveTraceBufferMax(): number {
|
||||
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
|
||||
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
|
||||
}
|
||||
|
||||
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
|
||||
/**
|
||||
@@ -89,15 +90,23 @@ class RingBuffer<T> {
|
||||
push(item: T): void {
|
||||
const end = (this.start + this.count) % this.cap;
|
||||
this.buf[end] = item;
|
||||
if (this.count < this.cap) this.count += 1;
|
||||
else this.start = (this.start + 1) % this.cap; // full → overwrite oldest
|
||||
|
||||
if (this.count < this.cap) {
|
||||
this.count += 1;
|
||||
} else {
|
||||
this.start = (this.start + 1) % this.cap;
|
||||
} // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!;
|
||||
|
||||
for (let i = 0; i < take; i += 1) {
|
||||
out[i] = this.buf[(first + i) % this.cap]!;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
@@ -115,21 +124,40 @@ let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
|
||||
if (
|
||||
raw === 'trace' ||
|
||||
raw === 'debug' ||
|
||||
raw === 'info' ||
|
||||
raw === 'success' ||
|
||||
raw === 'warn' ||
|
||||
raw === 'error'
|
||||
) {
|
||||
return raw;
|
||||
}
|
||||
|
||||
return 'info';
|
||||
}
|
||||
|
||||
function resolveFileMinLevel(): FileLogLevel {
|
||||
const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
if (raw === undefined || raw.trim() === '') return 'debug';
|
||||
|
||||
if (raw === undefined || raw.trim() === '') {
|
||||
return 'debug';
|
||||
}
|
||||
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === 'debug' || normalized === 'info' || normalized === 'success' ||
|
||||
normalized === 'warn' || normalized === 'error') {
|
||||
|
||||
if (
|
||||
normalized === 'debug' ||
|
||||
normalized === 'info' ||
|
||||
normalized === 'success' ||
|
||||
normalized === 'warn' ||
|
||||
normalized === 'error'
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
throw new TypeError(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
@@ -152,26 +180,39 @@ function shouldLogToFile(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentFileLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
export const LOG_LEVELS: readonly LogLevel[] = [
|
||||
'trace',
|
||||
'debug',
|
||||
'info',
|
||||
'success',
|
||||
'warn',
|
||||
'error',
|
||||
];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
}
|
||||
|
||||
|
||||
// Change the console / subscriber level at runtime.
|
||||
// Invalid input is a no-op (returns false).
|
||||
// Does not affect the file transport log level.
|
||||
|
||||
export function setLogLevel(level: string): boolean {
|
||||
const lower = String(level).toLowerCase();
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
|
||||
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
currentLevel = lower as LogLevel;
|
||||
return true;
|
||||
}
|
||||
|
||||
function useColor(): boolean {
|
||||
if (process.env.NO_COLOR === '1') return false;
|
||||
if (process.env.NO_COLOR === '1') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Boolean(process.stdout.isTTY);
|
||||
}
|
||||
|
||||
@@ -210,37 +251,36 @@ function render(level: LogLevel, options: LogOptions, message: string, reqId?: n
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
|
||||
}
|
||||
|
||||
function emit(
|
||||
level: LogLevel,
|
||||
options: LogOptions,
|
||||
args: unknown[],
|
||||
): void {
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
// Console / subscriber and file filters are independent. If no destination
|
||||
// accepts the record, stop before formatting or building a LogEntry.
|
||||
const passesConsole = shouldLog(level);
|
||||
const passesFile = level !== 'trace'
|
||||
&& shouldLogToFile(level);
|
||||
if (!passesConsole && !passesFile) return;
|
||||
const passesFile = level !== 'trace' && shouldLogToFile(level);
|
||||
|
||||
if (!passesConsole && !passesFile) {
|
||||
return;
|
||||
}
|
||||
|
||||
// `trace` is the high-volume full-chain diagnostic stream, intentionally
|
||||
// excluded from disk to avoid I/O saturation. When console is not dialed
|
||||
// to trace, the early return below skips format/render/disk entirely.
|
||||
// Set SNOWLUMA_LOG_LEVEL=trace to inspect trace output in console/memory;
|
||||
// trace never reaches disk regardless.
|
||||
if (level === 'trace' && !passesConsole) return;
|
||||
if (level === 'trace' && !passesConsole) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
|
||||
// (and its expensive deep render) only runs now that trace is confirmed live.
|
||||
let realArgs = args;
|
||||
|
||||
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
|
||||
realArgs = (args[0] as () => unknown[])();
|
||||
}
|
||||
|
||||
const reqId = currentRequestId();
|
||||
const formattedMessage = format(...realArgs);
|
||||
const message = level === 'trace'
|
||||
? formattedMessage
|
||||
: redactLogMessage(formattedMessage);
|
||||
const message = level === 'trace' ? formattedMessage : redactLogMessage(formattedMessage);
|
||||
const line = render(level, options, message, reqId);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
@@ -256,7 +296,11 @@ function emit(
|
||||
if (passesConsole) {
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
for (const subscriber of logSubscribers) subscriber(entry);
|
||||
|
||||
for (const subscriber of logSubscribers) {
|
||||
subscriber(entry);
|
||||
}
|
||||
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
@@ -265,6 +309,7 @@ function emit(
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const consoleLine = line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n';
|
||||
|
||||
try {
|
||||
stream.write(consoleLine);
|
||||
} catch {
|
||||
@@ -309,6 +354,7 @@ export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
logSubscribers.add(callback);
|
||||
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
@@ -364,7 +410,10 @@ export function renderTraceBytes(body: Uint8Array): string {
|
||||
}
|
||||
|
||||
export function runWithTraceRequest<T>(fn: () => T): T {
|
||||
if (currentRequestId() !== undefined || currentLevel !== 'trace') return fn();
|
||||
if (currentRequestId() !== undefined || currentLevel !== 'trace') {
|
||||
return fn();
|
||||
}
|
||||
|
||||
return runWithRequestId(nextRequestId(), fn);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,11 @@ let counter = 0;
|
||||
*/
|
||||
export function nextRequestId(): number {
|
||||
counter = (counter + 1) >>> 0;
|
||||
if (counter === 0) counter = 1;
|
||||
|
||||
if (counter === 0) {
|
||||
counter = 1;
|
||||
}
|
||||
|
||||
return counter;
|
||||
}
|
||||
|
||||
|
||||
+154
-58
@@ -33,9 +33,7 @@ export const DEFAULT_LOG_MAX_TOTAL_MB = 1024;
|
||||
export const DEFAULT_LOG_RETAIN_DAYS = 7;
|
||||
export const DEFAULT_LOG_PER_UIN = false;
|
||||
export const MAX_LOG_TOTAL_MB = Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024));
|
||||
export const MAX_LOG_RETAIN_DAYS = Math.floor(
|
||||
Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000),
|
||||
);
|
||||
export const MAX_LOG_RETAIN_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000));
|
||||
|
||||
/**
|
||||
* Pure on-disk-object → typed config normalization (defaults + validation,
|
||||
@@ -47,7 +45,9 @@ export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||
webuiHost: normalizeHost(obj.webuiHost),
|
||||
webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false },
|
||||
webuiTls: {
|
||||
enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false,
|
||||
},
|
||||
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
|
||||
logMaxTotalMb: normalizeRequiredInteger(
|
||||
obj.logMaxTotalMb,
|
||||
@@ -76,15 +76,24 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
|
||||
const out: Partial<RuntimeConfig> = {};
|
||||
|
||||
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
|
||||
if (port !== undefined) out.webuiPort = port;
|
||||
|
||||
if (port !== undefined) {
|
||||
out.webuiPort = port;
|
||||
}
|
||||
|
||||
const host = env.SNOWLUMA_WEBUI_HOST;
|
||||
if (typeof host === 'string' && host.trim()) out.webuiHost = host.trim();
|
||||
|
||||
if (typeof host === 'string' && host.trim()) {
|
||||
out.webuiHost = host.trim();
|
||||
}
|
||||
|
||||
// Present-but-"0"/"off" is a deliberate override (trust nobody), distinct
|
||||
// from "absent" — so gate on key presence, not truthiness.
|
||||
const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY;
|
||||
if (typeof tp === 'string') out.trustProxy = tp;
|
||||
|
||||
if (typeof tp === 'string') {
|
||||
out.trustProxy = tp;
|
||||
}
|
||||
|
||||
const logMaxTotalMb = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_MAX_TOTAL_MB,
|
||||
@@ -92,7 +101,10 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'SNOWLUMA_LOG_MAX_TOTAL_MB',
|
||||
);
|
||||
if (logMaxTotalMb !== undefined) out.logMaxTotalMb = logMaxTotalMb;
|
||||
|
||||
if (logMaxTotalMb !== undefined) {
|
||||
out.logMaxTotalMb = logMaxTotalMb;
|
||||
}
|
||||
|
||||
const logRetainDays = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
@@ -100,16 +112,22 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
);
|
||||
if (logRetainDays !== undefined) out.logRetainDays = logRetainDays;
|
||||
|
||||
const logPerUin = parseRequiredBoolEnv(
|
||||
env.SNOWLUMA_LOG_PER_UIN,
|
||||
'SNOWLUMA_LOG_PER_UIN',
|
||||
);
|
||||
if (logPerUin !== undefined) out.logPerUin = logPerUin;
|
||||
if (logRetainDays !== undefined) {
|
||||
out.logRetainDays = logRetainDays;
|
||||
}
|
||||
|
||||
const logPerUin = parseRequiredBoolEnv(env.SNOWLUMA_LOG_PER_UIN, 'SNOWLUMA_LOG_PER_UIN');
|
||||
|
||||
if (logPerUin !== undefined) {
|
||||
out.logPerUin = logPerUin;
|
||||
}
|
||||
|
||||
const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS');
|
||||
if (webuiTls !== undefined) out.webuiTls = { enabled: webuiTls };
|
||||
|
||||
if (webuiTls !== undefined) {
|
||||
out.webuiTls = { enabled: webuiTls };
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
@@ -152,7 +170,10 @@ export function updateRuntimeConfig(patch: Partial<RuntimeConfig>): RuntimeConfi
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): Record<string, unknown> | null {
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
@@ -163,6 +184,7 @@ function tryLoadRuntimeConfig(): Record<string, unknown> | null {
|
||||
|
||||
function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`;
|
||||
|
||||
try {
|
||||
fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH);
|
||||
@@ -177,6 +199,7 @@ function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -186,44 +209,68 @@ function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): boolean {
|
||||
const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined;
|
||||
return (
|
||||
parsed.webuiPort === n.webuiPort
|
||||
&& parsed.hookAutoLoad === n.hookAutoLoad
|
||||
&& parsed.webuiHost === n.webuiHost
|
||||
&& parsedTls === n.webuiTls?.enabled
|
||||
&& parsed.trustProxy === n.trustProxy
|
||||
&& parsed.logMaxTotalMb === n.logMaxTotalMb
|
||||
&& parsed.logRetainDays === n.logRetainDays
|
||||
&& parsed.logPerUin === n.logPerUin
|
||||
parsed.webuiPort === n.webuiPort &&
|
||||
parsed.hookAutoLoad === n.hookAutoLoad &&
|
||||
parsed.webuiHost === n.webuiHost &&
|
||||
parsedTls === n.webuiTls?.enabled &&
|
||||
parsed.trustProxy === n.trustProxy &&
|
||||
parsed.logMaxTotalMb === n.logMaxTotalMb &&
|
||||
parsed.logRetainDays === n.logRetainDays &&
|
||||
parsed.logPerUin === n.logPerUin
|
||||
);
|
||||
}
|
||||
|
||||
function parsePortString(raw: unknown): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
|
||||
if (!Number.isFinite(n)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
|
||||
if (port <= 0 || port > 65535) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
function normalizeHost(value: unknown): string {
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
return DEFAULT_WEBUI_HOST;
|
||||
}
|
||||
|
||||
function normalizePort(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const n = Math.trunc(value);
|
||||
if (n > 0 && n <= 65535) return n;
|
||||
|
||||
if (n > 0 && n <= 65535) {
|
||||
return n;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
|
||||
if (Number.isFinite(n)) {
|
||||
const port = Math.trunc(n);
|
||||
if (port > 0 && port <= 65535) return port;
|
||||
|
||||
if (port > 0 && port <= 65535) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
@@ -234,38 +281,54 @@ function normalizeRequiredInteger(
|
||||
max: number,
|
||||
field: string,
|
||||
): number {
|
||||
if (value === undefined) return fallback;
|
||||
if (value === undefined) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
|
||||
if (
|
||||
typeof n === 'number'
|
||||
&& Number.isSafeInteger(n)
|
||||
&& n >= min
|
||||
&& n <= max
|
||||
) {
|
||||
|
||||
if (typeof n === 'number' && Number.isSafeInteger(n) && n >= min && n <= max) {
|
||||
return n;
|
||||
}
|
||||
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
}
|
||||
|
||||
function normalizeRequiredBool(
|
||||
value: unknown,
|
||||
fallback: boolean,
|
||||
field: string,
|
||||
): boolean {
|
||||
if (value === undefined) return fallback;
|
||||
function normalizeRequiredBool(value: unknown, fallback: boolean, field: string): boolean {
|
||||
if (value === undefined) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const parsed = parseBoolValue(value);
|
||||
if (parsed !== undefined) return parsed;
|
||||
|
||||
if (parsed !== undefined) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
}
|
||||
|
||||
function normalizeBool(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'number') return value !== 0;
|
||||
if (typeof value === 'boolean') {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
return value !== 0;
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const v = value.trim().toLowerCase();
|
||||
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;
|
||||
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') return false;
|
||||
|
||||
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
@@ -275,27 +338,60 @@ function parseRequiredIntegerEnv(
|
||||
max: number,
|
||||
field: string,
|
||||
): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const n = Number(raw.trim());
|
||||
if (Number.isSafeInteger(n) && n >= min && n <= max) return n;
|
||||
|
||||
if (Number.isSafeInteger(n) && n >= min && n <= max) {
|
||||
return n;
|
||||
}
|
||||
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
}
|
||||
|
||||
function parseRequiredBoolEnv(raw: unknown, field: string): boolean | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const parsed = parseBoolValue(raw);
|
||||
if (parsed !== undefined) return parsed;
|
||||
|
||||
if (parsed !== undefined) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
}
|
||||
|
||||
function parseBoolValue(raw: unknown): boolean | undefined {
|
||||
if (typeof raw === 'boolean') return raw;
|
||||
if (raw === 1) return true;
|
||||
if (raw === 0) return false;
|
||||
if (typeof raw !== 'string') return undefined;
|
||||
if (typeof raw === 'boolean') {
|
||||
return raw;
|
||||
}
|
||||
|
||||
if (raw === 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (raw === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof raw !== 'string') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const value = raw.trim().toLowerCase();
|
||||
if (value === 'true' || value === '1' || value === 'yes' || value === 'on') return true;
|
||||
if (value === 'false' || value === '0' || value === 'no' || value === 'off') return false;
|
||||
|
||||
if (value === 'true' || value === '1' || value === 'yes' || value === 'on') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value === 'false' || value === '0' || value === 'no' || value === 'off') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -58,14 +58,26 @@ export class SingleFlightCache<K, V> {
|
||||
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
|
||||
if (!opts.force) {
|
||||
const hit = this.fresh.get(key);
|
||||
if (hit && this.now() - hit.at < this.ttlMs) return Promise.resolve(hit.value);
|
||||
|
||||
if (hit && this.now() - hit.at < this.ttlMs) {
|
||||
return Promise.resolve(hit.value);
|
||||
}
|
||||
}
|
||||
|
||||
const existing = this.inflight.get(key);
|
||||
if (existing) return existing;
|
||||
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
try {
|
||||
const value = await this.load(key);
|
||||
if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value });
|
||||
|
||||
if (this.shouldCache(value)) {
|
||||
this.fresh.set(key, { at: this.now(), value });
|
||||
}
|
||||
|
||||
return value;
|
||||
} finally {
|
||||
this.inflight.delete(key);
|
||||
|
||||
@@ -14,8 +14,12 @@ describe('access token strength', () => {
|
||||
});
|
||||
|
||||
it('scores system and user-specific words as guessable', () => {
|
||||
expect(assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001']))
|
||||
.toMatchObject({ acceptable: false, reason: 'guessable' });
|
||||
expect(
|
||||
assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001']),
|
||||
).toMatchObject({
|
||||
acceptable: false,
|
||||
reason: 'guessable',
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts a sufficiently long, hard-to-guess token', () => {
|
||||
|
||||
@@ -43,9 +43,14 @@ describe('mapWithConcurrency', () => {
|
||||
});
|
||||
|
||||
it('runs everything in one batch when concurrency >= length', async () => {
|
||||
let peak = 0, inFlight = 0;
|
||||
let peak = 0,
|
||||
inFlight = 0;
|
||||
const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => {
|
||||
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
inFlight--;
|
||||
return n;
|
||||
});
|
||||
expect(out).toEqual([1, 2, 3]);
|
||||
expect(peak).toBe(3);
|
||||
@@ -53,15 +58,23 @@ describe('mapWithConcurrency', () => {
|
||||
|
||||
it('returns [] for an empty input without calling fn', async () => {
|
||||
let called = 0;
|
||||
const out = await mapWithConcurrency([], 4, async (n) => { called++; return n; });
|
||||
const out = await mapWithConcurrency([], 4, async (n) => {
|
||||
called++;
|
||||
return n;
|
||||
});
|
||||
expect(out).toEqual([]);
|
||||
expect(called).toBe(0);
|
||||
});
|
||||
|
||||
it('treats concurrency < 1 as 1 (fully serial)', async () => {
|
||||
let peak = 0, inFlight = 0;
|
||||
let peak = 0,
|
||||
inFlight = 0;
|
||||
await mapWithConcurrency([1, 2, 3], 0, async (n) => {
|
||||
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
inFlight--;
|
||||
return n;
|
||||
});
|
||||
expect(peak).toBe(1);
|
||||
});
|
||||
|
||||
@@ -4,23 +4,31 @@ import { positiveIntEnv } from '../src/env';
|
||||
describe('positiveIntEnv', () => {
|
||||
it('returns the fallback when the variable is absent or blank', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(15);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(
|
||||
15,
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a positive integer and honors the max', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } })).toBe(2500);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } }),
|
||||
).toBe(2500);
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: '80' },
|
||||
})).toBe(80);
|
||||
}),
|
||||
).toBe(80);
|
||||
});
|
||||
|
||||
it('ignores zero, negatives, fractions, and values above the max', () => {
|
||||
for (const raw of ['0', '-5', '1.5', 'nope', '70000']) {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: raw },
|
||||
})).toBe(15);
|
||||
}),
|
||||
).toBe(15);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -28,8 +28,11 @@ let tmpDir: string;
|
||||
|
||||
function setEnv(env: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>): void {
|
||||
for (const [key, value] of Object.entries(env)) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +43,10 @@ function createTransport(policy?: LogStoragePolicy): FileTransport {
|
||||
}
|
||||
|
||||
function listLogFiles(dir: string): string[] {
|
||||
return fs.readdirSync(dir).filter((name) => name.endsWith('.log')).sort();
|
||||
return fs
|
||||
.readdirSync(dir)
|
||||
.filter((name) => name.endsWith('.log'))
|
||||
.sort();
|
||||
}
|
||||
|
||||
async function waitForLogFiles(dir: string, expected: string[]): Promise<void> {
|
||||
@@ -54,7 +60,10 @@ function silenceStderr(): ReturnType<typeof vi.spyOn> {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
for (const key of ENV_KEYS) savedEnv[key] = process.env[key];
|
||||
for (const key of ENV_KEYS) {
|
||||
savedEnv[key] = process.env[key];
|
||||
}
|
||||
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-common-log-'));
|
||||
setEnv({
|
||||
SNOWLUMA_LOG_DIR: tmpDir,
|
||||
@@ -69,10 +78,15 @@ beforeEach(() => {
|
||||
afterEach(async () => {
|
||||
await Promise.all(opened.splice(0).map((transport) => transport.close()));
|
||||
await _resetFileTransportForTesting();
|
||||
|
||||
for (const key of ENV_KEYS) {
|
||||
if (savedEnv[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = savedEnv[key];
|
||||
if (savedEnv[key] === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = savedEnv[key];
|
||||
}
|
||||
}
|
||||
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
@@ -87,11 +101,13 @@ describe('FileTransport environment and policy', () => {
|
||||
SNOWLUMA_LOG_FILE: '0',
|
||||
});
|
||||
|
||||
expect(createTransport({
|
||||
expect(
|
||||
createTransport({
|
||||
maxTotalMb: 3,
|
||||
retainDays: 0,
|
||||
perUinEnabled: true,
|
||||
}).getStorageStatus()).toEqual({
|
||||
}).getStorageStatus(),
|
||||
).toEqual({
|
||||
state: 'disabled',
|
||||
directory: tmpDir,
|
||||
totalBytes: 0,
|
||||
@@ -177,35 +193,47 @@ describe('FileTransport environment and policy', () => {
|
||||
|
||||
it('still validates SNOWLUMA_LOG_MAX_MB when a storage policy is supplied', () => {
|
||||
setEnv({ SNOWLUMA_LOG_MAX_MB: '0' });
|
||||
expect(() => new FileTransport({
|
||||
expect(
|
||||
() =>
|
||||
new FileTransport({
|
||||
maxTotalMb: 2,
|
||||
retainDays: 7,
|
||||
perUinEnabled: false,
|
||||
})).toThrow(new RangeError('SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591'));
|
||||
}),
|
||||
).toThrow(new RangeError('SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591'));
|
||||
});
|
||||
|
||||
it('rejects constructor policies before touching the log directory', () => {
|
||||
expect(() => new FileTransport({
|
||||
expect(
|
||||
() =>
|
||||
new FileTransport({
|
||||
maxTotalMb: 0,
|
||||
retainDays: 7,
|
||||
perUinEnabled: false,
|
||||
})).toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591'));
|
||||
expect(() => new FileTransport({
|
||||
}),
|
||||
).toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591'));
|
||||
expect(
|
||||
() =>
|
||||
new FileTransport({
|
||||
maxTotalMb: 2,
|
||||
retainDays: -1,
|
||||
perUinEnabled: false,
|
||||
})).toThrow(new RangeError('retainDays must be an integer in 0..104249991'));
|
||||
expect(() => new FileTransport({
|
||||
}),
|
||||
).toThrow(new RangeError('retainDays must be an integer in 0..104249991'));
|
||||
expect(
|
||||
() =>
|
||||
new FileTransport({
|
||||
maxTotalMb: 2,
|
||||
retainDays: 7,
|
||||
perUinEnabled: 'yes' as unknown as boolean,
|
||||
})).toThrow(new TypeError('perUinEnabled must be a boolean'));
|
||||
}),
|
||||
).toThrow(new TypeError('perUinEnabled must be a boolean'));
|
||||
expect(fs.readdirSync(tmpDir)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('FileTransport write, rotation, and paths', () => {
|
||||
it('creates today\'s shared file, appends a newline, and reports an exact healthy snapshot', async () => {
|
||||
it("creates today's shared file, appends a newline, and reports an exact healthy snapshot", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(2026, 6, 24, 15, 4, 5));
|
||||
const transport = createTransport();
|
||||
@@ -277,8 +305,9 @@ describe('FileTransport write, rotation, and paths', () => {
|
||||
second.write('z');
|
||||
await second.close();
|
||||
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8'))
|
||||
.toBe('0123456789hello\nz\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe(
|
||||
'0123456789hello\nz\n',
|
||||
);
|
||||
});
|
||||
|
||||
it('resumes the highest existing split index for the current day', async () => {
|
||||
@@ -291,8 +320,12 @@ describe('FileTransport write, rotation, and paths', () => {
|
||||
transport.write('two');
|
||||
await transport.close();
|
||||
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe('base\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'utf8')).toBe('one\ntwo\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe(
|
||||
'base\n',
|
||||
);
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'utf8')).toBe(
|
||||
'one\ntwo\n',
|
||||
);
|
||||
});
|
||||
|
||||
it('skips an already-present next split when rotating by size', async () => {
|
||||
@@ -317,8 +350,9 @@ describe('FileTransport write, rotation, and paths', () => {
|
||||
'snowluma-2026-07-24.2.log',
|
||||
'snowluma-2026-07-24.log',
|
||||
]);
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.2.log'), 'utf8'))
|
||||
.toBe('overflow\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.2.log'), 'utf8')).toBe(
|
||||
'overflow\n',
|
||||
);
|
||||
});
|
||||
|
||||
it('lets a first line exceed the per-file cap and only rotates on the next write', async () => {
|
||||
@@ -353,8 +387,12 @@ describe('FileTransport write, rotation, and paths', () => {
|
||||
'snowluma-2026-05-18.log',
|
||||
'snowluma-2026-05-19.log',
|
||||
]);
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-18.log'), 'utf8')).toBe('day-one\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-19.log'), 'utf8')).toBe('day-two\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-18.log'), 'utf8')).toBe(
|
||||
'day-one\n',
|
||||
);
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-19.log'), 'utf8')).toBe(
|
||||
'day-two\n',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -369,7 +407,10 @@ describe('FileTransport retention, listing, and quota', () => {
|
||||
);
|
||||
fs.mkdirSync(path.join(tmpDir, '10001'));
|
||||
fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'stale-root\n');
|
||||
fs.writeFileSync(path.join(tmpDir, '10001', 'snowluma-2020-01-01.2.log'), 'stale-account\n');
|
||||
fs.writeFileSync(
|
||||
path.join(tmpDir, '10001', 'snowluma-2020-01-01.2.log'),
|
||||
'stale-account\n',
|
||||
);
|
||||
|
||||
const transport = createTransport();
|
||||
await transport.close();
|
||||
@@ -378,10 +419,9 @@ describe('FileTransport retention, listing, and quota', () => {
|
||||
expect(fs.existsSync(path.join(tmpDir, '10001', 'snowluma-2020-01-01.2.log'))).toBe(false);
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'keep.txt'), 'utf8')).toBe('keep\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-nope.log'), 'utf8')).toBe('unmanaged\n');
|
||||
expect(fs.readFileSync(
|
||||
path.join(tmpDir, 'not-an-account', 'snowluma-2020-01-01.log'),
|
||||
'utf8',
|
||||
)).toBe('ignored\n');
|
||||
expect(
|
||||
fs.readFileSync(path.join(tmpDir, 'not-an-account', 'snowluma-2020-01-01.log'), 'utf8'),
|
||||
).toBe('ignored\n');
|
||||
});
|
||||
|
||||
it('keeps files inside the retention window and skips date cleanup when retainDays is 0', async () => {
|
||||
@@ -452,11 +492,13 @@ describe('FileTransport retention, listing, and quota', () => {
|
||||
fs.utimesSync(newer, new Date('2026-07-24T02:00:00Z'), new Date('2026-07-24T02:00:00Z'));
|
||||
|
||||
const transport = createTransport();
|
||||
expect(await transport.updatePolicy({
|
||||
expect(
|
||||
await transport.updatePolicy({
|
||||
maxTotalMb: 1,
|
||||
retainDays: 0,
|
||||
perUinEnabled: false,
|
||||
})).toMatchObject({
|
||||
}),
|
||||
).toMatchObject({
|
||||
state: 'healthy',
|
||||
maxTotalBytes: 1_048_576,
|
||||
totalBytes: 716_800,
|
||||
@@ -471,8 +513,14 @@ describe('FileTransport retention, listing, and quota', () => {
|
||||
const stderr = silenceStderr();
|
||||
const transport = createTransport();
|
||||
const kib = 'x'.repeat(1023);
|
||||
for (let i = 0; i < 1024; i += 1) transport.write(kib);
|
||||
for (let i = 0; i < 10; i += 1) transport.write('dropped');
|
||||
|
||||
for (let i = 0; i < 1024; i += 1) {
|
||||
transport.write(kib);
|
||||
}
|
||||
|
||||
for (let i = 0; i < 10; i += 1) {
|
||||
transport.write('dropped');
|
||||
}
|
||||
|
||||
expect(transport.getStorageStatus()).toMatchObject({
|
||||
state: 'degraded',
|
||||
@@ -495,7 +543,11 @@ describe('FileTransport retention, listing, and quota', () => {
|
||||
silenceStderr();
|
||||
const transport = createTransport();
|
||||
const kib = 'x'.repeat(1023);
|
||||
for (let i = 0; i < 1024; i += 1) transport.write(kib);
|
||||
|
||||
for (let i = 0; i < 1024; i += 1) {
|
||||
transport.write(kib);
|
||||
}
|
||||
|
||||
transport.write('overflow', 12345);
|
||||
|
||||
expect(transport.perUinPath(12345)).toBeNull();
|
||||
@@ -511,6 +563,7 @@ describe('FileTransport retention, listing, and quota', () => {
|
||||
if (path.resolve(String(filePath)) === stalePath) {
|
||||
throw new Error('permission denied');
|
||||
}
|
||||
|
||||
realUnlink(filePath);
|
||||
});
|
||||
silenceStderr();
|
||||
@@ -535,10 +588,12 @@ describe('FileTransport per-UIN writers', () => {
|
||||
transport.write('both', 12345);
|
||||
await transport.close();
|
||||
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8'))
|
||||
.toBe('shared-only\nboth\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, '12345', 'snowluma-2026-07-24.log'), 'utf8'))
|
||||
.toBe('both\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe(
|
||||
'shared-only\nboth\n',
|
||||
);
|
||||
expect(fs.readFileSync(path.join(tmpDir, '12345', 'snowluma-2026-07-24.log'), 'utf8')).toBe(
|
||||
'both\n',
|
||||
);
|
||||
});
|
||||
|
||||
it('does not create an account directory when the account path is already a file', async () => {
|
||||
@@ -553,7 +608,9 @@ describe('FileTransport per-UIN writers', () => {
|
||||
|
||||
expect(transport.perUinPath(12345)).toBeNull();
|
||||
expect(fs.statSync(path.join(tmpDir, '12345')).isFile()).toBe(true);
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe('shared-ok\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe(
|
||||
'shared-ok\n',
|
||||
);
|
||||
});
|
||||
|
||||
it('rolls per-UIN files on day change and stops creating them after the policy turns off', async () => {
|
||||
@@ -578,8 +635,9 @@ describe('FileTransport per-UIN writers', () => {
|
||||
await transport.close();
|
||||
|
||||
expect(fs.existsSync(path.join(tmpDir, '99', 'snowluma-2026-07-25.log'))).toBe(false);
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-25.log'), 'utf8'))
|
||||
.toBe('day-two\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-25.log'), 'utf8')).toBe(
|
||||
'day-two\n',
|
||||
);
|
||||
expect(transport.getStorageStatus().perUinEnabled).toBe(false);
|
||||
});
|
||||
|
||||
@@ -598,8 +656,9 @@ describe('FileTransport per-UIN writers', () => {
|
||||
transport.write('after', 55);
|
||||
await transport.close();
|
||||
|
||||
expect(fs.readFileSync(path.join(tmpDir, '55', 'snowluma-2026-07-24.log'), 'utf8'))
|
||||
.toBe('after\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, '55', 'snowluma-2026-07-24.log'), 'utf8')).toBe(
|
||||
'after\n',
|
||||
);
|
||||
});
|
||||
|
||||
it('replaces a disabled per-UIN writer on the next line for that account', async () => {
|
||||
@@ -610,9 +669,11 @@ describe('FileTransport per-UIN writers', () => {
|
||||
const accountStreams: fs.WriteStream[] = [];
|
||||
vi.spyOn(fs, 'createWriteStream').mockImplementation((file, options) => {
|
||||
const stream = realCreate(file, options);
|
||||
|
||||
if (String(file).startsWith(path.join(tmpDir, '77') + path.sep)) {
|
||||
accountStreams.push(stream);
|
||||
}
|
||||
|
||||
return stream;
|
||||
});
|
||||
silenceStderr();
|
||||
@@ -648,8 +709,9 @@ describe('FileTransport initialization, recovery, and policy updates', () => {
|
||||
fileCount: 0,
|
||||
droppedLines: 0,
|
||||
});
|
||||
expect(transport.getStorageStatus().lastError)
|
||||
.toMatch(/^failed to initialize log storage /);
|
||||
expect(transport.getStorageStatus().lastError).toMatch(
|
||||
/^failed to initialize log storage /,
|
||||
);
|
||||
expect(String(stderr.mock.calls[0]![0])).toContain('[logger.storage]');
|
||||
await transport.close();
|
||||
});
|
||||
@@ -661,6 +723,7 @@ describe('FileTransport initialization, recovery, and policy updates', () => {
|
||||
if (path.resolve(String(dir)) === path.join(tmpDir, '12345')) {
|
||||
throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' });
|
||||
}
|
||||
|
||||
return realReaddir(dir, options as Parameters<typeof realReaddir>[1]);
|
||||
});
|
||||
silenceStderr();
|
||||
@@ -693,8 +756,9 @@ describe('FileTransport initialization, recovery, and policy updates', () => {
|
||||
transport.write('recovered');
|
||||
await transport.close();
|
||||
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8'))
|
||||
.toBe('recovered\n');
|
||||
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe(
|
||||
'recovered\n',
|
||||
);
|
||||
});
|
||||
|
||||
it('does not persist lines during the quota retry window after a stream error', async () => {
|
||||
@@ -760,11 +824,13 @@ describe('FileTransport initialization, recovery, and policy updates', () => {
|
||||
});
|
||||
silenceStderr();
|
||||
|
||||
await expect(transport.updatePolicy({
|
||||
await expect(
|
||||
transport.updatePolicy({
|
||||
maxTotalMb: 4,
|
||||
retainDays: 1,
|
||||
perUinEnabled: true,
|
||||
})).rejects.toThrow(/failed to read managed log directory/);
|
||||
}),
|
||||
).rejects.toThrow(/failed to read managed log directory/);
|
||||
|
||||
expect(transport.getStorageStatus()).toMatchObject({
|
||||
state: 'degraded',
|
||||
@@ -800,16 +866,20 @@ describe('FileTransport initialization, recovery, and policy updates', () => {
|
||||
|
||||
it('rejects an unsafe updatePolicy without changing the live limits', async () => {
|
||||
const transport = createTransport();
|
||||
await expect(transport.updatePolicy({
|
||||
await expect(
|
||||
transport.updatePolicy({
|
||||
maxTotalMb: 9_007_199_254_740_991,
|
||||
retainDays: 7,
|
||||
perUinEnabled: false,
|
||||
})).rejects.toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591'));
|
||||
await expect(transport.updatePolicy({
|
||||
}),
|
||||
).rejects.toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591'));
|
||||
await expect(
|
||||
transport.updatePolicy({
|
||||
maxTotalMb: 2,
|
||||
retainDays: 9_007_199_254_740_991,
|
||||
perUinEnabled: false,
|
||||
})).rejects.toThrow(new RangeError('retainDays must be an integer in 0..104249991'));
|
||||
}),
|
||||
).rejects.toThrow(new RangeError('retainDays must be an integer in 0..104249991'));
|
||||
expect(transport.getStorageStatus()).toMatchObject({
|
||||
maxTotalBytes: 2_097_152,
|
||||
retainDays: 7,
|
||||
@@ -871,10 +941,12 @@ describe('FileTransport.clearManagedLogs', () => {
|
||||
const result = await transport.clearManagedLogs();
|
||||
expect(result.deletedFiles).toBe(0);
|
||||
expect(result.freedBytes).toBe(0);
|
||||
expect(result.failures).toEqual([{
|
||||
expect(result.failures).toEqual([
|
||||
{
|
||||
file: '.',
|
||||
message: expect.stringContaining(`failed to clear disabled log storage ${blocked}`),
|
||||
}]);
|
||||
},
|
||||
]);
|
||||
expect(result.status).toMatchObject({
|
||||
state: 'disabled',
|
||||
directory: blocked,
|
||||
@@ -908,10 +980,12 @@ describe('FileTransport.clearManagedLogs', () => {
|
||||
|
||||
const result = await transport.clearManagedLogs();
|
||||
expect(result.deletedFiles).toBe(1);
|
||||
expect(result.failures).toEqual([{
|
||||
expect(result.failures).toEqual([
|
||||
{
|
||||
file: '.',
|
||||
message: expect.stringMatching(/^failed to initialize log storage /),
|
||||
}]);
|
||||
},
|
||||
]);
|
||||
expect(transport.currentPath).toBeNull();
|
||||
});
|
||||
|
||||
@@ -925,15 +999,18 @@ describe('FileTransport.clearManagedLogs', () => {
|
||||
if (String(file).startsWith(accountPrefix)) {
|
||||
throw new Error('account reopen failed');
|
||||
}
|
||||
|
||||
return realCreate(file, options);
|
||||
});
|
||||
silenceStderr();
|
||||
|
||||
const result = await transport.clearManagedLogs();
|
||||
expect(result.failures).toEqual([{
|
||||
expect(result.failures).toEqual([
|
||||
{
|
||||
file: '12345',
|
||||
message: `failed to reopen account log writer: failed to prepare log writer in ${path.join(tmpDir, '12345')}`,
|
||||
}]);
|
||||
},
|
||||
]);
|
||||
expect(transport.currentPath).not.toBeNull();
|
||||
expect(transport.perUinPath(12345)).toBeNull();
|
||||
});
|
||||
@@ -949,10 +1026,12 @@ describe('FileTransport.clearManagedLogs', () => {
|
||||
expect(result).toMatchObject({
|
||||
deletedFiles: 0,
|
||||
freedBytes: 0,
|
||||
failures: [{
|
||||
failures: [
|
||||
{
|
||||
file: '.',
|
||||
message: expect.stringMatching(/^failed to initialize log storage /),
|
||||
}],
|
||||
},
|
||||
],
|
||||
status: { state: 'disabled', directory: blocked },
|
||||
});
|
||||
});
|
||||
@@ -1007,11 +1086,13 @@ describe('file-transport singleton', () => {
|
||||
perUinEnabled: true,
|
||||
});
|
||||
|
||||
await expect(configureFileTransport({
|
||||
await expect(
|
||||
configureFileTransport({
|
||||
maxTotalMb: 0,
|
||||
retainDays: 2,
|
||||
perUinEnabled: true,
|
||||
})).rejects.toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591'));
|
||||
}),
|
||||
).rejects.toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591'));
|
||||
expect(getLogStorageStatus().maxTotalBytes).toBe(5_242_880);
|
||||
});
|
||||
|
||||
|
||||
@@ -7,9 +7,9 @@ describe('sanitizeLogLine', () => {
|
||||
});
|
||||
|
||||
it('removes OSC hyperlinks without removing their visible label', () => {
|
||||
expect(
|
||||
sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07'),
|
||||
).toBe('visible');
|
||||
expect(sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07')).toBe(
|
||||
'visible',
|
||||
);
|
||||
});
|
||||
|
||||
it('removes terminal control-string payloads', () => {
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
redactLogMessage,
|
||||
renderParamsVerbose,
|
||||
summarizeParams,
|
||||
} from '../src/log-summary';
|
||||
import { redactLogMessage, renderParamsVerbose, summarizeParams } from '../src/log-summary';
|
||||
|
||||
describe('summarizeParams', () => {
|
||||
it('renders null/undefined as {}', () => {
|
||||
@@ -22,10 +18,10 @@ describe('summarizeParams', () => {
|
||||
});
|
||||
|
||||
it('quotes string fields, collapses nested values, truncates long strings', () => {
|
||||
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] }))
|
||||
.toBe('a=1 b="x" c={...} e=[len=2]');
|
||||
expect(summarizeParams({ s: 'x'.repeat(50) }))
|
||||
.toBe(`s="${'x'.repeat(40)}..."`);
|
||||
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] })).toBe(
|
||||
'a=1 b="x" c={...} e=[len=2]',
|
||||
);
|
||||
expect(summarizeParams({ s: 'x'.repeat(50) })).toBe(`s="${'x'.repeat(40)}..."`);
|
||||
});
|
||||
|
||||
it('redacts authentication fields without exposing their values', () => {
|
||||
@@ -50,18 +46,22 @@ describe('summarizeParams', () => {
|
||||
});
|
||||
|
||||
it('does not treat sensitive substrings inside ordinary keys as credentials', () => {
|
||||
expect(summarizeParams({
|
||||
expect(
|
||||
summarizeParams({
|
||||
retoken: 'visible',
|
||||
cookietown: 'visible',
|
||||
myauthorization: 'visible',
|
||||
})).toBe(
|
||||
'retoken="visible" cookietown="visible" myauthorization="visible"',
|
||||
);
|
||||
}),
|
||||
).toBe('retoken="visible" cookietown="visible" myauthorization="visible"');
|
||||
});
|
||||
|
||||
it('caps total output and appends "..." on overflow', () => {
|
||||
const big: Record<string, number> = {};
|
||||
for (let i = 0; i < 60; i++) big['key' + i] = i;
|
||||
|
||||
for (let i = 0; i < 60; i++) {
|
||||
big['key' + i] = i;
|
||||
}
|
||||
|
||||
const out = summarizeParams(big);
|
||||
expect(out.startsWith('key0=0')).toBe(true);
|
||||
expect(out.endsWith('...')).toBe(true);
|
||||
@@ -87,9 +87,7 @@ describe('redactLogMessage', () => {
|
||||
'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required',
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
'password=*** Authorization: *** cookie=*** password change required',
|
||||
);
|
||||
expect(out).toBe('password=*** Authorization: *** cookie=*** password change required');
|
||||
});
|
||||
|
||||
it('redacts quoted object keys, Basic auth, and complete Cookie values', () => {
|
||||
@@ -110,15 +108,13 @@ describe('redactLogMessage', () => {
|
||||
|
||||
it('redacts complete multi-parameter Authorization values', () => {
|
||||
const out = redactLogMessage(
|
||||
'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n'
|
||||
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, '
|
||||
+ 'SignedHeaders=host;x-date, Signature=aws-secret\n'
|
||||
+ 'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/',
|
||||
'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n' +
|
||||
'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, ' +
|
||||
'SignedHeaders=host;x-date, Signature=aws-secret\n' +
|
||||
'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/',
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
'Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***',
|
||||
);
|
||||
expect(out).toBe('Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***');
|
||||
expect(out).not.toMatch(
|
||||
/alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/,
|
||||
);
|
||||
@@ -129,40 +125,37 @@ describe('redactLogMessage', () => {
|
||||
`authToken=auth-secret idToken=id-secret clientSecret=client-secret {"userPassword":"password-secret"}`,
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
`authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`,
|
||||
);
|
||||
expect(out).not.toMatch(
|
||||
/auth-secret|id-secret|client-secret|password-secret/,
|
||||
);
|
||||
expect(redactLogMessage(
|
||||
expect(out).toBe(`authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`);
|
||||
expect(out).not.toMatch(/auth-secret|id-secret|client-secret|password-secret/);
|
||||
expect(redactLogMessage('retoken=value cookietown=value myauthorization=value')).toBe(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
)).toBe('retoken=value cookietown=value myauthorization=value');
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts leading separator and numeric authentication keys without matching larger words', () => {
|
||||
expect(redactLogMessage(
|
||||
expect(
|
||||
redactLogMessage(
|
||||
'_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible',
|
||||
)).toBe('_token=*** --password=*** 2faToken=*** retoken=visible');
|
||||
),
|
||||
).toBe('_token=*** --password=*** 2faToken=*** retoken=visible');
|
||||
});
|
||||
|
||||
it('redacts nested assignments inside non-sensitive wrapper values', () => {
|
||||
expect(redactLogMessage(
|
||||
'params=authToken=auth-secret params=cookie="cookie-secret"',
|
||||
)).toBe('params=authToken=*** params=cookie=***');
|
||||
expect(redactLogMessage('params=authToken=auth-secret params=cookie="cookie-secret"')).toBe(
|
||||
'params=authToken=*** params=cookie=***',
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts the entire Authorization value when it starts with a marker', () => {
|
||||
expect(redactLogMessage('Authorization: *** secret-value'))
|
||||
.toBe('Authorization: ***');
|
||||
expect(redactLogMessage('Authorization: *** secret-value')).toBe('Authorization: ***');
|
||||
});
|
||||
|
||||
it('redacts property paths and URL query authentication values', () => {
|
||||
const out = redactLogMessage(
|
||||
'headers.authorization=Basic dXNlcjpwYXNz '
|
||||
+ 'request.token=plain-token '
|
||||
+ 'GET /callback?access_token=query-secret&x=1 '
|
||||
+ 'url=https://host/?api_key=url-secret',
|
||||
'headers.authorization=Basic dXNlcjpwYXNz ' +
|
||||
'request.token=plain-token ' +
|
||||
'GET /callback?access_token=query-secret&x=1 ' +
|
||||
'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
|
||||
expect(out).toContain('headers.authorization=***');
|
||||
@@ -174,19 +167,21 @@ describe('redactLogMessage', () => {
|
||||
|
||||
it('redacts prefixed authentication keys without matching larger words', () => {
|
||||
const redacted = redactLogMessage(
|
||||
'x-api-key=api-secret user_password=password-secret '
|
||||
+ 'headers.authorization=Basic auth-secret '
|
||||
+ 'x-cookie="session=cookie-secret"; Path=/; HttpOnly',
|
||||
'x-api-key=api-secret user_password=password-secret ' +
|
||||
'headers.authorization=Basic auth-secret ' +
|
||||
'x-cookie="session=cookie-secret"; Path=/; HttpOnly',
|
||||
);
|
||||
|
||||
expect(redacted).toContain('x-api-key=***');
|
||||
expect(redacted).toContain('user_password=***');
|
||||
expect(redacted).toContain('headers.authorization=***');
|
||||
expect(redacted).toContain('x-cookie=***');
|
||||
expect(redacted).not.toMatch(/api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/);
|
||||
expect(redactLogMessage(
|
||||
expect(redacted).not.toMatch(
|
||||
/api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/,
|
||||
);
|
||||
expect(redactLogMessage('retoken=value cookietown=value myauthorization=value')).toBe(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
)).toBe('retoken=value cookietown=value myauthorization=value');
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -224,8 +219,9 @@ describe('renderParamsVerbose', () => {
|
||||
it('renders shared non-cyclic references in every branch', () => {
|
||||
const shared = { value: 1 };
|
||||
|
||||
expect(renderParamsVerbose({ left: shared, right: shared }))
|
||||
.toBe('{left:{value:1},right:{value:1}}');
|
||||
expect(renderParamsVerbose({ left: shared, right: shared })).toBe(
|
||||
'{left:{value:1},right:{value:1}}',
|
||||
);
|
||||
});
|
||||
|
||||
it('renders nested structure with primitives intact', () => {
|
||||
|
||||
@@ -18,11 +18,7 @@ vi.mock('../src/log-file-transport', () => ({
|
||||
getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }),
|
||||
}));
|
||||
|
||||
import {
|
||||
createLogger,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '../src/logger';
|
||||
import { createLogger, subscribeLogs, type LogEntry } from '../src/logger';
|
||||
|
||||
// Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp
|
||||
// shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored
|
||||
@@ -44,8 +40,13 @@ describe('logger UIN slot padding', () => {
|
||||
|
||||
afterEach(() => {
|
||||
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
|
||||
if (prevNoColor === undefined) delete process.env.NO_COLOR;
|
||||
else process.env.NO_COLOR = prevNoColor;
|
||||
|
||||
if (prevNoColor === undefined) {
|
||||
delete process.env.NO_COLOR;
|
||||
} else {
|
||||
process.env.NO_COLOR = prevNoColor;
|
||||
}
|
||||
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
@@ -85,25 +86,40 @@ describe('logger UIN slot padding', () => {
|
||||
const SAVED_FILE_LEVEL = externalFileLevel;
|
||||
|
||||
async function loadLoggerForFileLevel(level?: string) {
|
||||
if (level === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_FILE_LEVEL = level;
|
||||
if (level === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = level;
|
||||
}
|
||||
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
return import('../src/logger');
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
if (SAVED_FILE_LEVEL === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
}
|
||||
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
if (externalLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel;
|
||||
if (SAVED_FILE_LEVEL === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
}
|
||||
|
||||
if (externalLogLevel === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel;
|
||||
}
|
||||
});
|
||||
|
||||
describe('file output gating', () => {
|
||||
@@ -129,7 +145,9 @@ describe('file output gating', () => {
|
||||
log.warn('warn');
|
||||
log.error('error');
|
||||
|
||||
const messages = fileWriteSpy.mock.calls.map(([line]) => String(line).split('] ').at(-1));
|
||||
const messages = fileWriteSpy.mock.calls.map(([line]) =>
|
||||
String(line).split('] ').at(-1),
|
||||
);
|
||||
expect(messages).toEqual(testCase.expected);
|
||||
});
|
||||
}
|
||||
@@ -218,17 +236,17 @@ describe('file output gating', () => {
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
log.info(
|
||||
'headers.authorization=Basic dotted-auth request.token=dotted-token '
|
||||
+ 'GET /callback?access_token=query-secret&x=1 '
|
||||
+ 'url=https://host/?api_key=url-secret',
|
||||
'headers.authorization=Basic dotted-auth request.token=dotted-token ' +
|
||||
'GET /callback?access_token=query-secret&x=1 ' +
|
||||
'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
log.info(
|
||||
'Authorization: Digest username="alice", response="digest-secret"\n'
|
||||
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret',
|
||||
'Authorization: Digest username="alice", response="digest-secret"\n' +
|
||||
'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret',
|
||||
);
|
||||
log.info(
|
||||
'authToken=camel-auth idToken=camel-id clientSecret=camel-client '
|
||||
+ `json={"userPassword":"camel-password"}`,
|
||||
'authToken=camel-auth idToken=camel-id clientSecret=camel-client ' +
|
||||
`json={"userPassword":"camel-password"}`,
|
||||
);
|
||||
log.info('_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret');
|
||||
log.info('Authorization: *** marker-secret');
|
||||
@@ -261,7 +279,8 @@ describe('file output gating', () => {
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|camel-auth|camel-id|camel-client|camel-password|underscore-secret|cli-secret|two-factor-secret|marker-secret/,
|
||||
);
|
||||
|
||||
const trace = entries.filter((entry) => entry.level === 'trace')
|
||||
const trace = entries
|
||||
.filter((entry) => entry.level === 'trace')
|
||||
.map((entry) => entry.message)
|
||||
.join('\n');
|
||||
expect(trace).toContain('trace-password');
|
||||
@@ -286,9 +305,7 @@ describe('file output gating', () => {
|
||||
log.trace('trace-hex=001122aabbcc');
|
||||
log.warn('normal-after');
|
||||
|
||||
expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual([
|
||||
'normal-after',
|
||||
]);
|
||||
expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual(['normal-after']);
|
||||
expect(fresh.getLogSnapshot().map((entry) => entry.message)).toEqual([
|
||||
'normal-before',
|
||||
'trace-hex=001122aabbcc',
|
||||
|
||||
@@ -18,7 +18,8 @@ describe('normalizeRuntimeConfig', () => {
|
||||
});
|
||||
|
||||
it('passes through valid values', () => {
|
||||
expect(normalizeRuntimeConfig({
|
||||
expect(
|
||||
normalizeRuntimeConfig({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
@@ -27,7 +28,8 @@ describe('normalizeRuntimeConfig', () => {
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
})).toEqual({
|
||||
}),
|
||||
).toEqual({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
@@ -53,22 +55,22 @@ describe('normalizeRuntimeConfig', () => {
|
||||
});
|
||||
|
||||
it('fails fast on invalid persisted log settings', () => {
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 }))
|
||||
.toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: -1 }))
|
||||
.toThrow(/logRetainDays/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' }))
|
||||
.toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: '' }))
|
||||
.toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER }))
|
||||
.toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER }))
|
||||
.toThrow(/logRetainDays/);
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 })).toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: -1 })).toThrow(/logRetainDays/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' })).toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: '' })).toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER })).toThrow(
|
||||
/logMaxTotalMb/,
|
||||
);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER })).toThrow(
|
||||
/logRetainDays/,
|
||||
);
|
||||
});
|
||||
|
||||
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
|
||||
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true });
|
||||
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({
|
||||
enabled: true,
|
||||
});
|
||||
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('127.0.0.1');
|
||||
});
|
||||
|
||||
@@ -84,19 +86,23 @@ describe('resolveRuntimeEnvOverrides', () => {
|
||||
});
|
||||
|
||||
it('parses port / host / trustProxy from env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({
|
||||
expect(
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_WEBUI_PORT: '6700',
|
||||
SNOWLUMA_WEBUI_HOST: '127.0.0.1',
|
||||
SNOWLUMA_WEBUI_TRUST_PROXY: '1',
|
||||
})).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
|
||||
}),
|
||||
).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
|
||||
});
|
||||
|
||||
it('parses log storage overrides including retainDays=0', () => {
|
||||
expect(resolveRuntimeEnvOverrides({
|
||||
expect(
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '4096',
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '0',
|
||||
SNOWLUMA_LOG_PER_UIN: '1',
|
||||
})).toEqual({
|
||||
}),
|
||||
).toEqual({
|
||||
logMaxTotalMb: 4096,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
@@ -104,24 +110,34 @@ describe('resolveRuntimeEnvOverrides', () => {
|
||||
});
|
||||
|
||||
it('fails fast on invalid log storage overrides', () => {
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '0',
|
||||
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '-1',
|
||||
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_PER_UIN: 'maybe',
|
||||
})).toThrow(/SNOWLUMA_LOG_PER_UIN/);
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_PER_UIN/);
|
||||
});
|
||||
|
||||
it('fails fast when converted log storage overrides would be unsafe', () => {
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER),
|
||||
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER),
|
||||
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
});
|
||||
|
||||
it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => {
|
||||
@@ -131,8 +147,9 @@ describe('resolveRuntimeEnvOverrides', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({
|
||||
webuiTls: { enabled: false },
|
||||
});
|
||||
expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' }))
|
||||
.toThrow(/SNOWLUMA_WEBUI_TLS/);
|
||||
expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' })).toThrow(
|
||||
/SNOWLUMA_WEBUI_TLS/,
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores an out-of-range / non-numeric port env', () => {
|
||||
@@ -141,7 +158,9 @@ describe('resolveRuntimeEnvOverrides', () => {
|
||||
});
|
||||
|
||||
it('treats trustProxy="0"/"off" as a real override (not absent)', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' });
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({
|
||||
trustProxy: '0',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -150,7 +169,9 @@ describe('updateRuntimeConfig (fs)', () => {
|
||||
let dir: string;
|
||||
let prevPortEnv: string | undefined;
|
||||
beforeEach(async () => {
|
||||
const fs = await import('fs'); const os = await import('os'); const path = await import('path');
|
||||
const fs = await import('fs');
|
||||
const os = await import('os');
|
||||
const path = await import('path');
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-'));
|
||||
prevCwd = process.cwd();
|
||||
process.chdir(dir);
|
||||
@@ -159,15 +180,21 @@ describe('updateRuntimeConfig (fs)', () => {
|
||||
});
|
||||
afterEach(async () => {
|
||||
process.chdir(prevCwd);
|
||||
if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
|
||||
|
||||
if (prevPortEnv === undefined) {
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
} else {
|
||||
process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
|
||||
}
|
||||
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('merges a patch over on-disk values and persists normalized', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
const fs = await import('fs');
|
||||
const path = await import('path');
|
||||
const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } });
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: true });
|
||||
@@ -178,7 +205,8 @@ describe('updateRuntimeConfig (fs)', () => {
|
||||
|
||||
it('does NOT bake an env-overridden port into the persisted file', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
const fs = await import('fs');
|
||||
const path = await import('path');
|
||||
process.env.SNOWLUMA_WEBUI_PORT = '9999';
|
||||
updateRuntimeConfig({ webuiHost: '127.0.0.1' });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
@@ -194,8 +222,7 @@ describe('updateRuntimeConfig (fs)', () => {
|
||||
throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' });
|
||||
});
|
||||
|
||||
expect(() => updateRuntimeConfig({ logRetainDays: 0 }))
|
||||
.toThrow(/disk replacement failed/);
|
||||
expect(() => updateRuntimeConfig({ logRetainDays: 0 })).toThrow(/disk replacement failed/);
|
||||
expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before);
|
||||
expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -5,7 +5,10 @@ import { createSingleFlightCache } from '../src/single-flight-cache';
|
||||
function deferred<T>() {
|
||||
let resolve!: (v: T) => void;
|
||||
let reject!: (e: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
@@ -13,7 +16,11 @@ describe('SingleFlightCache', () => {
|
||||
it('caches within the TTL and reloads once expired', async () => {
|
||||
let clock = 1000;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 100, load, now: () => clock });
|
||||
const cache = createSingleFlightCache<string, string>({
|
||||
ttlMs: 100,
|
||||
load,
|
||||
now: () => clock,
|
||||
});
|
||||
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
clock = 1050; // still fresh (< 100)
|
||||
@@ -51,7 +58,11 @@ describe('SingleFlightCache', () => {
|
||||
it('force bypasses the freshness check but still joins an in-flight load', async () => {
|
||||
let clock = 0;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load, now: () => clock });
|
||||
const cache = createSingleFlightCache<string, string>({
|
||||
ttlMs: 10_000,
|
||||
load,
|
||||
now: () => clock,
|
||||
});
|
||||
|
||||
expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh
|
||||
clock = 5; // still fresh
|
||||
@@ -71,7 +82,11 @@ describe('SingleFlightCache', () => {
|
||||
it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => {
|
||||
let n = 0;
|
||||
const load = vi.fn(async () => ({ error: true as boolean, n: ++n }));
|
||||
const cache = createSingleFlightCache({ ttlMs: 10_000, load, shouldCache: (v) => !v.error });
|
||||
const cache = createSingleFlightCache({
|
||||
ttlMs: 10_000,
|
||||
load,
|
||||
shouldCache: (v) => !v.error,
|
||||
});
|
||||
|
||||
// concurrent callers still share one load...
|
||||
const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]);
|
||||
@@ -95,7 +110,11 @@ describe('SingleFlightCache', () => {
|
||||
let attempt = 0;
|
||||
const load = vi.fn(async () => {
|
||||
attempt++;
|
||||
if (attempt === 1) throw new Error('boom');
|
||||
|
||||
if (attempt === 1) {
|
||||
throw new Error('boom');
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
});
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
|
||||
@@ -20,8 +20,7 @@ afterEach(() => {
|
||||
describe('TRACE diagnostics contract', () => {
|
||||
it('renders every byte as continuous lowercase hexadecimal', () => {
|
||||
expect(renderTraceBytes(new Uint8Array())).toBe('');
|
||||
expect(renderTraceBytes(new Uint8Array([0x00, 0x01, 0x0f, 0x10, 0xff])))
|
||||
.toBe('00010f10ff');
|
||||
expect(renderTraceBytes(new Uint8Array([0x00, 0x01, 0x0f, 0x10, 0xff]))).toBe('00010f10ff');
|
||||
});
|
||||
|
||||
it('renders only the addressed Uint8Array view', () => {
|
||||
@@ -51,7 +50,8 @@ describe('TRACE diagnostics contract', () => {
|
||||
expect(afterDisabled).toBe(beforeDisabled + 1);
|
||||
|
||||
setLogLevel('trace');
|
||||
const observeContext = () => runWithTraceRequest(async () => {
|
||||
const observeContext = () =>
|
||||
runWithTraceRequest(async () => {
|
||||
const before = currentRequestId();
|
||||
await Promise.resolve();
|
||||
const after = currentRequestId();
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
|
||||
import {
|
||||
getCollectionList,
|
||||
type CollectionListResult,
|
||||
} from '@snowluma/protocol/web/collection';
|
||||
import { getCollectionList, type CollectionListResult } from '@snowluma/protocol/web/collection';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
const COLLECTION_DOMAIN = 'weiyun.com';
|
||||
@@ -16,7 +13,10 @@ export class CollectionApi {
|
||||
domainList: [COLLECTION_DOMAIN],
|
||||
});
|
||||
const pskey = domainPskeyMap.get(COLLECTION_DOMAIN);
|
||||
if (!pskey) throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
|
||||
|
||||
if (!pskey) {
|
||||
throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
|
||||
}
|
||||
|
||||
return getCollectionList({
|
||||
uin: this.ctx.identity.uin,
|
||||
|
||||
@@ -25,11 +25,17 @@ 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 { SendTuwenArk, type SendTuwenArkParams } from '@snowluma/protocol/oidb-services/contacts/send-tuwen-ark';
|
||||
import {
|
||||
SendTuwenArk,
|
||||
type SendTuwenArkParams,
|
||||
} from '@snowluma/protocol/oidb-services/contacts/send-tuwen-ark';
|
||||
import { SetFriendCategory } from '@snowluma/protocol/oidb-services/contacts/set-friend-category';
|
||||
import { toHex } from '@snowluma/common/hex';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache';
|
||||
import {
|
||||
createSingleFlightCache,
|
||||
type SingleFlightCache,
|
||||
} from '@snowluma/common/single-flight-cache';
|
||||
import type {
|
||||
FriendCategoryInfo,
|
||||
FriendInfo,
|
||||
@@ -62,9 +68,11 @@ export interface SetFriendCategoryParams {
|
||||
}
|
||||
|
||||
export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boolean {
|
||||
return Number.isInteger(uin)
|
||||
&& uin > 0
|
||||
&& ranges.some(({ minUin, maxUin }) => uin >= minUin && uin <= maxUin);
|
||||
return (
|
||||
Number.isInteger(uin) &&
|
||||
uin > 0 &&
|
||||
ranges.some(({ minUin, maxUin }) => uin >= minUin && uin <= maxUin)
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeGroupRequestSequence(
|
||||
@@ -72,11 +80,13 @@ function normalizeGroupRequestSequence(
|
||||
groupId: number,
|
||||
): number {
|
||||
const sequence = Number(rawSequence ?? 0);
|
||||
|
||||
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
|
||||
throw new Error(
|
||||
`invalid group-request sequence: group=${groupId} sequence=${String(rawSequence ?? 0)}`,
|
||||
);
|
||||
}
|
||||
|
||||
return sequence;
|
||||
}
|
||||
|
||||
@@ -105,7 +115,9 @@ export class ContactsApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
private fetchRobotUinRanges(groupId: number): Promise<RobotUinRangeSnapshot> {
|
||||
if (this.robotUinRangesPromise_) return this.robotUinRangesPromise_;
|
||||
if (this.robotUinRangesPromise_) {
|
||||
return this.robotUinRangesPromise_;
|
||||
}
|
||||
|
||||
const pending = FetchRobotUinRanges.invoke(this.ctx).then((snapshot) => {
|
||||
log.info(
|
||||
@@ -121,7 +133,10 @@ export class ContactsApi {
|
||||
// A failed first load must be observable and retryable. Keep the rejection
|
||||
// visible to the caller instead of converting every member to false.
|
||||
void pending.catch((err: unknown) => {
|
||||
if (this.robotUinRangesPromise_ === pending) this.robotUinRangesPromise_ = null;
|
||||
if (this.robotUinRangesPromise_ === pending) {
|
||||
this.robotUinRangesPromise_ = null;
|
||||
}
|
||||
|
||||
log.error(
|
||||
'failed to load robot UIN ranges: uin=%s group=%d err=%s',
|
||||
this.ctx.identity.uin,
|
||||
@@ -156,49 +171,59 @@ export class ContactsApi {
|
||||
for (;;) {
|
||||
const page = await FetchFriendListPage.invoke(this.ctx, { cookie });
|
||||
entries.push(...page.entries);
|
||||
|
||||
for (const category of page.categories) {
|
||||
categories.set(category.categoryId, category);
|
||||
}
|
||||
|
||||
const next = page.cookie;
|
||||
if (!next?.length) break;
|
||||
|
||||
if (!next?.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
const key = toHex(next);
|
||||
|
||||
if (seenCookies.has(key)) {
|
||||
throw new Error(`repeated friend-list cookie ${key}`);
|
||||
}
|
||||
|
||||
seenCookies.add(key);
|
||||
cookie = next;
|
||||
}
|
||||
|
||||
const friends = entries.map(entry => entry.friend);
|
||||
const friends = entries.map((entry) => entry.friend);
|
||||
this.ctx.identity.rememberFriends(friends);
|
||||
return { entries, categories: [...categories.values()] };
|
||||
}
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> {
|
||||
const roster = await this.fetchFriendRoster();
|
||||
return roster.entries.map(entry => entry.friend);
|
||||
return roster.entries.map((entry) => entry.friend);
|
||||
}
|
||||
|
||||
async fetchFriendCategories(): Promise<FriendCategoryInfo[]> {
|
||||
const roster = await this.fetchFriendRoster();
|
||||
const buckets = new Map(
|
||||
roster.categories.map(category => [category.categoryId, [] as FriendInfo[]]),
|
||||
roster.categories.map((category) => [category.categoryId, [] as FriendInfo[]]),
|
||||
);
|
||||
|
||||
for (const entry of roster.entries) {
|
||||
const bucket = buckets.get(entry.categoryId);
|
||||
|
||||
if (!bucket) {
|
||||
throw new Error(
|
||||
`friend roster references missing category ${entry.categoryId} `
|
||||
+ `(${roster.entries.length} friends total)`,
|
||||
`friend roster references missing category ${entry.categoryId} ` +
|
||||
`(${roster.entries.length} friends total)`,
|
||||
);
|
||||
}
|
||||
|
||||
bucket.push(entry.friend);
|
||||
}
|
||||
|
||||
return roster.categories.map(category => {
|
||||
return roster.categories.map((category) => {
|
||||
const friends = buckets.get(category.categoryId)!;
|
||||
|
||||
if (friends.length !== category.memberCount) {
|
||||
log.warn(
|
||||
'friend category member count mismatch category=%d server=%d assembled=%d',
|
||||
@@ -207,41 +232,54 @@ export class ContactsApi {
|
||||
friends.length,
|
||||
);
|
||||
}
|
||||
|
||||
return { ...category, friends };
|
||||
});
|
||||
}
|
||||
|
||||
async setFriendCategory(params: SetFriendCategoryParams): Promise<void> {
|
||||
const selectorCount = Number(params.categoryId !== undefined)
|
||||
+ Number(params.categoryName !== undefined);
|
||||
const selectorCount =
|
||||
Number(params.categoryId !== undefined) + Number(params.categoryName !== undefined);
|
||||
|
||||
if (selectorCount !== 1) {
|
||||
throw new Error('exactly one of categoryId or categoryName is required');
|
||||
}
|
||||
|
||||
const categories = await this.fetchFriendCategories();
|
||||
const friendCategory = categories.find(category =>
|
||||
category.friends.some(friend => friend.uin === params.uin));
|
||||
const friend = friendCategory?.friends.find(entry => entry.uin === params.uin);
|
||||
const friendCategory = categories.find((category) =>
|
||||
category.friends.some((friend) => friend.uin === params.uin),
|
||||
);
|
||||
const friend = friendCategory?.friends.find((entry) => entry.uin === params.uin);
|
||||
|
||||
if (!friend) {
|
||||
throw new Error(`friend ${params.uin} is not in the live roster`);
|
||||
}
|
||||
|
||||
if (!friend.uid) {
|
||||
throw new Error(`friend ${params.uin} has no UID in the live roster`);
|
||||
}
|
||||
|
||||
let target: FriendCategoryInfo | undefined;
|
||||
|
||||
if (params.categoryId !== undefined) {
|
||||
target = categories.find(category => category.categoryId === params.categoryId);
|
||||
target = categories.find((category) => category.categoryId === params.categoryId);
|
||||
|
||||
if (!target) {
|
||||
throw new Error(`friend category ${params.categoryId} does not exist`);
|
||||
}
|
||||
} else {
|
||||
const matches = categories.filter(category => category.categoryName === params.categoryName);
|
||||
const matches = categories.filter(
|
||||
(category) => category.categoryName === params.categoryName,
|
||||
);
|
||||
|
||||
if (matches.length === 0) {
|
||||
throw new Error(`friend category name "${params.categoryName}" does not exist`);
|
||||
}
|
||||
|
||||
if (matches.length > 1) {
|
||||
throw new Error(`friend category name "${params.categoryName}" is ambiguous`);
|
||||
}
|
||||
|
||||
target = matches[0]!;
|
||||
}
|
||||
|
||||
@@ -260,6 +298,7 @@ export class ContactsApi {
|
||||
async fetchGroupList(): Promise<QQGroupInfo[]> {
|
||||
const resp = await FetchGroupList.invoke(this.ctx);
|
||||
const groups: QQGroupInfo[] = [];
|
||||
|
||||
for (const raw of resp.groups ?? []) {
|
||||
groups.push({
|
||||
groupId: raw.groupUin ?? 0,
|
||||
@@ -279,6 +318,7 @@ export class ContactsApi {
|
||||
allMuted: isGroupAllMuted(raw.info?.shutUpAllTimestamp),
|
||||
});
|
||||
}
|
||||
|
||||
this.ctx.identity.rememberGroups(groups);
|
||||
return groups;
|
||||
}
|
||||
@@ -291,10 +331,17 @@ export class ContactsApi {
|
||||
* joined-groups roster / get_group_list.
|
||||
*/
|
||||
async fetchGroupDetail(groupId: number): Promise<QQGroupInfo | null> {
|
||||
if (!(groupId > 0)) return null;
|
||||
if (!(groupId > 0)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resp = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const r = resp.groupInfo?.results;
|
||||
if (!r) return null;
|
||||
|
||||
if (!r) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
groupId,
|
||||
groupName: r.name ?? '',
|
||||
@@ -327,6 +374,7 @@ export class ContactsApi {
|
||||
const robotSnapshotPromise = this.fetchRobotUinRanges(groupId);
|
||||
const members: GroupMemberInfo[] = [];
|
||||
let token = '';
|
||||
|
||||
do {
|
||||
const page = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
|
||||
members.push(...page.members);
|
||||
@@ -334,6 +382,7 @@ export class ContactsApi {
|
||||
} while (token);
|
||||
|
||||
const robotSnapshot = await robotSnapshotPromise;
|
||||
|
||||
for (const member of members) {
|
||||
member.isRobot = isRobotUin(member.uin, robotSnapshot.ranges);
|
||||
}
|
||||
@@ -354,7 +403,11 @@ export class ContactsApi {
|
||||
* .Create(targetUid)` path. */
|
||||
async fetchUserProfileByUid(uid: string): Promise<UserProfileInfo> {
|
||||
const info = await FetchUserProfileByUid.invoke(this.ctx, { uid });
|
||||
if (info.uin > 0) this.ctx.identity.rememberUserProfile(info);
|
||||
|
||||
if (info.uin > 0) {
|
||||
this.ctx.identity.rememberUserProfile(info);
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
@@ -371,26 +424,31 @@ export class ContactsApi {
|
||||
): Promise<GroupRequestInfo[]> {
|
||||
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered, count, cursor });
|
||||
const requests: GroupRequestInfo[] = [];
|
||||
|
||||
for (const raw of resp.requests ?? []) {
|
||||
const groupId = raw.group?.groupUin ?? 0;
|
||||
const targetUin = raw.target?.uin ?? 0;
|
||||
const invitorUin = raw.invitor?.uin ?? 0;
|
||||
const operatorUin = raw.operatorUser?.uin ?? 0;
|
||||
const targetUid = raw.target?.uid
|
||||
|| this.ctx.identity.findUidByUin(targetUin, groupId)
|
||||
|| this.ctx.identity.findUidByUin(targetUin)
|
||||
|| '';
|
||||
const invitorUid = raw.invitor?.uid
|
||||
|| this.ctx.identity.findUidByUin(invitorUin, groupId)
|
||||
|| this.ctx.identity.findUidByUin(invitorUin)
|
||||
|| '';
|
||||
const operatorUid = raw.operatorUser?.uid
|
||||
|| this.ctx.identity.findUidByUin(operatorUin, groupId)
|
||||
|| this.ctx.identity.findUidByUin(operatorUin)
|
||||
|| '';
|
||||
const targetUid =
|
||||
raw.target?.uid ||
|
||||
this.ctx.identity.findUidByUin(targetUin, groupId) ||
|
||||
this.ctx.identity.findUidByUin(targetUin) ||
|
||||
'';
|
||||
const invitorUid =
|
||||
raw.invitor?.uid ||
|
||||
this.ctx.identity.findUidByUin(invitorUin, groupId) ||
|
||||
this.ctx.identity.findUidByUin(invitorUin) ||
|
||||
'';
|
||||
const operatorUid =
|
||||
raw.operatorUser?.uid ||
|
||||
this.ctx.identity.findUidByUin(operatorUin, groupId) ||
|
||||
this.ctx.identity.findUidByUin(operatorUin) ||
|
||||
'';
|
||||
const notifyType = raw.eventType ?? 0;
|
||||
const operationType = groupRequestOperationType(notifyType);
|
||||
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
|
||||
|
||||
if (operationType === null) {
|
||||
log.warn(
|
||||
'unsupported group-request notification type: group=%d sequence=%s type=%d',
|
||||
@@ -399,26 +457,30 @@ export class ContactsApi {
|
||||
notifyType,
|
||||
);
|
||||
}
|
||||
|
||||
requests.push({
|
||||
groupId,
|
||||
groupName: raw.group?.groupName ?? '',
|
||||
targetUid,
|
||||
targetUin: targetUin
|
||||
|| this.ctx.identity.findUinByUid(targetUid, groupId)
|
||||
|| this.ctx.identity.findUinByUid(targetUid)
|
||||
|| 0,
|
||||
targetUin:
|
||||
targetUin ||
|
||||
this.ctx.identity.findUinByUid(targetUid, groupId) ||
|
||||
this.ctx.identity.findUinByUid(targetUid) ||
|
||||
0,
|
||||
targetName: raw.target?.name ?? '',
|
||||
invitorUid,
|
||||
invitorUin: invitorUin
|
||||
|| this.ctx.identity.findUinByUid(invitorUid, groupId)
|
||||
|| this.ctx.identity.findUinByUid(invitorUid)
|
||||
|| 0,
|
||||
invitorUin:
|
||||
invitorUin ||
|
||||
this.ctx.identity.findUinByUid(invitorUid, groupId) ||
|
||||
this.ctx.identity.findUinByUid(invitorUid) ||
|
||||
0,
|
||||
invitorName: raw.invitor?.name ?? '',
|
||||
operatorUid,
|
||||
operatorUin: operatorUin
|
||||
|| this.ctx.identity.findUinByUid(operatorUid, groupId)
|
||||
|| this.ctx.identity.findUinByUid(operatorUid)
|
||||
|| 0,
|
||||
operatorUin:
|
||||
operatorUin ||
|
||||
this.ctx.identity.findUinByUid(operatorUid, groupId) ||
|
||||
this.ctx.identity.findUinByUid(operatorUid) ||
|
||||
0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
@@ -426,11 +488,13 @@ export class ContactsApi {
|
||||
eventType: operationType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
operateTransInfo:
|
||||
raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
? raw.operateTransInfo
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
this.ctx.identity.rememberGroupRequests(requests);
|
||||
return requests;
|
||||
}
|
||||
@@ -445,6 +509,7 @@ export class ContactsApi {
|
||||
): Promise<GroupRequestInfo[]> {
|
||||
const resp = await FetchGroupRequestsByUid.invoke(this.ctx, { filtered, count, cursor });
|
||||
const requests: GroupRequestInfo[] = [];
|
||||
|
||||
for (const raw of resp.requests ?? []) {
|
||||
const groupId = raw.group?.groupUin ?? 0;
|
||||
const targetUid = raw.target?.uid ?? '';
|
||||
@@ -453,6 +518,7 @@ export class ContactsApi {
|
||||
const notifyType = raw.eventType ?? 0;
|
||||
const operationType = groupRequestOperationType(notifyType);
|
||||
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
|
||||
|
||||
if (operationType === null) {
|
||||
log.warn(
|
||||
'unsupported group-request notification type: group=%d sequence=%s type=%d',
|
||||
@@ -461,23 +527,27 @@ export class ContactsApi {
|
||||
notifyType,
|
||||
);
|
||||
}
|
||||
|
||||
requests.push({
|
||||
groupId,
|
||||
groupName: raw.group?.groupName ?? '',
|
||||
targetUid,
|
||||
targetUin: this.ctx.identity.findUinByUid(targetUid, groupId)
|
||||
?? this.ctx.identity.findUinByUid(targetUid)
|
||||
?? 0,
|
||||
targetUin:
|
||||
this.ctx.identity.findUinByUid(targetUid, groupId) ??
|
||||
this.ctx.identity.findUinByUid(targetUid) ??
|
||||
0,
|
||||
targetName: raw.target?.name ?? '',
|
||||
invitorUid,
|
||||
invitorUin: this.ctx.identity.findUinByUid(invitorUid, groupId)
|
||||
?? this.ctx.identity.findUinByUid(invitorUid)
|
||||
?? 0,
|
||||
invitorUin:
|
||||
this.ctx.identity.findUinByUid(invitorUid, groupId) ??
|
||||
this.ctx.identity.findUinByUid(invitorUid) ??
|
||||
0,
|
||||
invitorName: raw.invitor?.name ?? '',
|
||||
operatorUid,
|
||||
operatorUin: this.ctx.identity.findUinByUid(operatorUid, groupId)
|
||||
?? this.ctx.identity.findUinByUid(operatorUid)
|
||||
?? 0,
|
||||
operatorUin:
|
||||
this.ctx.identity.findUinByUid(operatorUid, groupId) ??
|
||||
this.ctx.identity.findUinByUid(operatorUid) ??
|
||||
0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
@@ -485,18 +555,22 @@ export class ContactsApi {
|
||||
eventType: operationType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
operateTransInfo:
|
||||
raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
? raw.operateTransInfo
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
this.ctx.identity.rememberGroupRequests(requests);
|
||||
return requests;
|
||||
}
|
||||
|
||||
/** Live observation write. IncomingPacketPipeline and tests only. */
|
||||
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
|
||||
if (groupUin > 0 && sequence > 0) this.groupInviteCardSeqs_.set(groupUin, sequence);
|
||||
if (groupUin > 0 && sequence > 0) {
|
||||
this.groupInviteCardSeqs_.set(groupUin, sequence);
|
||||
}
|
||||
}
|
||||
|
||||
/** The approval msgseq captured from a private "qun.invite" card for this
|
||||
@@ -510,8 +584,11 @@ export class ContactsApi {
|
||||
* use this path because the card sequence is absent from 0x10C0. */
|
||||
findGroupInviteCardGroupBySequence(sequence: number): number | undefined {
|
||||
for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) {
|
||||
if (rememberedSequence === sequence) return groupUin;
|
||||
if (rememberedSequence === sequence) {
|
||||
return groupUin;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -519,9 +596,11 @@ export class ContactsApi {
|
||||
const resp = await FetchDownloadRkeys.invoke(this.ctx);
|
||||
|
||||
const result: DownloadRKeyInfo[] = [];
|
||||
|
||||
for (const entry of resp.downloadRkey?.rkeys ?? []) {
|
||||
const rkey = entry.rkey ?? '';
|
||||
const type = entry.type ?? 0;
|
||||
|
||||
if (rkey && type) {
|
||||
result.push({
|
||||
rkey,
|
||||
@@ -532,6 +611,7 @@ export class ContactsApi {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,10 @@ import {
|
||||
FetchAiVoiceList,
|
||||
type AiVoiceCategory as NamespaceAiVoiceCategory,
|
||||
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
|
||||
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import {
|
||||
GetStrangerStatus,
|
||||
type StrangerStatus as NamespaceStrangerStatus,
|
||||
} from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import {
|
||||
GetGroupTodoList,
|
||||
type GroupTodoListItem as NamespaceGroupTodoListItem,
|
||||
@@ -46,7 +49,7 @@ export const AiVoiceChatType = {
|
||||
Sound: 1,
|
||||
Sing: 2,
|
||||
} as const;
|
||||
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
|
||||
export type AiVoiceChatType = (typeof AiVoiceChatType)[keyof typeof AiVoiceChatType];
|
||||
|
||||
export type AiVoiceCategory = NamespaceAiVoiceCategory;
|
||||
export interface AiVoiceItem {
|
||||
@@ -72,18 +75,33 @@ function normalizeMediaUuid(value: unknown): string {
|
||||
|
||||
function matchesAiVoiceEvent(node: MediaIndexNode, event: GroupMessageEvent): boolean {
|
||||
const expectedUuid = normalizeMediaUuid(node.fileUuid);
|
||||
if (!expectedUuid) return false;
|
||||
for (const element of event.elements) {
|
||||
if (element.type !== 'record') continue;
|
||||
const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId);
|
||||
if (actualUuid === expectedUuid) return true;
|
||||
|
||||
if (!expectedUuid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const element of event.elements) {
|
||||
if (element.type !== 'record') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId);
|
||||
|
||||
if (actualUuid === expectedUuid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function describeAiVoiceFingerprint(node: MediaIndexNode): string {
|
||||
const uuid = normalizeMediaUuid(node.fileUuid);
|
||||
if (uuid) return `uuid:${uuid.slice(-12)}`;
|
||||
|
||||
if (uuid) {
|
||||
return `uuid:${uuid.slice(-12)}`;
|
||||
}
|
||||
|
||||
return 'missing';
|
||||
}
|
||||
|
||||
@@ -121,7 +139,11 @@ export class ExtrasApi {
|
||||
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
|
||||
try {
|
||||
const status = await GetStrangerStatus.invoke(this.ctx, { uin });
|
||||
if (!status) log.warn('user status query returned no status target=%d', uin);
|
||||
|
||||
if (!status) {
|
||||
log.warn('user status query returned no status target=%d', uin);
|
||||
}
|
||||
|
||||
return status;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
@@ -135,7 +157,10 @@ export class ExtrasApi {
|
||||
|
||||
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
|
||||
|
||||
fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
|
||||
fetchAiVoiceList(
|
||||
groupId: number,
|
||||
chatType: AiVoiceChatType | number,
|
||||
): Promise<AiVoiceCategory[]> {
|
||||
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
|
||||
}
|
||||
|
||||
@@ -158,9 +183,17 @@ export class ExtrasApi {
|
||||
maxRetries = 30,
|
||||
): Promise<MediaIndexNode> {
|
||||
// Random 32-bit session id — server uses this to deduplicate polls.
|
||||
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
|
||||
const sessionId = Math.floor(Math.random() * 0xffffffff) >>> 0;
|
||||
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
|
||||
const node = await FetchAiVoice.invoke(this.ctx, {
|
||||
groupId,
|
||||
voiceId,
|
||||
text,
|
||||
chatType,
|
||||
sessionId,
|
||||
});
|
||||
|
||||
if (node) {
|
||||
log.debug(
|
||||
'AI voice synthesis completed group=%d media=%s polls=%d',
|
||||
@@ -171,6 +204,7 @@ export class ExtrasApi {
|
||||
return node as MediaIndexNode;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
|
||||
@@ -200,26 +234,46 @@ export class ExtrasApi {
|
||||
});
|
||||
|
||||
const claim = (event: GroupMessageEvent): boolean => {
|
||||
if (receiptSettled) return false;
|
||||
if (receiptSettled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`;
|
||||
if (this.claimedAiVoiceReceiptKeys.has(key)) return false;
|
||||
|
||||
if (this.claimedAiVoiceReceiptKeys.has(key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.claimedAiVoiceReceiptKeys.add(key);
|
||||
|
||||
if (this.claimedAiVoiceReceiptKeys.size > AI_VOICE_CLAIM_LIMIT) {
|
||||
const oldest = this.claimedAiVoiceReceiptKeys.values().next().value;
|
||||
if (oldest !== undefined) this.claimedAiVoiceReceiptKeys.delete(oldest);
|
||||
|
||||
if (oldest !== undefined) {
|
||||
this.claimedAiVoiceReceiptKeys.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
receiptSettled = true;
|
||||
return true;
|
||||
};
|
||||
|
||||
const accept = (event: GroupMessageEvent): void => {
|
||||
if (event.groupId !== groupId || event.senderUin !== event.selfUin) return;
|
||||
if (!event.elements.some(element => element.type === 'record')) return;
|
||||
if (event.groupId !== groupId || event.senderUin !== event.selfUin) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!event.elements.some((element) => element.type === 'record')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (expectedNode && matchesAiVoiceEvent(expectedNode, event) && claim(event)) {
|
||||
resolveReceipt?.(event);
|
||||
return;
|
||||
}
|
||||
|
||||
candidates.push(event);
|
||||
|
||||
if (candidates.length > AI_VOICE_CANDIDATE_LIMIT) {
|
||||
candidates.shift();
|
||||
candidatesOverflowed = true;
|
||||
@@ -228,36 +282,50 @@ export class ExtrasApi {
|
||||
|
||||
const unsubscribe = this.ctx.events.on('group_message', accept);
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
try {
|
||||
const node = await this.fetchAiVoice(groupId, voiceId, text, chatType);
|
||||
expectedNode = node;
|
||||
const fingerprint = describeAiVoiceFingerprint(node);
|
||||
if (fingerprint === 'missing') {
|
||||
throw new Error('AI voice was published but QQ returned no exact media identifier for receipt correlation');
|
||||
}
|
||||
|
||||
const buffered = candidates.find(event => matchesAiVoiceEvent(node, event) && claim(event));
|
||||
if (!buffered && candidatesOverflowed) {
|
||||
if (fingerprint === 'missing') {
|
||||
throw new Error(
|
||||
`AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} `
|
||||
+ `unmatched self voice messages (group=${groupId} media=${fingerprint})`,
|
||||
'AI voice was published but QQ returned no exact media identifier for receipt correlation',
|
||||
);
|
||||
}
|
||||
const event = buffered ?? await Promise.race([
|
||||
|
||||
const buffered = candidates.find(
|
||||
(event) => matchesAiVoiceEvent(node, event) && claim(event),
|
||||
);
|
||||
|
||||
if (!buffered && candidatesOverflowed) {
|
||||
throw new Error(
|
||||
`AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} ` +
|
||||
`unmatched self voice messages (group=${groupId} media=${fingerprint})`,
|
||||
);
|
||||
}
|
||||
|
||||
const event =
|
||||
buffered ??
|
||||
(await Promise.race([
|
||||
receiptPromise,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
reject(new Error(
|
||||
`AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms `
|
||||
+ `(group=${groupId} media=${fingerprint})`,
|
||||
));
|
||||
reject(
|
||||
new Error(
|
||||
`AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms ` +
|
||||
`(group=${groupId} media=${fingerprint})`,
|
||||
),
|
||||
);
|
||||
}, receiptTimeoutMs);
|
||||
timeout.unref?.();
|
||||
}),
|
||||
]);
|
||||
]));
|
||||
|
||||
if (!Number.isInteger(event.msgSeq) || event.msgSeq <= 0) {
|
||||
throw new Error(`AI voice receipt carried invalid message sequence: ${event.msgSeq}`);
|
||||
throw new Error(
|
||||
`AI voice receipt carried invalid message sequence: ${event.msgSeq}`,
|
||||
);
|
||||
}
|
||||
|
||||
log.debug(
|
||||
@@ -271,7 +339,10 @@ export class ExtrasApi {
|
||||
sequence: event.msgSeq,
|
||||
};
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
unsubscribe();
|
||||
}
|
||||
}
|
||||
@@ -295,38 +366,58 @@ export class ExtrasApi {
|
||||
? {
|
||||
type: 1,
|
||||
groupItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), groupUin: BigInt(input.peerUin),
|
||||
fileId: input.fileId ?? 0, md5, duration: input.duration, size: input.size,
|
||||
format: input.format, uuid: input.uuid,
|
||||
msgId: BigInt(input.msgId),
|
||||
senderUin: BigInt(input.senderUin),
|
||||
groupUin: BigInt(input.peerUin),
|
||||
fileId: input.fileId ?? 0,
|
||||
md5,
|
||||
duration: input.duration,
|
||||
size: input.size,
|
||||
format: input.format,
|
||||
uuid: input.uuid,
|
||||
},
|
||||
}
|
||||
: {
|
||||
type: 2,
|
||||
c2cItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), receiverUin: BigInt(input.peerUin),
|
||||
uuid: input.uuid, duration: input.duration, size: input.size, format: input.format, md5,
|
||||
msgId: BigInt(input.msgId),
|
||||
senderUin: BigInt(input.senderUin),
|
||||
receiverUin: BigInt(input.peerUin),
|
||||
uuid: input.uuid,
|
||||
duration: input.duration,
|
||||
size: input.size,
|
||||
format: input.format,
|
||||
md5,
|
||||
},
|
||||
};
|
||||
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
|
||||
|
||||
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'ptt translate request failed');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<PttTransResp>(result.responseData);
|
||||
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
|
||||
|
||||
if (item?.errCode) {
|
||||
// Diagnostic (#165 备选): correlate QQ's errCode with the request fields we
|
||||
// sourced from cache, to tell a server-side ASR failure apart from our own
|
||||
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
|
||||
log.warn(
|
||||
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
|
||||
item.errCode, input.isGroup,
|
||||
item.errCode,
|
||||
input.isGroup,
|
||||
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
|
||||
input.format, input.uuid ? 'set' : 'EMPTY', input.duration, input.size,
|
||||
input.format,
|
||||
input.uuid ? 'set' : 'EMPTY',
|
||||
input.duration,
|
||||
input.size,
|
||||
);
|
||||
throw new Error(`ptt translate failed: error=${item.errCode}`);
|
||||
}
|
||||
|
||||
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,11 @@ import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
|
||||
import { hashFlashFileStreaming } from '@snowluma/protocol/highway/hash-file';
|
||||
import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream';
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import type { FlashSliceUploadBody, FlashSliceUploadResp, FlashFileId } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
|
||||
import type {
|
||||
FlashSliceUploadBody,
|
||||
FlashSliceUploadResp,
|
||||
FlashFileId,
|
||||
} from '@snowluma/proto-defs/oidb-actions/flash-transfer';
|
||||
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
||||
import { promises as fsp } from 'node:fs';
|
||||
import { deflateSync } from 'node:zlib';
|
||||
@@ -36,19 +40,52 @@ import { deflateSync } from 'node:zlib';
|
||||
const FLASH_SLICE_SIZE = 1024 * 1024;
|
||||
|
||||
const FLASH_IMAGE_EXT = new Set([
|
||||
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'heic', 'avif', 'tiff', 'tif', 'ico', 'dib', 'heif',
|
||||
'jpg',
|
||||
'jpeg',
|
||||
'png',
|
||||
'gif',
|
||||
'bmp',
|
||||
'webp',
|
||||
'heic',
|
||||
'avif',
|
||||
'tiff',
|
||||
'tif',
|
||||
'ico',
|
||||
'dib',
|
||||
'heif',
|
||||
]);
|
||||
const FLASH_AUDIO_EXT = new Set(['mp3', 'wav', 'aac', 'flac']);
|
||||
const FLASH_VIDEO_EXT = new Set([
|
||||
'mp4', 'avi', 'mkv', 'mov', '3gp', 'mpeg', 'rmvb', 'rm', 'wmv', 'flv', 'asf', 'webm', 'mpg', 'vob', 'm4v', 'f4v',
|
||||
'mp4',
|
||||
'avi',
|
||||
'mkv',
|
||||
'mov',
|
||||
'3gp',
|
||||
'mpeg',
|
||||
'rmvb',
|
||||
'rm',
|
||||
'wmv',
|
||||
'flv',
|
||||
'asf',
|
||||
'webm',
|
||||
'mpg',
|
||||
'vob',
|
||||
'm4v',
|
||||
'f4v',
|
||||
]);
|
||||
const FLASH_ARCHIVE_EXT = new Set(['zip', 'rar', 'tar', 'bz2', 'xz', 'tgz', 'gz', '7z']);
|
||||
const FLASH_MODEL_EXT = new Set(['pt', 'pth', 'onnx', 'model', 'mlmodel']);
|
||||
|
||||
/** 0x93cf f3 粗类:压缩包走 2/6,其余按媒体类 7。 */
|
||||
function flashApplyTypeCode(ext: string): number {
|
||||
if (ext === 'zip') return 6;
|
||||
if (FLASH_ARCHIVE_EXT.has(ext)) return 2;
|
||||
if (ext === 'zip') {
|
||||
return 6;
|
||||
}
|
||||
|
||||
if (FLASH_ARCHIVE_EXT.has(ext)) {
|
||||
return 2;
|
||||
}
|
||||
|
||||
return 7;
|
||||
}
|
||||
|
||||
@@ -57,29 +94,98 @@ function flashApplyTypeCode(ext: string): number {
|
||||
* 图片 26、音频 1、视频 2、文档 3、压缩包 4、未知 11。
|
||||
*/
|
||||
function flashFormatCode(ext: string): number {
|
||||
if (FLASH_IMAGE_EXT.has(ext)) return 26;
|
||||
if (FLASH_AUDIO_EXT.has(ext)) return 1;
|
||||
if (FLASH_VIDEO_EXT.has(ext)) return 2;
|
||||
if (ext === 'doc' || ext === 'docx') return 3;
|
||||
if (FLASH_ARCHIVE_EXT.has(ext)) return 4;
|
||||
if (ext === 'apk') return 5;
|
||||
if (ext === 'xls' || ext === 'xlsx') return 6;
|
||||
if (ext === 'ppt' || ext === 'pptx') return 7;
|
||||
if (ext === 'html' || ext === 'htm') return 8;
|
||||
if (ext === 'pdf') return 9;
|
||||
if (ext === 'txt') return 10;
|
||||
if (ext === 'psd') return 12;
|
||||
if (FLASH_MODEL_EXT.has(ext)) return 15;
|
||||
if (ext === 'ttf' || ext === 'otf') return 16;
|
||||
if (ext === 'ipa') return 17;
|
||||
if (ext === 'dmg') return 23;
|
||||
if (ext === 'pkg') return 24;
|
||||
if (ext === 'key') return 18;
|
||||
if (ext === 'note') return 19;
|
||||
if (ext === 'numbers') return 20;
|
||||
if (ext === 'pages') return 21;
|
||||
if (ext === 'sketch') return 22;
|
||||
if (ext === 'exe') return 27;
|
||||
if (FLASH_IMAGE_EXT.has(ext)) {
|
||||
return 26;
|
||||
}
|
||||
|
||||
if (FLASH_AUDIO_EXT.has(ext)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (FLASH_VIDEO_EXT.has(ext)) {
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (ext === 'doc' || ext === 'docx') {
|
||||
return 3;
|
||||
}
|
||||
|
||||
if (FLASH_ARCHIVE_EXT.has(ext)) {
|
||||
return 4;
|
||||
}
|
||||
|
||||
if (ext === 'apk') {
|
||||
return 5;
|
||||
}
|
||||
|
||||
if (ext === 'xls' || ext === 'xlsx') {
|
||||
return 6;
|
||||
}
|
||||
|
||||
if (ext === 'ppt' || ext === 'pptx') {
|
||||
return 7;
|
||||
}
|
||||
|
||||
if (ext === 'html' || ext === 'htm') {
|
||||
return 8;
|
||||
}
|
||||
|
||||
if (ext === 'pdf') {
|
||||
return 9;
|
||||
}
|
||||
|
||||
if (ext === 'txt') {
|
||||
return 10;
|
||||
}
|
||||
|
||||
if (ext === 'psd') {
|
||||
return 12;
|
||||
}
|
||||
|
||||
if (FLASH_MODEL_EXT.has(ext)) {
|
||||
return 15;
|
||||
}
|
||||
|
||||
if (ext === 'ttf' || ext === 'otf') {
|
||||
return 16;
|
||||
}
|
||||
|
||||
if (ext === 'ipa') {
|
||||
return 17;
|
||||
}
|
||||
|
||||
if (ext === 'dmg') {
|
||||
return 23;
|
||||
}
|
||||
|
||||
if (ext === 'pkg') {
|
||||
return 24;
|
||||
}
|
||||
|
||||
if (ext === 'key') {
|
||||
return 18;
|
||||
}
|
||||
|
||||
if (ext === 'note') {
|
||||
return 19;
|
||||
}
|
||||
|
||||
if (ext === 'numbers') {
|
||||
return 20;
|
||||
}
|
||||
|
||||
if (ext === 'pages') {
|
||||
return 21;
|
||||
}
|
||||
|
||||
if (ext === 'sketch') {
|
||||
return 22;
|
||||
}
|
||||
|
||||
if (ext === 'exe') {
|
||||
return 27;
|
||||
}
|
||||
|
||||
return 11;
|
||||
}
|
||||
|
||||
@@ -88,8 +194,12 @@ function flashFormatCode(ext: string): number {
|
||||
const FLASH_FILE_ID_RETRY_DELAYS_MS = [1000, 2000, 4000, 4000] as const;
|
||||
|
||||
/** Fail cleanly if the staged file changed since the streaming hash pass. */
|
||||
async function assertUnchanged(filePath: string, baseline: { size: number; mtimeMs: number }): Promise<void> {
|
||||
async function assertUnchanged(
|
||||
filePath: string,
|
||||
baseline: { size: number; mtimeMs: number },
|
||||
): Promise<void> {
|
||||
const now = await fsp.stat(filePath);
|
||||
|
||||
if (now.size !== baseline.size || now.mtimeMs !== baseline.mtimeMs) {
|
||||
throw new Error('file source changed during send (mutated between hashing and upload)');
|
||||
}
|
||||
@@ -158,27 +268,38 @@ const QFILE_SHARE_TIMEOUT_MS = 20_000;
|
||||
|
||||
function officialQfileShareUrl(input: string): string {
|
||||
const value = input.trim();
|
||||
if (!value) throw new Error('get_fileset_id: share code is empty');
|
||||
|
||||
if (!value) {
|
||||
throw new Error('get_fileset_id: share code is empty');
|
||||
}
|
||||
|
||||
let code = value;
|
||||
|
||||
if (/^[a-z][a-z\d+.-]*:/i.test(value) || value.startsWith('//')) {
|
||||
let parsed: URL;
|
||||
|
||||
try {
|
||||
parsed = new URL(value);
|
||||
} catch (error) {
|
||||
throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error });
|
||||
}
|
||||
|
||||
if (
|
||||
parsed.protocol !== 'https:'
|
||||
|| parsed.hostname !== 'qfile.qq.com'
|
||||
|| parsed.port !== ''
|
||||
|| parsed.username !== ''
|
||||
|| parsed.password !== ''
|
||||
parsed.protocol !== 'https:' ||
|
||||
parsed.hostname !== 'qfile.qq.com' ||
|
||||
parsed.port !== '' ||
|
||||
parsed.username !== '' ||
|
||||
parsed.password !== ''
|
||||
) {
|
||||
throw new Error('get_fileset_id: expected an official QQ share URL');
|
||||
}
|
||||
|
||||
const match = /^\/q\/([^/]+)\/?$/.exec(parsed.pathname);
|
||||
if (!match) throw new Error('get_fileset_id: expected an official QQ share URL');
|
||||
|
||||
if (!match) {
|
||||
throw new Error('get_fileset_id: expected an official QQ share URL');
|
||||
}
|
||||
|
||||
try {
|
||||
code = decodeURIComponent(match[1]);
|
||||
} catch (error) {
|
||||
@@ -190,9 +311,11 @@ function officialQfileShareUrl(input: string): string {
|
||||
const codePoint = char.codePointAt(0) ?? 0;
|
||||
return codePoint <= 0x20 || codePoint === 0x7f || '/\\?#'.includes(char);
|
||||
});
|
||||
|
||||
if (code.length > 256 || hasForbiddenCharacter) {
|
||||
throw new Error('get_fileset_id: invalid share code');
|
||||
}
|
||||
|
||||
return `${QFILE_SHARE_ORIGIN}/q/${encodeURIComponent(code)}`;
|
||||
}
|
||||
|
||||
@@ -202,42 +325,64 @@ async function rejectShareResponse(response: Response, error: Error): Promise<ne
|
||||
} catch (cleanupError) {
|
||||
throw new AggregateError([error, cleanupError], error.message);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
async function readSharePage(response: Response): Promise<string> {
|
||||
const declaredLength = response.headers.get('content-length');
|
||||
|
||||
if (declaredLength !== null) {
|
||||
if (!/^\d+$/.test(declaredLength)) {
|
||||
await rejectShareResponse(response, new Error('get_fileset_id: invalid response length'));
|
||||
await rejectShareResponse(
|
||||
response,
|
||||
new Error('get_fileset_id: invalid response length'),
|
||||
);
|
||||
}
|
||||
|
||||
if (Number(declaredLength) > QFILE_SHARE_PAGE_MAX_BYTES) {
|
||||
await rejectShareResponse(response, new Error('get_fileset_id: share page too large'));
|
||||
}
|
||||
}
|
||||
if (!response.body) throw new Error('get_fileset_id: share page response has no body');
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error('get_fileset_id: share page response has no body');
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let total = 0;
|
||||
let html = '';
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
continue;
|
||||
}
|
||||
|
||||
total += value.byteLength;
|
||||
|
||||
if (total > QFILE_SHARE_PAGE_MAX_BYTES) {
|
||||
const error = new Error('get_fileset_id: share page too large');
|
||||
|
||||
try {
|
||||
await reader.cancel(error);
|
||||
} catch (cleanupError) {
|
||||
throw new AggregateError([error, cleanupError], error.message);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
html += decoder.decode(value, { stream: true });
|
||||
}
|
||||
|
||||
html += decoder.decode();
|
||||
return html;
|
||||
} finally {
|
||||
@@ -249,18 +394,28 @@ async function readSharePage(response: Response): Promise<string> {
|
||||
// 避免命中服务端秒传缓存。
|
||||
const CRC_TABLE: Uint32Array = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
|
||||
|
||||
for (let k = 0; k < 8; k++) {
|
||||
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
}
|
||||
|
||||
table[n] = c >>> 0;
|
||||
}
|
||||
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(buf: Buffer): number {
|
||||
let c = 0xFFFFFFFF;
|
||||
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xFF] ^ (c >>> 8);
|
||||
return (c ^ 0xFFFFFFFF) >>> 0;
|
||||
let c = 0xffffffff;
|
||||
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
|
||||
}
|
||||
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function pngChunk(type: string, data: Buffer): Buffer {
|
||||
@@ -280,24 +435,34 @@ function generatePng(width: number, height: number): Buffer {
|
||||
const b = Math.floor(Math.random() * 256);
|
||||
const rowLen = 1 + width * 3;
|
||||
const raw = Buffer.alloc(rowLen * height);
|
||||
|
||||
for (let y = 0; y < height; y++) {
|
||||
const off = y * rowLen;
|
||||
raw[off] = 0; // filter none
|
||||
|
||||
for (let x = 0; x < width; x++) {
|
||||
raw[off + 1 + x * 3] = r;
|
||||
raw[off + 1 + x * 3 + 1] = g;
|
||||
raw[off + 1 + x * 3 + 2] = b;
|
||||
}
|
||||
}
|
||||
|
||||
const compressed = deflateSync(raw);
|
||||
const sig = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
|
||||
const sig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(width, 0);
|
||||
ihdr.writeUInt32BE(height, 4);
|
||||
ihdr[8] = 8; // bit depth
|
||||
ihdr[9] = 2; // color type RGB
|
||||
ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0;
|
||||
return Buffer.concat([sig, pngChunk('IHDR', ihdr), pngChunk('IDAT', compressed), pngChunk('IEND', Buffer.alloc(0))]);
|
||||
ihdr[10] = 0;
|
||||
ihdr[11] = 0;
|
||||
ihdr[12] = 0;
|
||||
return Buffer.concat([
|
||||
sig,
|
||||
pngChunk('IHDR', ihdr),
|
||||
pngChunk('IDAT', compressed),
|
||||
pngChunk('IEND', Buffer.alloc(0)),
|
||||
]);
|
||||
}
|
||||
|
||||
export class FlashTransferApi {
|
||||
@@ -324,11 +489,13 @@ export class FlashTransferApi {
|
||||
* FLASH_FILE_ID_RETRY_DELAYS_MS 再问 0x93d4;已经有 fileId 后 0x12a9 只打一枪。
|
||||
*/
|
||||
private async getFileDownload(
|
||||
filesetUuid: string, fileIndex: number = 1,
|
||||
filesetUuid: string,
|
||||
fileIndex: number = 1,
|
||||
): Promise<{ url: string; fileName: string; fileSize: number } | null> {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid });
|
||||
const meta = metas.find((m) => m.fileIndex === fileIndex);
|
||||
|
||||
if (meta?.fileId) {
|
||||
const url = await GetFlashDownload.invoke(this.ctx, {
|
||||
filesetUuid: meta.filesetUuid,
|
||||
@@ -336,11 +503,20 @@ export class FlashTransferApi {
|
||||
fileId: meta.fileId,
|
||||
fileName: meta.fileName,
|
||||
});
|
||||
if (!url) return null;
|
||||
|
||||
if (!url) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { url, fileName: meta.fileName, fileSize: meta.fileSize };
|
||||
}
|
||||
|
||||
const delay = FLASH_FILE_ID_RETRY_DELAYS_MS[attempt];
|
||||
if (delay === undefined) return null;
|
||||
|
||||
if (delay === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
@@ -352,7 +528,11 @@ export class FlashTransferApi {
|
||||
*/
|
||||
async getFlashFileUrl(filesetUuid: string, fileIndex: number = 1): Promise<string> {
|
||||
const dl = await this.getFileDownload(filesetUuid, fileIndex);
|
||||
if (!dl || !dl.url) throw new Error('get_flash_file_url: no download url available');
|
||||
|
||||
if (!dl || !dl.url) {
|
||||
throw new Error('get_flash_file_url: no download url available');
|
||||
}
|
||||
|
||||
return dl.url;
|
||||
}
|
||||
|
||||
@@ -365,7 +545,11 @@ export class FlashTransferApi {
|
||||
opts?: { fileName?: string; fileIndex?: number },
|
||||
): Promise<{ url: string; fileName: string; fileSize: number }> {
|
||||
const dl = await this.getFileDownload(filesetUuid, opts?.fileIndex ?? 1);
|
||||
if (!dl || !dl.url) throw new Error('download_fileset: no download url available');
|
||||
|
||||
if (!dl || !dl.url) {
|
||||
throw new Error('download_fileset: no download url available');
|
||||
}
|
||||
|
||||
return dl;
|
||||
}
|
||||
|
||||
@@ -395,13 +579,21 @@ export class FlashTransferApi {
|
||||
* 发送闪传文件(send_flash_msg,0x93d7)。私聊:user_id→uid;群聊:group_id 直接用。
|
||||
* 0x93d7 响应无 message_id(分享 fileset,非传统消息),OneBot 层 message_id 由 action 返回 0。
|
||||
*/
|
||||
async sendFlashMsg(filesetUuid: string, target: { userId?: number; groupId?: number }): Promise<void> {
|
||||
async sendFlashMsg(
|
||||
filesetUuid: string,
|
||||
target: { userId?: number; groupId?: number },
|
||||
): Promise<void> {
|
||||
if (target.groupId) {
|
||||
await SendFlashMsg.invoke(this.ctx, { groupId: target.groupId, filesetUuid });
|
||||
return;
|
||||
}
|
||||
|
||||
const userId = target.userId;
|
||||
if (!userId) throw new Error('send_flash_msg: user_id or group_id is required');
|
||||
|
||||
if (!userId) {
|
||||
throw new Error('send_flash_msg: user_id or group_id is required');
|
||||
}
|
||||
|
||||
const targetUid = await this.ctx.identity.resolveUid(userId);
|
||||
await SendFlashMsg.invoke(this.ctx, { targetUid, filesetUuid });
|
||||
}
|
||||
@@ -414,27 +606,45 @@ export class FlashTransferApi {
|
||||
async getFilesetIdByCode(shareCode: string): Promise<string> {
|
||||
const url = officialQfileShareUrl(shareCode);
|
||||
let resp: Response;
|
||||
|
||||
try {
|
||||
resp = await fetch(url, {
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(QFILE_SHARE_TIMEOUT_MS),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {
|
||||
if (
|
||||
error instanceof Error &&
|
||||
(error.name === 'AbortError' || error.name === 'TimeoutError')
|
||||
) {
|
||||
throw new Error('get_fileset_id: share page request timed out', { cause: error });
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (resp.status >= 300 && resp.status < 400) {
|
||||
await rejectShareResponse(resp, new Error('get_fileset_id: share page redirect is not allowed'));
|
||||
await rejectShareResponse(
|
||||
resp,
|
||||
new Error('get_fileset_id: share page redirect is not allowed'),
|
||||
);
|
||||
}
|
||||
|
||||
if (!resp.ok) {
|
||||
await rejectShareResponse(resp, new Error(`get_fileset_id: HTTP ${resp.status}`));
|
||||
}
|
||||
|
||||
const html = await readSharePage(resp);
|
||||
// 网页里 fileset_id 以 JSON 嵌入(引号可能被转义为 \"),正则兼容两种形态。
|
||||
const m = /fileset_id\\?"\s*:\s*\\?"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec(html);
|
||||
if (!m) throw new Error('get_fileset_id: fileset_id not found in share page');
|
||||
const m =
|
||||
/fileset_id\\?"\s*:\s*\\?"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec(
|
||||
html,
|
||||
);
|
||||
|
||||
if (!m) {
|
||||
throw new Error('get_fileset_id: fileset_id not found in share page');
|
||||
}
|
||||
|
||||
return m[1];
|
||||
}
|
||||
|
||||
@@ -496,7 +706,11 @@ export class FlashTransferApi {
|
||||
_thumbPath?: string,
|
||||
): Promise<{ filesetId: string }> {
|
||||
const fileList = normalizeFlashTaskInputs(files);
|
||||
if (fileList.length === 0) throw new Error('create_flash_task: files is empty');
|
||||
|
||||
if (fileList.length === 0) {
|
||||
throw new Error('create_flash_task: files is empty');
|
||||
}
|
||||
|
||||
const uploader = {
|
||||
uin: this.ctx.identity.uin,
|
||||
nickname: this.ctx.identity.nickname,
|
||||
@@ -505,10 +719,15 @@ export class FlashTransferApi {
|
||||
uid: await resolveSelfUid(this.ctx),
|
||||
};
|
||||
const items: StagedFlashItem[] = [];
|
||||
|
||||
try {
|
||||
for (let i = 0; i < fileList.length; i++) {
|
||||
const source = fileList[i]!.file;
|
||||
if (!source) throw new Error('create_flash_task: files is empty');
|
||||
|
||||
if (!source) {
|
||||
throw new Error('create_flash_task: files is empty');
|
||||
}
|
||||
|
||||
const staged = await stageSourceToDisk(source, flashStageMaxBytes(source));
|
||||
const fileName = flashFileDisplayName(fileList[i]!.name, staged.fileName);
|
||||
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
|
||||
@@ -522,42 +741,74 @@ export class FlashTransferApi {
|
||||
guardStat: await fsp.stat(staged.filePath),
|
||||
cleanup: () => staged.cleanup(),
|
||||
});
|
||||
if (staged.fileSize === 0) throw new Error('create_flash_task: file is empty');
|
||||
|
||||
if (staged.fileSize === 0) {
|
||||
throw new Error('create_flash_task: file is empty');
|
||||
}
|
||||
}
|
||||
|
||||
// 申请 fileset。fileName 是卡片/面板上的 fileset 标题;各文件真实名走 commit。
|
||||
// 未指定 name 时,多文件用「<首文件名>等N个文件」、fileSize 用总和,
|
||||
// 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。
|
||||
const first = items[0];
|
||||
const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName);
|
||||
const isMulti = items.length > 1;
|
||||
const filesetName = name?.trim()
|
||||
|| (isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName);
|
||||
const filesetName =
|
||||
name?.trim() ||
|
||||
(isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName);
|
||||
const totalSize = items.reduce((s, it) => s + it.fileSize, 0);
|
||||
const apply = await ApplyFileset.invoke(this.ctx, {
|
||||
fileName: filesetName, origName: filesetName,
|
||||
fileSize: totalSize, typeCode, uploader,
|
||||
fileName: filesetName,
|
||||
origName: filesetName,
|
||||
fileSize: totalSize,
|
||||
typeCode,
|
||||
uploader,
|
||||
});
|
||||
const filesetUuid = apply.filesetUuid;
|
||||
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
|
||||
|
||||
if (!filesetUuid) {
|
||||
throw new Error('apply fileset failed: missing uuid');
|
||||
}
|
||||
|
||||
// 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号)
|
||||
const commitEntries = items.map((it) => ({
|
||||
fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName,
|
||||
fileSize: it.fileSize, formatCode: it.formatCode, fileIndex: it.fileIndex,
|
||||
fileUuid: it.fileUuid,
|
||||
fileName: it.fileName,
|
||||
origName: it.fileName,
|
||||
fileSize: it.fileSize,
|
||||
formatCode: it.formatCode,
|
||||
fileIndex: it.fileIndex,
|
||||
}));
|
||||
await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries });
|
||||
await CompleteFileset.invoke(this.ctx, { filesetUuid });
|
||||
// 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。
|
||||
const prepared: { it: StagedFlashItem; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
|
||||
const prepared: {
|
||||
it: StagedFlashItem;
|
||||
rkey: string;
|
||||
sha1StateV: Uint8Array[];
|
||||
sliceCount: number;
|
||||
}[] = [];
|
||||
|
||||
for (const it of items) {
|
||||
const p = await this.prepareAndApply(filesetUuid, it);
|
||||
if (p) prepared.push({ it, ...p });
|
||||
|
||||
if (p) {
|
||||
prepared.push({ it, ...p });
|
||||
}
|
||||
}
|
||||
|
||||
for (const p of prepared) {
|
||||
await assertUnchanged(p.it.filePath, p.it.guardStat);
|
||||
await this.sliceuploadFile(
|
||||
p.it.filePath, p.it.fileSize, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName,
|
||||
p.it.filePath,
|
||||
p.it.fileSize,
|
||||
p.rkey,
|
||||
p.sha1StateV,
|
||||
p.sliceCount,
|
||||
p.it.fileName,
|
||||
);
|
||||
}
|
||||
|
||||
// fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联
|
||||
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1);
|
||||
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2);
|
||||
@@ -574,21 +825,38 @@ export class FlashTransferApi {
|
||||
* 返回 null 只表示调用方跳过 sliceupload。
|
||||
*/
|
||||
private async prepareAndApply(
|
||||
filesetUuid: string, it: StagedFlashItem,
|
||||
filesetUuid: string,
|
||||
it: StagedFlashItem,
|
||||
): Promise<{ rkey: string; sha1StateV: Uint8Array[]; sliceCount: number } | null> {
|
||||
const hashes = await hashFlashFileStreaming(it.filePath);
|
||||
await assertUnchanged(it.filePath, it.guardStat);
|
||||
|
||||
const rkey = await PrepareUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid: it.fileUuid, fileName: it.fileName, fileSize: it.fileSize,
|
||||
sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
|
||||
filesetUuid,
|
||||
fileUuid: it.fileUuid,
|
||||
fileName: it.fileName,
|
||||
fileSize: it.fileSize,
|
||||
sha1: hashes.sha1Hex,
|
||||
fileIndex: it.fileIndex,
|
||||
formatCode: it.formatCode,
|
||||
});
|
||||
const fileId = FlashTransferApi.buildFileId(hashes.sha1, it.fileSize);
|
||||
await ApplyUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid: it.fileUuid, fileId, fileName: it.fileName, fileSize: it.fileSize,
|
||||
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
|
||||
filesetUuid,
|
||||
fileUuid: it.fileUuid,
|
||||
fileId,
|
||||
fileName: it.fileName,
|
||||
fileSize: it.fileSize,
|
||||
md5: hashes.md5Hex,
|
||||
sha1: hashes.sha1Hex,
|
||||
fileIndex: it.fileIndex,
|
||||
formatCode: it.formatCode,
|
||||
});
|
||||
if (rkey === null) return null;
|
||||
|
||||
if (rkey === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { rkey, sha1StateV: hashes.sha1StateV, sliceCount: hashes.sliceCount };
|
||||
}
|
||||
|
||||
@@ -596,16 +864,23 @@ export class FlashTransferApi {
|
||||
* 阶段2:从磁盘按 1 MiB 切片 POST sliceupload(所有文件 prepare+apply 完成后调用)。
|
||||
*/
|
||||
private async sliceuploadFile(
|
||||
filePath: string, fileSize: number, rkey: string,
|
||||
sha1StateV: Uint8Array[], sliceCount: number, fileName: string,
|
||||
filePath: string,
|
||||
fileSize: number,
|
||||
rkey: string,
|
||||
sha1StateV: Uint8Array[],
|
||||
sliceCount: number,
|
||||
fileName: string,
|
||||
): Promise<void> {
|
||||
const src = await FileChunkSource.open(filePath, fileSize);
|
||||
|
||||
try {
|
||||
for (let i = 0; i < sliceCount; i++) {
|
||||
const start = i * FLASH_SLICE_SIZE;
|
||||
const chunkLen = Math.min(FLASH_SLICE_SIZE, fileSize - start);
|
||||
const chunk = await src.read(start, chunkLen);
|
||||
const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest());
|
||||
const chunkSha1 = new Uint8Array(
|
||||
createHash('sha1').update(Buffer.from(chunk)).digest(),
|
||||
);
|
||||
const body: FlashSliceUploadBody = {
|
||||
field1: 0,
|
||||
appid: 14901,
|
||||
@@ -634,21 +909,27 @@ export class FlashTransferApi {
|
||||
*/
|
||||
private async postSliceupload(bodyBytes: Uint8Array, label: string): Promise<void> {
|
||||
const resp = await fetch('https://multimedia.qfile.qq.com/sliceupload', {
|
||||
method: 'POST', body: bodyBytes,
|
||||
method: 'POST',
|
||||
body: bodyBytes,
|
||||
headers: {
|
||||
Accept: '*/*', Connection: 'Keep-Alive',
|
||||
Accept: '*/*',
|
||||
Connection: 'Keep-Alive',
|
||||
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)',
|
||||
Pragma: 'no-cache', 'Cache-Control': 'no-cache',
|
||||
Pragma: 'no-cache',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Content-Length': String(bodyBytes.length),
|
||||
'X-Retried-Times': '1',
|
||||
},
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
const errBody = await resp.text().catch(() => '');
|
||||
throw new Error(`${label} failed: HTTP ${resp.status} ${errBody.slice(0, 300)}`);
|
||||
}
|
||||
|
||||
const respBuf = new Uint8Array(await resp.arrayBuffer());
|
||||
const sliceResp = protobuf_decode<FlashSliceUploadResp>(respBuf);
|
||||
|
||||
if (sliceResp.status !== 'success') {
|
||||
throw new Error(`${label} failed: ${sliceResp.status || 'no status in response'}`);
|
||||
}
|
||||
@@ -661,36 +942,67 @@ export class FlashTransferApi {
|
||||
* fileIndex 为缩略图在 fileset 内的序号(主文件之后递增),与 commit f6 对齐。
|
||||
*/
|
||||
private async uploadThumbnail(
|
||||
filesetUuid: string, mainFileUuid: string, thumbType: 'png' | 'jpg', fileIndex: number,
|
||||
filesetUuid: string,
|
||||
mainFileUuid: string,
|
||||
thumbType: 'png' | 'jpg',
|
||||
fileIndex: number,
|
||||
): Promise<void> {
|
||||
// 526x360 是 QQ 客户端缩略图尺寸;1x1 会被服务端拒(HTTP 400,宽高太小)。
|
||||
const width = 526, height = 360;
|
||||
const width = 526,
|
||||
height = 360;
|
||||
const thumbBytes = generatePng(width, height); // 随机纯色,SHA1 不同避免秒传
|
||||
const appid = thumbType === 'png' ? 14903 : 14902; // png=14903, jpg=14902
|
||||
const fileUuid = thumbType === 'png' ? randomUUID() : mainFileUuid; // png 独立,jpg 挂主文件
|
||||
const fileName = thumbType === 'png'
|
||||
const fileName =
|
||||
thumbType === 'png'
|
||||
? `${randomUUID().slice(0, 8)}_one.png`
|
||||
: `${createHash('md5').update(thumbBytes).digest('hex').slice(0, 32)}.jpg`;
|
||||
const hashes = computeHashes(new Uint8Array(thumbBytes));
|
||||
const fileSize = thumbBytes.length;
|
||||
const thumbFormatCode = thumbType === 'png' ? 26 : 2; // png缩略图=26, jpg缩略图=2
|
||||
const rkey = await PrepareUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex,
|
||||
fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
|
||||
filesetUuid,
|
||||
fileUuid,
|
||||
fileName,
|
||||
fileSize,
|
||||
sha1: hashes.sha1Hex,
|
||||
fileIndex,
|
||||
formatCode: thumbFormatCode,
|
||||
thumbType,
|
||||
width,
|
||||
height,
|
||||
});
|
||||
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize, appid);
|
||||
await ApplyUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileId, fileName, fileSize,
|
||||
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
|
||||
filesetUuid,
|
||||
fileUuid,
|
||||
fileId,
|
||||
fileName,
|
||||
fileSize,
|
||||
md5: hashes.md5Hex,
|
||||
sha1: hashes.sha1Hex,
|
||||
fileIndex,
|
||||
formatCode: thumbFormatCode,
|
||||
thumbType,
|
||||
width,
|
||||
height,
|
||||
});
|
||||
if (rkey === null) return;
|
||||
|
||||
if (rkey === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// sliceupload(缩略图小,1 片,Sha1StateV=[标准 SHA1])
|
||||
const sha1StateV = computeSha1StateV(new Uint8Array(thumbBytes), 1, fileSize);
|
||||
const body: FlashSliceUploadBody = {
|
||||
field1: 0, appid, field3: 2,
|
||||
field1: 0,
|
||||
appid,
|
||||
field3: 2,
|
||||
payload: {
|
||||
field1: {}, rkey,
|
||||
start: 0, end: fileSize - 1,
|
||||
field1: {},
|
||||
rkey,
|
||||
start: 0,
|
||||
end: fileSize - 1,
|
||||
sha1: new Uint8Array(hashes.sha1),
|
||||
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
|
||||
chunk: new Uint8Array(thumbBytes),
|
||||
|
||||
@@ -10,7 +10,11 @@ import type {
|
||||
} from '@snowluma/proto-defs/longmsg';
|
||||
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import type { ForwardNodePayload, MessageElement, MessageElementOf } from '@snowluma/protocol/events';
|
||||
import type {
|
||||
ForwardNodePayload,
|
||||
MessageElement,
|
||||
MessageElementOf,
|
||||
} from '@snowluma/protocol/events';
|
||||
import {
|
||||
assertWindowShakeSendPolicy,
|
||||
MessageElementValidationError,
|
||||
@@ -23,7 +27,9 @@ import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
|
||||
import { resolveSelfUid, toInt } from './shared';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
function asBridge(ctx: BridgeContext): Bridge {
|
||||
return ctx as unknown as Bridge;
|
||||
}
|
||||
|
||||
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
|
||||
// of the process — that's enough because OneBot clients typically
|
||||
@@ -77,12 +83,18 @@ interface ForwardUploadResult {
|
||||
// module just for one call. Mirrors `highway/pipeline.ts::hexToBytes`.
|
||||
function hexToBytesLocal(hex: string): Uint8Array {
|
||||
const s = hex.trim();
|
||||
if (!s) return new Uint8Array(0);
|
||||
|
||||
if (!s) {
|
||||
return new Uint8Array(0);
|
||||
}
|
||||
|
||||
const len = s.length >> 1;
|
||||
const out = new Uint8Array(len);
|
||||
|
||||
for (let i = 0; i < len; i++) {
|
||||
out[i] = parseInt(s.substr(i * 2, 2), 16);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -93,7 +105,10 @@ async function buildForwardPushBody(
|
||||
userUid?: string,
|
||||
): Promise<PushMsgBody> {
|
||||
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
|
||||
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
|
||||
|
||||
if (fromUin <= 0) {
|
||||
throw new Error('forward node user uin is invalid');
|
||||
}
|
||||
|
||||
const nickname = node.nickname.trim() || String(fromUin);
|
||||
// image/record/video upload inside a forward node must be scoped to the
|
||||
@@ -108,7 +123,8 @@ async function buildForwardPushBody(
|
||||
// result=79; notOnlineFile via PbSendMsg doesn't render), but the
|
||||
// long-msg upload service stores the bytes verbatim and the
|
||||
// receiver decodes them through the normal msg-push path.
|
||||
const sendCtx = groupId !== undefined
|
||||
const sendCtx =
|
||||
groupId !== undefined
|
||||
? { bridge, groupId, forwardFake: true, scene: 'forward' as const }
|
||||
: userUid
|
||||
? { bridge, userUid, forwardFake: true, scene: 'forward' as const }
|
||||
@@ -130,8 +146,10 @@ async function buildForwardPushBody(
|
||||
// a live c2c send. Group nodes ignore this branch entirely (the
|
||||
// transElem(24) elems[] entry above covers them).
|
||||
let msgContent: Uint8Array | undefined;
|
||||
|
||||
if (groupId === undefined) {
|
||||
const fileEl = node.elements.find(e => e.type === 'file' && e.fileId);
|
||||
const fileEl = node.elements.find((e) => e.type === 'file' && e.fileId);
|
||||
|
||||
if (fileEl) {
|
||||
// Honour inline segment fields first; fall back to the upload
|
||||
// metadata cache (populated by upload_private_file). Without
|
||||
@@ -198,20 +216,29 @@ async function buildForwardPushBody(
|
||||
function deriveInnerSource(innerNodes: ForwardNodePayload[], isGroup: boolean): string {
|
||||
const nicks: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const node of innerNodes) {
|
||||
const name = (node.nickname ?? '').trim();
|
||||
|
||||
if (name && !seen.has(name)) {
|
||||
seen.add(name);
|
||||
nicks.push(name);
|
||||
}
|
||||
if (nicks.length >= 4) break;
|
||||
|
||||
if (nicks.length >= 4) {
|
||||
break;
|
||||
}
|
||||
if (nicks.length === 0) return isGroup ? '群聊的聊天记录' : '聊天记录';
|
||||
}
|
||||
|
||||
if (nicks.length === 0) {
|
||||
return isGroup ? '群聊的聊天记录' : '聊天记录';
|
||||
}
|
||||
|
||||
return `${nicks.join('和')}的聊天记录`;
|
||||
}
|
||||
|
||||
function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text: string }> {
|
||||
return innerNodes.slice(0, 4).map(node => {
|
||||
return innerNodes.slice(0, 4).map((node) => {
|
||||
const name = (node.nickname ?? '').trim() || String(node.userUin || 'QQ用户');
|
||||
const previewText = previewFromElements(node.elements);
|
||||
return { text: previewText ? `${name}: ${previewText}` : name };
|
||||
@@ -220,22 +247,46 @@ function previewLinesFromNodes(innerNodes: ForwardNodePayload[]): Array<{ text:
|
||||
|
||||
function previewFromElements(elements: MessageElement[]): string {
|
||||
for (const elem of elements) {
|
||||
if (elem.type === 'text' && elem.text) return elem.text.slice(0, 30);
|
||||
if (elem.type === 'image') return '[图片]';
|
||||
if (elem.type === 'record') return '[语音]';
|
||||
if (elem.type === 'video') return '[视频]';
|
||||
if (elem.type === 'file') return '[文件]';
|
||||
if (elem.type === 'forward') return '[聊天记录]';
|
||||
if (elem.type === 'face') return '[表情]';
|
||||
if (elem.type === 'text' && elem.text) {
|
||||
return elem.text.slice(0, 30);
|
||||
}
|
||||
|
||||
if (elem.type === 'image') {
|
||||
return '[图片]';
|
||||
}
|
||||
|
||||
if (elem.type === 'record') {
|
||||
return '[语音]';
|
||||
}
|
||||
|
||||
if (elem.type === 'video') {
|
||||
return '[视频]';
|
||||
}
|
||||
|
||||
if (elem.type === 'file') {
|
||||
return '[文件]';
|
||||
}
|
||||
|
||||
if (elem.type === 'forward') {
|
||||
return '[聊天记录]';
|
||||
}
|
||||
|
||||
if (elem.type === 'face') {
|
||||
return '[表情]';
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload {
|
||||
function cloneNodeWithElements(
|
||||
node: ForwardNodePayload,
|
||||
elements: MessageElement[],
|
||||
): ForwardNodePayload {
|
||||
return {
|
||||
...node,
|
||||
elements,
|
||||
news: node.news?.map(item => ({ ...item })),
|
||||
news: node.news?.map((item) => ({ ...item })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -250,13 +301,18 @@ function isCachedFileUsableInTarget(
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): boolean {
|
||||
if (!cached) return true;
|
||||
if (!cached) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (groupId !== undefined) {
|
||||
return cached.scope === 'group' && cached.groupId === groupId;
|
||||
}
|
||||
|
||||
if (userId !== undefined) {
|
||||
return cached.scope === 'private' && cached.userId === userId;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -267,6 +323,7 @@ function fileNameForUpload(element: MessageElement, cached?: UploadedFileMeta):
|
||||
function assertPrivateForwardFileCapacity(nodes: ForwardNodePayload[]): void {
|
||||
for (const node of nodes) {
|
||||
const fileCount = node.elements.filter((element) => element.type === 'file').length;
|
||||
|
||||
if (fileCount > 1) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
@@ -274,7 +331,10 @@ function assertPrivateForwardFileCapacity(nodes: ForwardNodePayload[]): void {
|
||||
'file',
|
||||
);
|
||||
}
|
||||
if (node.innerForward) assertPrivateForwardFileCapacity(node.innerForward);
|
||||
|
||||
if (node.innerForward) {
|
||||
assertPrivateForwardFileCapacity(node.innerForward);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,7 +345,10 @@ function assertNoWindowShakeInForward(nodes: ForwardNodePayload[]): void {
|
||||
node.elements.length,
|
||||
'forward',
|
||||
);
|
||||
if (node.innerForward) assertNoWindowShakeInForward(node.innerForward);
|
||||
|
||||
if (node.innerForward) {
|
||||
assertNoWindowShakeInForward(node.innerForward);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,10 +359,14 @@ export class ForwardApi {
|
||||
// Reject the complete recursive tree before identity resolution, media
|
||||
// upload, or long-message upload. Window shake has no forward wire form.
|
||||
assertNoWindowShakeInForward(nodes);
|
||||
|
||||
// A c2c RichText owns exactly one msgContent/FileExtra payload. Validate
|
||||
// the entire recursive tree before any file/media/long-message upload so a
|
||||
// second file cannot be uploaded and then silently discarded.
|
||||
if (groupId === undefined) assertPrivateForwardFileCapacity(nodes);
|
||||
if (groupId === undefined) {
|
||||
assertPrivateForwardFileCapacity(nodes);
|
||||
}
|
||||
|
||||
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
|
||||
return resId;
|
||||
}
|
||||
@@ -308,10 +375,18 @@ export class ForwardApi {
|
||||
if (cached.scope === 'group' && cached.groupId !== undefined) {
|
||||
return this.ctx.apis.groupFile.getUrl(cached.groupId, cached.fileId);
|
||||
}
|
||||
|
||||
if (cached.scope === 'private' && cached.userId !== undefined && cached.fileHash) {
|
||||
return this.ctx.apis.groupFile.getPrivateUrl(cached.userId, cached.fileId, cached.fileHash);
|
||||
return this.ctx.apis.groupFile.getPrivateUrl(
|
||||
cached.userId,
|
||||
cached.fileId,
|
||||
cached.fileHash,
|
||||
);
|
||||
}
|
||||
throw new Error('forward file_id belongs to another scope; pass file/base64/url so SnowLuma can re-upload it');
|
||||
|
||||
throw new Error(
|
||||
'forward file_id belongs to another scope; pass file/base64/url so SnowLuma can re-upload it',
|
||||
);
|
||||
}
|
||||
|
||||
private async uploadForwardFileSource(
|
||||
@@ -321,21 +396,50 @@ export class ForwardApi {
|
||||
userId?: number,
|
||||
): Promise<MessageElementOf<'file'>> {
|
||||
if (groupId !== undefined) {
|
||||
const uploaded = await this.ctx.apis.groupFile.upload(groupId, source, name, '/', true, false);
|
||||
if (!uploaded.fileId) throw new Error('forward group file upload returned no file_id');
|
||||
const uploaded = await this.ctx.apis.groupFile.upload(
|
||||
groupId,
|
||||
source,
|
||||
name,
|
||||
'/',
|
||||
true,
|
||||
false,
|
||||
);
|
||||
|
||||
if (!uploaded.fileId) {
|
||||
throw new Error('forward group file upload returned no file_id');
|
||||
}
|
||||
|
||||
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
|
||||
const element: MessageElement = {
|
||||
type: 'file',
|
||||
fileId: uploaded.fileId,
|
||||
};
|
||||
const fileName = cached?.fileName || name;
|
||||
if (fileName) element.fileName = fileName;
|
||||
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
|
||||
|
||||
if (fileName) {
|
||||
element.fileName = fileName;
|
||||
}
|
||||
|
||||
if (cached?.fileSize !== undefined) {
|
||||
element.fileSize = cached.fileSize;
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
if (userId !== undefined) {
|
||||
const uploaded = await this.ctx.apis.groupFile.uploadPrivate(userId, source, name, true, false);
|
||||
if (!uploaded.fileId) throw new Error('forward private file upload returned no file_id');
|
||||
const uploaded = await this.ctx.apis.groupFile.uploadPrivate(
|
||||
userId,
|
||||
source,
|
||||
name,
|
||||
true,
|
||||
false,
|
||||
);
|
||||
|
||||
if (!uploaded.fileId) {
|
||||
throw new Error('forward private file upload returned no file_id');
|
||||
}
|
||||
|
||||
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
|
||||
const element: MessageElement = {
|
||||
type: 'file',
|
||||
@@ -343,11 +447,22 @@ export class ForwardApi {
|
||||
};
|
||||
const fileName = cached?.fileName || name;
|
||||
const fileHash = uploaded.fileHash ?? cached?.fileHash ?? '';
|
||||
if (fileName) element.fileName = fileName;
|
||||
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
|
||||
if (fileHash) element.fileHash = fileHash;
|
||||
|
||||
if (fileName) {
|
||||
element.fileName = fileName;
|
||||
}
|
||||
|
||||
if (cached?.fileSize !== undefined) {
|
||||
element.fileSize = cached.fileSize;
|
||||
}
|
||||
|
||||
if (fileHash) {
|
||||
element.fileHash = fileHash;
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
throw new Error('forward file source requires group_id or user_id');
|
||||
}
|
||||
|
||||
@@ -356,11 +471,19 @@ export class ForwardApi {
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<MessageElement> {
|
||||
if (element.type !== 'file') return element;
|
||||
if (element.type !== 'file') {
|
||||
return element;
|
||||
}
|
||||
|
||||
const source = (element.url ?? '').trim();
|
||||
|
||||
if (source && !element.fileId) {
|
||||
const uploaded = await this.uploadForwardFileSource(source, fileNameForUpload(element), groupId, userId);
|
||||
const uploaded = await this.uploadForwardFileSource(
|
||||
source,
|
||||
fileNameForUpload(element),
|
||||
groupId,
|
||||
userId,
|
||||
);
|
||||
return {
|
||||
...stripFileSource(element),
|
||||
...uploaded,
|
||||
@@ -369,7 +492,11 @@ export class ForwardApi {
|
||||
|
||||
if (element.fileId) {
|
||||
const cached = this.ctx.recallUploadedFile(element.fileId);
|
||||
if (isCachedFileUsableInTarget(cached, groupId, userId)) return element;
|
||||
|
||||
if (isCachedFileUsableInTarget(cached, groupId, userId)) {
|
||||
return element;
|
||||
}
|
||||
|
||||
const sourceFromCache = await this.downloadSourceFromCachedFile(cached!);
|
||||
const uploaded = await this.uploadForwardFileSource(
|
||||
sourceFromCache,
|
||||
@@ -391,12 +518,16 @@ export class ForwardApi {
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<ForwardNodePayload[]> {
|
||||
return Promise.all(nodes.map(async (node) => {
|
||||
const elements = await Promise.all(node.elements.map(
|
||||
element => this.prepareForwardFileElement(element, groupId, userId),
|
||||
));
|
||||
return Promise.all(
|
||||
nodes.map(async (node) => {
|
||||
const elements = await Promise.all(
|
||||
node.elements.map((element) =>
|
||||
this.prepareForwardFileElement(element, groupId, userId),
|
||||
),
|
||||
);
|
||||
return cloneNodeWithElements(node, elements);
|
||||
}));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -430,12 +561,22 @@ export class ForwardApi {
|
||||
// for text-only forwards). Also need it when a node is itself a nested
|
||||
// forward — the inner upload uses the same scene.
|
||||
let userUid: string | undefined;
|
||||
|
||||
if (groupId === undefined && userId !== undefined && userId > 0) {
|
||||
const needsUid = nodes.some(node => !!node.innerForward
|
||||
|| node.elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video'));
|
||||
const needsUid = nodes.some(
|
||||
(node) =>
|
||||
!!node.innerForward ||
|
||||
node.elements.some(
|
||||
(e) => e.type === 'image' || e.type === 'record' || e.type === 'video',
|
||||
),
|
||||
);
|
||||
|
||||
if (needsUid) {
|
||||
const resolved = await this.ctx.resolveUserUid(userId);
|
||||
if (resolved) userUid = resolved;
|
||||
|
||||
if (resolved) {
|
||||
userUid = resolved;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -454,6 +595,7 @@ export class ForwardApi {
|
||||
const myInnerActions: ForwardInnerAction[] = [];
|
||||
const processedNodes: ForwardNodePayload[] = [];
|
||||
const isGroup = groupId !== undefined;
|
||||
|
||||
for (const node of nodes) {
|
||||
if (node.innerForward && node.innerForward.length > 0) {
|
||||
const inner = await this.uploadRecursive(node.innerForward, groupId, userId);
|
||||
@@ -471,16 +613,20 @@ export class ForwardApi {
|
||||
type: 'forward',
|
||||
resId: inner.resId,
|
||||
forwardUuid: inner.uuid,
|
||||
forwardSource: node.source && node.source.length > 0
|
||||
forwardSource:
|
||||
node.source && node.source.length > 0
|
||||
? node.source
|
||||
: deriveInnerSource(node.innerForward, isGroup),
|
||||
forwardSummary: node.summary && node.summary.length > 0
|
||||
forwardSummary:
|
||||
node.summary && node.summary.length > 0
|
||||
? node.summary
|
||||
: `查看${node.innerForward.length}条转发消息`,
|
||||
forwardPrompt: node.prompt && node.prompt.length > 0
|
||||
? node.prompt
|
||||
: '[聊天记录]',
|
||||
forwardNews: node.news && node.news.length > 0 ? node.news : previewLinesFromNodes(node.innerForward),
|
||||
forwardPrompt:
|
||||
node.prompt && node.prompt.length > 0 ? node.prompt : '[聊天记录]',
|
||||
forwardNews:
|
||||
node.news && node.news.length > 0
|
||||
? node.news
|
||||
: previewLinesFromNodes(node.innerForward),
|
||||
forwardTSum: node.innerForward.length,
|
||||
};
|
||||
const processed = cloneNodeWithElements(node, [previewElement]);
|
||||
@@ -494,15 +640,15 @@ export class ForwardApi {
|
||||
const uploadReadyNodes = await this.prepareForwardFiles(processedNodes, groupId, userId);
|
||||
|
||||
// Encode this level's msgBody.
|
||||
const msgBody = await Promise.all(uploadReadyNodes.map(
|
||||
node => buildForwardPushBody(bridge, node, groupId, userUid),
|
||||
));
|
||||
const msgBody = await Promise.all(
|
||||
uploadReadyNodes.map((node) => buildForwardPushBody(bridge, node, groupId, userUid)),
|
||||
);
|
||||
|
||||
// Compose the action list: own MultiMsg + piggybacked inner actions.
|
||||
const longMsgResult = protobuf_encode<LongMsgResult>({
|
||||
action: [
|
||||
{ actionCommand: 'MultiMsg', actionData: { msgBody } },
|
||||
...myInnerActions.map(a => ({
|
||||
...myInnerActions.map((a) => ({
|
||||
actionCommand: a.uuid,
|
||||
actionData: { msgBody: a.msgBody },
|
||||
})),
|
||||
@@ -515,7 +661,10 @@ export class ForwardApi {
|
||||
uid: { uid: groupId ? String(groupId) : selfUid },
|
||||
payload: gzipSync(Buffer.from(longMsgResult)),
|
||||
};
|
||||
if (groupId) info.groupUin = groupId;
|
||||
|
||||
if (groupId) {
|
||||
info.groupUin = groupId;
|
||||
}
|
||||
|
||||
const request = protobuf_encode<SendLongMsgReq>({
|
||||
info,
|
||||
@@ -527,22 +676,30 @@ export class ForwardApi {
|
||||
},
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request);
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'trpc.group.long_msg_interface.MsgService.SsoSendLongMsg',
|
||||
request,
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'upload forward message failed');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<SendLongMsgResp>(result.responseData);
|
||||
const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : '';
|
||||
|
||||
if (!resId) {
|
||||
throw new Error('upload forward message response missing res_id');
|
||||
}
|
||||
|
||||
forwardResCache.set(resId, uploadReadyNodes.map(node => ({
|
||||
forwardResCache.set(
|
||||
resId,
|
||||
uploadReadyNodes.map((node) => ({
|
||||
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
|
||||
groupId: node.groupId ?? groupId,
|
||||
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
|
||||
})));
|
||||
})),
|
||||
);
|
||||
|
||||
return {
|
||||
resId,
|
||||
@@ -563,11 +720,16 @@ export class ForwardApi {
|
||||
async fetch(resId: string): Promise<ForwardNodePayload[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cached = forwardResCache.get(resId);
|
||||
|
||||
if (cached) {
|
||||
const nodes = cloneNodes(cached);
|
||||
|
||||
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
|
||||
// on read (a no-op once names are present) and persist so later hits skip.
|
||||
if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes));
|
||||
if (await this.enrichSenders(nodes)) {
|
||||
forwardResCache.set(resId, cloneNodes(nodes));
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}
|
||||
|
||||
@@ -586,18 +748,24 @@ export class ForwardApi {
|
||||
},
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg', request);
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'trpc.group.long_msg_interface.MsgService.SsoRecvLongMsg',
|
||||
request,
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'download forward message failed');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<RecvLongMsgResp>(result.responseData);
|
||||
const payload = resp?.result?.payload;
|
||||
|
||||
if (!(payload instanceof Uint8Array) || payload.length === 0) {
|
||||
throw new Error('download forward message payload is empty');
|
||||
}
|
||||
|
||||
let inflate: Buffer;
|
||||
|
||||
try {
|
||||
inflate = gunzipSync(Buffer.from(payload), {
|
||||
maxOutputLength: FORWARD_LONG_MSG_MAX_OUTPUT_BYTES,
|
||||
@@ -618,10 +786,13 @@ export class ForwardApi {
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
|
||||
const longMsg = protobuf_decode<LongMsgResult>(inflate);
|
||||
const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : [];
|
||||
const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg');
|
||||
const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody) ? mainAction!.actionData!.msgBody : [];
|
||||
const mainAction = actions.find((item) => item?.actionCommand === 'MultiMsg');
|
||||
const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody)
|
||||
? mainAction!.actionData!.msgBody
|
||||
: [];
|
||||
|
||||
// Piggyback index: any non-`MultiMsg` action carries an inner
|
||||
// layer keyed by the uuid the sender baked into its forward
|
||||
@@ -630,9 +801,14 @@ export class ForwardApi {
|
||||
// server roundtrip — matches the sender-side piggyback emitted in
|
||||
// `uploadRecursive` above.
|
||||
const piggybackByUuid = new Map<string, PushMsgBody[]>();
|
||||
|
||||
for (const action of actions) {
|
||||
const cmd = action?.actionCommand;
|
||||
if (!cmd || cmd === 'MultiMsg') continue;
|
||||
|
||||
if (!cmd || cmd === 'MultiMsg') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const body = Array.isArray(action.actionData?.msgBody) ? action.actionData.msgBody : [];
|
||||
piggybackByUuid.set(cmd, body);
|
||||
}
|
||||
@@ -656,6 +832,7 @@ export class ForwardApi {
|
||||
if (nodes.length > 0) {
|
||||
forwardResCache.set(resId, cloneNodes(nodes));
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}
|
||||
|
||||
@@ -672,13 +849,18 @@ export class ForwardApi {
|
||||
* placeholder rather than failing the whole forward. Returns true if any
|
||||
* node was changed (so callers can persist the enriched cache). */
|
||||
private async enrichSenders(nodes: ForwardNodePayload[]): Promise<boolean> {
|
||||
const pending = nodes.filter(n => this.needsName(n));
|
||||
if (pending.length === 0) return false;
|
||||
const pending = nodes.filter((n) => this.needsName(n));
|
||||
|
||||
if (pending.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let changed = false;
|
||||
|
||||
// L3 — group member lists (one fetch resolves every sender from that group).
|
||||
const byGroup = new Map<number, ForwardNodePayload[]>();
|
||||
const residue: ForwardNodePayload[] = [];
|
||||
|
||||
for (const n of pending) {
|
||||
if (n.messageType === 'group' && n.groupId) {
|
||||
const arr = byGroup.get(n.groupId) ?? [];
|
||||
@@ -688,20 +870,26 @@ export class ForwardApi {
|
||||
residue.push(n);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [groupId, groupNodes] of byGroup) {
|
||||
let byUin: Map<number, { nickname: string; card: string }>;
|
||||
|
||||
try {
|
||||
const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId);
|
||||
byUin = new Map(members.map(m => [m.uin, { nickname: m.nickname, card: m.card }]));
|
||||
byUin = new Map(
|
||||
members.map((m) => [m.uin, { nickname: m.nickname, card: m.card }]),
|
||||
);
|
||||
} catch {
|
||||
// Member list (one cheap, cached call) failed — keep the placeholder
|
||||
// rather than fanning the whole group out to per-uin profile lookups.
|
||||
// That error path is exactly what would amplify into a rate-limit ban.
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const n of groupNodes) {
|
||||
const m = byUin.get(n.userUin);
|
||||
const name = m?.card || m?.nickname;
|
||||
|
||||
if (name) {
|
||||
n.senderCard = m!.card || n.senderCard || '';
|
||||
n.nickname = name;
|
||||
@@ -717,22 +905,45 @@ export class ForwardApi {
|
||||
// Tencent rate-limits these hard (see ContactsApi's member-list note), so:
|
||||
// dedupe by uin, CAP the count (drop the rest to placeholder), and resolve
|
||||
// in small concurrency-limited batches. Best-effort.
|
||||
const uins = [...new Set(residue.filter(n => this.needsName(n)).map(n => n.userUin))]
|
||||
.slice(0, FORWARD_PROFILE_MAX);
|
||||
const uins = [
|
||||
...new Set(residue.filter((n) => this.needsName(n)).map((n) => n.userUin)),
|
||||
].slice(0, FORWARD_PROFILE_MAX);
|
||||
|
||||
if (uins.length > 0) {
|
||||
const byUin = new Map<number, string>();
|
||||
const results = await mapWithConcurrency(uins, FORWARD_PROFILE_CONCURRENCY,
|
||||
const results = await mapWithConcurrency(
|
||||
uins,
|
||||
FORWARD_PROFILE_CONCURRENCY,
|
||||
async (uin): Promise<readonly [number, string]> => {
|
||||
try { return [uin, (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname] as const; }
|
||||
catch { return [uin, ''] as const; }
|
||||
});
|
||||
for (const [uin, nick] of results) byUin.set(uin, nick);
|
||||
try {
|
||||
return [
|
||||
uin,
|
||||
(await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname,
|
||||
] as const;
|
||||
} catch {
|
||||
return [uin, ''] as const;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
for (const [uin, nick] of results) {
|
||||
byUin.set(uin, nick);
|
||||
}
|
||||
|
||||
for (const n of residue) {
|
||||
if (!this.needsName(n)) continue;
|
||||
if (!this.needsName(n)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const nick = byUin.get(n.userUin);
|
||||
if (nick) { n.nickname = nick; changed = true; }
|
||||
|
||||
if (nick) {
|
||||
n.nickname = nick;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
@@ -741,6 +952,7 @@ export class ForwardApi {
|
||||
* so both the outer + piggyback decode paths share one implementation. */
|
||||
private decodeMsgBodiesToNodes(msgBodyList: PushMsgBody[]): ForwardNodePayload[] {
|
||||
const out: ForwardNodePayload[] = [];
|
||||
|
||||
for (const msgBody of msgBodyList) {
|
||||
const wrapped = protobuf_encode<PushMsg>({ message: msgBody });
|
||||
const pkt: PacketInfo = {
|
||||
@@ -753,9 +965,16 @@ export class ForwardApi {
|
||||
body: wrapped,
|
||||
};
|
||||
const events = parseMsgPush(pkt, this.ctx.identity);
|
||||
const event = events.find(e =>
|
||||
e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
|
||||
if (!event) continue;
|
||||
const event = events.find(
|
||||
(e) =>
|
||||
e.kind === 'friend_message' ||
|
||||
e.kind === 'group_message' ||
|
||||
e.kind === 'temp_message',
|
||||
);
|
||||
|
||||
if (!event) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.kind === 'group_message') {
|
||||
// [#201] The merged-forward sender name now comes through the group
|
||||
@@ -794,6 +1013,7 @@ export class ForwardApi {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -809,15 +1029,27 @@ export class ForwardApi {
|
||||
piggybackByUuid: Map<string, PushMsgBody[]>,
|
||||
): void {
|
||||
const seen = new Set<string>();
|
||||
|
||||
const visit = (chain: ForwardNodePayload[]): void => {
|
||||
for (const node of chain) {
|
||||
for (const elem of node.elements) {
|
||||
if (elem.type !== 'forward') continue;
|
||||
if (elem.type !== 'forward') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const uuid = elem.forwardUuid;
|
||||
const innerResId = elem.resId;
|
||||
if (!uuid || !innerResId || seen.has(uuid)) continue;
|
||||
|
||||
if (!uuid || !innerResId || seen.has(uuid)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const body = piggybackByUuid.get(uuid);
|
||||
if (!body) continue;
|
||||
|
||||
if (!body) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(uuid);
|
||||
const innerNodes = this.decodeMsgBodiesToNodes(body);
|
||||
forwardResCache.set(innerResId, cloneNodes(innerNodes));
|
||||
@@ -825,18 +1057,29 @@ export class ForwardApi {
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
visit(nodes);
|
||||
}
|
||||
}
|
||||
|
||||
function cacheableForwardElement(element: MessageElement): MessageElement {
|
||||
if (element.type !== 'image') return element;
|
||||
if (element.imageUrl || element.fileId || element.md5Hex) return element;
|
||||
if (element.type !== 'image') {
|
||||
return element;
|
||||
}
|
||||
|
||||
if (element.imageUrl || element.fileId || element.md5Hex) {
|
||||
return element;
|
||||
}
|
||||
|
||||
const source = (element.url ?? '').trim();
|
||||
if (!source) return element;
|
||||
|
||||
if (!source) {
|
||||
return element;
|
||||
}
|
||||
|
||||
return { ...element, imageUrl: source };
|
||||
}
|
||||
|
||||
function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] {
|
||||
return nodes.map(node => cloneNodeWithElements(node, [...node.elements]));
|
||||
return nodes.map((node) => cloneNodeWithElements(node, [...node.elements]));
|
||||
}
|
||||
@@ -3,7 +3,10 @@ import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-cont
|
||||
import { ApproveDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/approve-doubt-buddy-req';
|
||||
import { ClearFriendRemark } from '@snowluma/protocol/oidb-services/friend/clear-friend-remark';
|
||||
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
|
||||
import { GetDoubtBuddyReq, type DoubtBuddyRequest } from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req';
|
||||
import {
|
||||
GetDoubtBuddyReq,
|
||||
type DoubtBuddyRequest,
|
||||
} from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req';
|
||||
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
|
||||
import { RejectDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/reject-doubt-buddy-req';
|
||||
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
|
||||
@@ -28,6 +31,7 @@ export class FriendApi {
|
||||
if (findDatalineDeviceByUin(userId)) {
|
||||
throw new Error('this contact cannot be deleted');
|
||||
}
|
||||
|
||||
await DeleteFriend.invoke(this.ctx, { userId, block });
|
||||
|
||||
// The server-side delete has already completed. A refresh failure must be
|
||||
@@ -48,22 +52,27 @@ export class FriendApi {
|
||||
if (findDatalineDeviceByUin(userId)) {
|
||||
throw new Error('this contact does not support remarks');
|
||||
}
|
||||
|
||||
if (remark === '') {
|
||||
await ClearFriendRemark.invoke(this.ctx, { userId });
|
||||
return;
|
||||
}
|
||||
|
||||
await SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||
}
|
||||
|
||||
/** List doubtful friend-add requests (可能认识的人). */
|
||||
async getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
|
||||
const list = await GetDoubtBuddyReq.invoke(this.ctx, { count });
|
||||
return Promise.all(list.map(async (item) => {
|
||||
return Promise.all(
|
||||
list.map(async (item) => {
|
||||
let uid = item.uid;
|
||||
let userId = item.user_id;
|
||||
|
||||
if (userId <= 0 && uid) {
|
||||
userId = this.ctx.identity.findUinByUid(uid) ?? 0;
|
||||
}
|
||||
|
||||
// Applicants need not be friends or share a group. Use Identity's
|
||||
// profile lookup when the list only supplies an account number.
|
||||
if (!uid && userId > 0) {
|
||||
@@ -77,8 +86,10 @@ export class FriendApi {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { ...item, uid: uid || '', user_id: userId };
|
||||
}));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */
|
||||
@@ -103,7 +114,10 @@ export class FriendApi {
|
||||
* by the server. Same rule as inbound friend-request handling.
|
||||
*/
|
||||
private resolveDoubtFlag(uidOrFlag: string): Promise<string> {
|
||||
if (!/^\d+$/.test(uidOrFlag)) return Promise.resolve(uidOrFlag);
|
||||
if (!/^\d+$/.test(uidOrFlag)) {
|
||||
return Promise.resolve(uidOrFlag);
|
||||
}
|
||||
|
||||
return this.ctx.resolveUserUid(parseInt(uidOrFlag, 10));
|
||||
}
|
||||
}
|
||||
@@ -68,8 +68,16 @@ export class GroupAdminApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
/** Set the group's robot-add option (switch / examine) via group ext-info. */
|
||||
setRobotAddOption(groupId: number, robotMemberSwitch?: number, robotMemberExamine?: number): Promise<void> {
|
||||
return ModifyGroupExtInfo.invoke(this.ctx, { groupId, robotMemberSwitch, robotMemberExamine });
|
||||
setRobotAddOption(
|
||||
groupId: number,
|
||||
robotMemberSwitch?: number,
|
||||
robotMemberExamine?: number,
|
||||
): Promise<void> {
|
||||
return ModifyGroupExtInfo.invoke(this.ctx, {
|
||||
groupId,
|
||||
robotMemberSwitch,
|
||||
robotMemberExamine,
|
||||
});
|
||||
}
|
||||
|
||||
async getAdminSettings(groupId: number): Promise<GroupAdminSettings> {
|
||||
@@ -78,9 +86,11 @@ export class GroupAdminApi {
|
||||
FetchGroupExtInfo.invoke(this.ctx, { groupId }),
|
||||
]);
|
||||
const results = detail.groupInfo?.results;
|
||||
|
||||
if (!results) {
|
||||
throw new Error(`unable to read group admin settings for group ${groupId}`);
|
||||
}
|
||||
|
||||
const privilegeFlag = results.privilegeFlag ?? 0;
|
||||
const permissions = decodeGroupMemberPermissions(privilegeFlag);
|
||||
return {
|
||||
@@ -120,7 +130,9 @@ export class GroupAdminApi {
|
||||
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
|
||||
}
|
||||
|
||||
listCategoryTags(groupClass: number): Promise<{ tags: { id: number; name: string; type: number }[] }> {
|
||||
listCategoryTags(
|
||||
groupClass: number,
|
||||
): Promise<{ tags: { id: number; name: string; type: number }[] }> {
|
||||
return GetGroupCategoryTags.invoke(this.ctx, { groupClass });
|
||||
}
|
||||
|
||||
@@ -152,12 +164,17 @@ export class GroupAdminApi {
|
||||
'after update',
|
||||
);
|
||||
const mask = BigInt(MEMBER_INVITE_PRIVILEGE_MASK);
|
||||
|
||||
if ((BigInt(actualPrivilegeFlag) & mask) !== (BigInt(expectedPrivilegeFlag) & mask)) {
|
||||
throw new Error(`group member invite policy was not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchGroupPrivilegeFlag(groupId: number, setting: string, phase: string): Promise<number> {
|
||||
private async fetchGroupPrivilegeFlag(
|
||||
groupId: number,
|
||||
setting: string,
|
||||
phase: string,
|
||||
): Promise<number> {
|
||||
return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag;
|
||||
}
|
||||
|
||||
@@ -168,21 +185,27 @@ export class GroupAdminApi {
|
||||
): Promise<{ privilegeFlag: number; ownerUid?: string }> {
|
||||
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const results = detail.groupInfo?.results;
|
||||
|
||||
if (!results) {
|
||||
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
|
||||
}
|
||||
|
||||
return {
|
||||
privilegeFlag: results.privilegeFlag ?? 0,
|
||||
ownerUid: results.ownerUid,
|
||||
};
|
||||
}
|
||||
|
||||
async setMemberPermissions(groupId: number, permissions: GroupMemberPermissions): Promise<void> {
|
||||
async setMemberPermissions(
|
||||
groupId: number,
|
||||
permissions: GroupMemberPermissions,
|
||||
): Promise<void> {
|
||||
const updates: ReadonlyArray<readonly [GroupMemberPermission, boolean | undefined]> = [
|
||||
['upload_album', permissions.allowMemberUploadAlbum],
|
||||
['temporary_session', permissions.allowMemberTemporarySession],
|
||||
['create_group', permissions.allowMemberCreateGroup],
|
||||
];
|
||||
|
||||
if (!updates.some(([, allow]) => allow !== undefined)) {
|
||||
throw new Error('at least one member permission must be specified');
|
||||
}
|
||||
@@ -193,6 +216,7 @@ export class GroupAdminApi {
|
||||
'before update',
|
||||
);
|
||||
const selfUid = this.ctx.identity.selfUid;
|
||||
|
||||
if (selfUid && before.ownerUid && selfUid !== before.ownerUid) {
|
||||
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
}
|
||||
@@ -201,7 +225,10 @@ export class GroupAdminApi {
|
||||
let combinedMask = 0n;
|
||||
|
||||
for (const [permission, allow] of updates) {
|
||||
if (allow === undefined) continue;
|
||||
if (allow === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await SetMemberPermission.invoke(this.ctx, {
|
||||
groupId,
|
||||
@@ -213,9 +240,15 @@ export class GroupAdminApi {
|
||||
if (error instanceof OidbError && error.code === 1287) {
|
||||
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
expectedPrivilegeFlag = mergeGroupMemberPermission(expectedPrivilegeFlag, permission, allow);
|
||||
|
||||
expectedPrivilegeFlag = mergeGroupMemberPermission(
|
||||
expectedPrivilegeFlag,
|
||||
permission,
|
||||
allow,
|
||||
);
|
||||
combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]);
|
||||
}
|
||||
|
||||
@@ -224,7 +257,11 @@ export class GroupAdminApi {
|
||||
'group member permissions',
|
||||
'after update',
|
||||
);
|
||||
if ((BigInt(actualPrivilegeFlag) & combinedMask) !== (BigInt(expectedPrivilegeFlag) & combinedMask)) {
|
||||
|
||||
if (
|
||||
(BigInt(actualPrivilegeFlag) & combinedMask) !==
|
||||
(BigInt(expectedPrivilegeFlag) & combinedMask)
|
||||
) {
|
||||
throw new Error(`group member permissions were not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
@@ -233,6 +270,7 @@ export class GroupAdminApi {
|
||||
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
|
||||
|
||||
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
|
||||
|
||||
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
|
||||
throw new Error(`new-member history visibility was not applied for group ${groupId}`);
|
||||
}
|
||||
@@ -241,19 +279,33 @@ export class GroupAdminApi {
|
||||
private async fetchGroupFlagExt4(groupId: number, phase: string): Promise<number> {
|
||||
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const results = detail.groupInfo?.results;
|
||||
|
||||
if (!results) {
|
||||
throw new Error(`unable to read new-member history visibility ${phase} for group ${groupId}`);
|
||||
throw new Error(
|
||||
`unable to read new-member history visibility ${phase} for group ${groupId}`,
|
||||
);
|
||||
}
|
||||
|
||||
return results.groupFlagExt4 ?? 0;
|
||||
}
|
||||
|
||||
setAddRequest(
|
||||
groupId: number, sequence: number, eventType: number,
|
||||
approve: boolean, reason = '', filtered = false,
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
eventType: number,
|
||||
approve: boolean,
|
||||
reason = '',
|
||||
filtered = false,
|
||||
operateTransInfo?: Uint8Array,
|
||||
): Promise<void> {
|
||||
return SetAddRequest.invoke(this.ctx, {
|
||||
groupId, sequence, eventType, approve, reason, filtered, operateTransInfo,
|
||||
groupId,
|
||||
sequence,
|
||||
eventType,
|
||||
approve,
|
||||
reason,
|
||||
filtered,
|
||||
operateTransInfo,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,10 @@ import type {
|
||||
MediaInfo,
|
||||
UrlInfo,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-album';
|
||||
import { uploadImageToGroupAlbum, uploadVideoToGroupAlbum } from '@snowluma/protocol/web/group-album';
|
||||
import {
|
||||
uploadImageToGroupAlbum,
|
||||
uploadVideoToGroupAlbum,
|
||||
} from '@snowluma/protocol/web/group-album';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
@@ -41,14 +44,19 @@ function uint64ToString(value: bigint | undefined): string {
|
||||
|
||||
function uint64ToSafeNumber(value: bigint | undefined, fieldName: string): number {
|
||||
const normalized = value ?? 0n;
|
||||
|
||||
if (normalized > BigInt(Number.MAX_SAFE_INTEGER)) {
|
||||
throw new Error(`group album ${fieldName} exceeds Number.MAX_SAFE_INTEGER: ${normalized}`);
|
||||
}
|
||||
|
||||
return Number(normalized);
|
||||
}
|
||||
|
||||
function normalizeAlbumCreator(creator: AlbumCreator | undefined): QunAlbumCreator | undefined {
|
||||
if (!creator) return undefined;
|
||||
if (!creator) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
uid: creator.uid ?? '',
|
||||
nick: creator.nick ?? '',
|
||||
@@ -66,7 +74,10 @@ function normalizeAlbumCreator(creator: AlbumCreator | undefined): QunAlbumCreat
|
||||
}
|
||||
|
||||
function normalizeCoverUrl(url: UrlInfo | null | undefined): QunAlbumCoverUrl | null {
|
||||
if (!url) return null;
|
||||
if (!url) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
url: url.url ?? '',
|
||||
width: url.width ?? 0,
|
||||
@@ -75,11 +86,15 @@ function normalizeCoverUrl(url: UrlInfo | null | undefined): QunAlbumCoverUrl |
|
||||
}
|
||||
|
||||
function normalizeAlbumCover(cover: MediaInfo | undefined): QunAlbumCover | null {
|
||||
if (!cover) return null;
|
||||
if (!cover) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const image = cover.image;
|
||||
return {
|
||||
type: cover.type ?? 0,
|
||||
image: image ? {
|
||||
image: image
|
||||
? {
|
||||
name: image.name ?? '',
|
||||
sloc: image.sloc ?? '',
|
||||
lloc: image.lloc ?? '',
|
||||
@@ -90,7 +105,8 @@ function normalizeAlbumCover(cover: MediaInfo | undefined): QunAlbumCover | null
|
||||
defaultUrl: normalizeCoverUrl(image.defaultUrl),
|
||||
isGif: image.isGif ?? false,
|
||||
hasRaw: image.hasRaw ?? false,
|
||||
} : null,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -118,7 +134,11 @@ function normalizeQunAlbum(album: GroupAlbumInfoWire): QunAlbumInfo {
|
||||
sort_type: album.sortType ?? 0,
|
||||
};
|
||||
const creator = normalizeAlbumCreator(album.creator);
|
||||
if (creator) normalized.creator = creator;
|
||||
|
||||
if (creator) {
|
||||
normalized.creator = creator;
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
@@ -142,24 +162,42 @@ function toLegacyAlbum(album: GroupAlbumInfoWire): GroupAlbumInfo {
|
||||
}
|
||||
|
||||
function convertBigIntToString(obj: unknown): JsonValue {
|
||||
if (obj === null || obj === undefined) return null;
|
||||
if (typeof obj === 'bigint') return obj.toString();
|
||||
if (Array.isArray(obj)) return obj.map(convertBigIntToString);
|
||||
if (obj === null || obj === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof obj === 'bigint') {
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map(convertBigIntToString);
|
||||
}
|
||||
|
||||
if (typeof obj === 'object') {
|
||||
const result: JsonObject = {};
|
||||
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
result[key] = convertBigIntToString(value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') return obj;
|
||||
|
||||
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') {
|
||||
return obj;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export class GroupAlbumApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
private async fetchAlbumList(groupId: number, attachInfo: string): Promise<GroupAlbumWireResult> {
|
||||
private async fetchAlbumList(
|
||||
groupId: number,
|
||||
attachInfo: string,
|
||||
): Promise<GroupAlbumWireResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
const body = protobuf_encode<GetAlbumListRequest>({
|
||||
seq: GET_ALBUM_LIST_SEQ,
|
||||
@@ -181,6 +219,7 @@ export class GroupAlbumApi {
|
||||
);
|
||||
|
||||
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, packetTimeoutMs());
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(
|
||||
`get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`,
|
||||
@@ -189,6 +228,7 @@ export class GroupAlbumApi {
|
||||
|
||||
const response = protobuf_decode<GetAlbumListResponse>(result.responseData);
|
||||
const resultCode = response.result ?? 0;
|
||||
|
||||
if (resultCode !== 0) {
|
||||
throw new Error(
|
||||
`get group album list failed: result=${resultCode}, error=${response.errorText || 'unknown'}`,
|
||||
@@ -245,12 +285,14 @@ export class GroupAlbumApi {
|
||||
}
|
||||
|
||||
const nextAttachInfo = result.attachInfo;
|
||||
|
||||
if (!nextAttachInfo) {
|
||||
throw new Error(
|
||||
`get group album list pagination failed: group=${groupId} page=${page} `
|
||||
+ 'hasMore=true but cursor is empty',
|
||||
`get group album list pagination failed: group=${groupId} page=${page} ` +
|
||||
'hasMore=true but cursor is empty',
|
||||
);
|
||||
}
|
||||
|
||||
if (seenCursors.has(nextAttachInfo)) {
|
||||
throw new Error(
|
||||
`get group album list pagination failed: group=${groupId} repeated cursor at page ${page}`,
|
||||
@@ -263,21 +305,35 @@ export class GroupAlbumApi {
|
||||
}
|
||||
|
||||
// 上传图片到现有相册(HTTP 分片上传)。
|
||||
async upload(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void> {
|
||||
async upload(
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
albumName: string,
|
||||
filePath: string,
|
||||
): Promise<void> {
|
||||
const groupCode = groupId.toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
|
||||
}
|
||||
|
||||
async uploadVideo(groupId: number, albumId: string, albumName: string, filePath: string): Promise<{ id: string }> {
|
||||
async uploadVideo(
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
albumName: string,
|
||||
filePath: string,
|
||||
): Promise<{ id: string }> {
|
||||
const groupCode = groupId.toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return uploadVideoToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
|
||||
}
|
||||
|
||||
async getMediaList(groupId: number, albumId: string, attachInfo = ''): Promise<GroupAlbumMediaResult> {
|
||||
async getMediaList(
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
attachInfo = '',
|
||||
): Promise<GroupAlbumMediaResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
const body = protobuf_encode<GetMediaListRequest>({
|
||||
@@ -308,6 +364,7 @@ export class GroupAlbumApi {
|
||||
const resp = protobuf_decode<GetMediaListResponse>(result.responseData);
|
||||
|
||||
const retCode = resp.field1 ?? 0;
|
||||
|
||||
if (retCode !== 0) {
|
||||
throw new Error(`fetch album media list error: retCode ${retCode}`);
|
||||
}
|
||||
@@ -316,18 +373,28 @@ export class GroupAlbumApi {
|
||||
const mediaList = data.mediaList ?? [];
|
||||
const nextAttachInfo = data.nextAttachInfo ?? '';
|
||||
|
||||
return convertBigIntToString({ mediaList, nextAttachInfo }) as unknown as GroupAlbumMediaResult;
|
||||
return convertBigIntToString({
|
||||
mediaList,
|
||||
nextAttachInfo,
|
||||
}) as unknown as GroupAlbumMediaResult;
|
||||
}
|
||||
|
||||
async comment(groupId: number, albumId: string, lloc: string, content: string): Promise<GroupAlbumCommentResult> {
|
||||
async comment(
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
lloc: string,
|
||||
content: string,
|
||||
): Promise<GroupAlbumCommentResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
const clientKey = Date.now().toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
const resolved = await this.resolveCommentMedia(groupId, albumId, lloc);
|
||||
const batchId = optionalBatchId(resolved?.batchId);
|
||||
|
||||
if (batchId === undefined) {
|
||||
throw new Error('comment album media error: media not found');
|
||||
}
|
||||
|
||||
const mediaLloc = commentMediaLloc(resolved, lloc);
|
||||
const feed = await this.getQunFeedDetail(groupId, albumId, batchId, mediaLloc);
|
||||
const ownerUin = feed.ownerUin || resolved?.uploader || '';
|
||||
@@ -368,14 +435,16 @@ export class GroupAlbumApi {
|
||||
|
||||
const resp = protobuf_decode<DoQunCommentResponse>(result.responseData);
|
||||
const resultCode = resp.result ?? 0;
|
||||
|
||||
if (resultCode !== 0) {
|
||||
throw new Error(
|
||||
`comment album media error: retCode ${resultCode}`
|
||||
+ (resp.errorText ? `, ${resp.errorText}` : ''),
|
||||
`comment album media error: retCode ${resultCode}` +
|
||||
(resp.errorText ? `, ${resp.errorText}` : ''),
|
||||
);
|
||||
}
|
||||
|
||||
const commentData = commentFromResponse(resp);
|
||||
|
||||
if (!commentData.id) {
|
||||
throw new Error('comment album media error: empty comment');
|
||||
}
|
||||
@@ -392,7 +461,13 @@ export class GroupAlbumApi {
|
||||
}) as unknown as GroupAlbumCommentResult;
|
||||
}
|
||||
|
||||
async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<JsonValue> {
|
||||
async like(
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
batchId: string,
|
||||
lloc: string | undefined,
|
||||
isLike: boolean,
|
||||
): Promise<JsonValue> {
|
||||
const uin = this.ctx.identity.uin;
|
||||
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
@@ -484,7 +559,9 @@ export class GroupAlbumApi {
|
||||
const errMsg = resp.field3;
|
||||
|
||||
if (resCode !== 8694 || errCode) {
|
||||
throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`);
|
||||
throw new Error(
|
||||
`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`,
|
||||
);
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
@@ -502,15 +579,21 @@ export class GroupAlbumApi {
|
||||
try {
|
||||
const seenCursors = new Set<string>();
|
||||
let attachInfo = '';
|
||||
|
||||
while (true) {
|
||||
const page = await this.getMediaList(groupId, albumId, attachInfo);
|
||||
const hit = findDeleteTarget(page.mediaList, mediaKey);
|
||||
if (hit) return hit;
|
||||
|
||||
if (hit) {
|
||||
return hit;
|
||||
}
|
||||
|
||||
const next = page.nextAttachInfo ?? '';
|
||||
|
||||
if (!next || seenCursors.has(next)) {
|
||||
return { mediaId: mediaKey };
|
||||
}
|
||||
|
||||
seenCursors.add(next);
|
||||
attachInfo = next;
|
||||
}
|
||||
@@ -536,13 +619,21 @@ export class GroupAlbumApi {
|
||||
): Promise<AlbumCommentMediaItem | undefined> {
|
||||
const seenCursors = new Set<string>();
|
||||
let attachInfo = '';
|
||||
|
||||
while (true) {
|
||||
const page = await this.getMediaList(groupId, albumId, attachInfo);
|
||||
const hit = findCommentMedia(page.mediaList, mediaKey);
|
||||
if (hit) return hit;
|
||||
|
||||
if (hit) {
|
||||
return hit;
|
||||
}
|
||||
|
||||
const next = page.nextAttachInfo ?? '';
|
||||
if (!next || seenCursors.has(next)) return undefined;
|
||||
|
||||
if (!next || seenCursors.has(next)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
seenCursors.add(next);
|
||||
attachInfo = next;
|
||||
}
|
||||
@@ -572,26 +663,34 @@ export class GroupAlbumApi {
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(GET_QUN_FEED_DETAIL_CMD, body, packetTimeoutMs());
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
GET_QUN_FEED_DETAIL_CMD,
|
||||
body,
|
||||
packetTimeoutMs(),
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to fetch album feed');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<GetQunFeedDetailResponse>(result.responseData);
|
||||
const resultCode = resp.result ?? 0;
|
||||
|
||||
if (resultCode !== 0) {
|
||||
throw new Error(
|
||||
`fetch album feed error: retCode ${resultCode}`
|
||||
+ (resp.errorText ? `, ${resp.errorText}` : ''),
|
||||
`fetch album feed error: retCode ${resultCode}` +
|
||||
(resp.errorText ? `, ${resp.errorText}` : ''),
|
||||
);
|
||||
}
|
||||
|
||||
const feed = resp.data?.feed?.feed;
|
||||
const cell = feed?.cellCommon;
|
||||
const feedId = cell?.feedId ?? '';
|
||||
|
||||
if (!feedId) {
|
||||
throw new Error('comment album media error: empty feed');
|
||||
}
|
||||
|
||||
return {
|
||||
cellCommon: cell ?? { feedId },
|
||||
ownerUin: feed?.cellUserInfo?.user?.uin ?? '',
|
||||
@@ -611,19 +710,25 @@ function findDeleteTarget(
|
||||
mediaKey: string,
|
||||
): { mediaId: string; batchId?: string } | undefined {
|
||||
for (const raw of mediaList) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
if (!raw || typeof raw !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const item = raw as AlbumDeleteMediaItem;
|
||||
const batchId = item.batchId === undefined || item.batchId === ''
|
||||
? undefined
|
||||
: String(item.batchId);
|
||||
const batchId =
|
||||
item.batchId === undefined || item.batchId === '' ? undefined : String(item.batchId);
|
||||
|
||||
if (item.image?.lloc === mediaKey) {
|
||||
return { mediaId: mediaKey, batchId };
|
||||
}
|
||||
|
||||
const coverLloc = item.video?.cover?.lloc;
|
||||
|
||||
if (item.video?.id === mediaKey || coverLloc === mediaKey) {
|
||||
return { mediaId: coverLloc || mediaKey, batchId };
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -649,7 +754,10 @@ interface AlbumCommentMediaItem {
|
||||
}
|
||||
|
||||
function optionalBatchId(value: unknown): bigint | undefined {
|
||||
if (value === undefined || value === null || value === '') return undefined;
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const batchId = BigInt(value as string | number | bigint);
|
||||
return batchId === 0n ? undefined : batchId;
|
||||
@@ -659,8 +767,14 @@ function optionalBatchId(value: unknown): bigint | undefined {
|
||||
}
|
||||
|
||||
function commentMediaLloc(item: AlbumCommentMediaItem | undefined, lloc: string): string {
|
||||
if (item?.video?.cover?.lloc) return item.video.cover.lloc;
|
||||
if (item?.image?.lloc) return item.image.lloc;
|
||||
if (item?.video?.cover?.lloc) {
|
||||
return item.video.cover.lloc;
|
||||
}
|
||||
|
||||
if (item?.image?.lloc) {
|
||||
return item.image.lloc;
|
||||
}
|
||||
|
||||
return lloc;
|
||||
}
|
||||
|
||||
@@ -670,6 +784,7 @@ function mediaInfoForComment(item: AlbumCommentMediaItem | undefined, lloc: stri
|
||||
...(item?.uploader ? { uploader: item.uploader } : {}),
|
||||
...(batchId !== undefined ? { batchId } : {}),
|
||||
};
|
||||
|
||||
if (item?.video) {
|
||||
return {
|
||||
...shared,
|
||||
@@ -677,6 +792,7 @@ function mediaInfoForComment(item: AlbumCommentMediaItem | undefined, lloc: stri
|
||||
video: { cover: { lloc: item.video.cover?.lloc || lloc } },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...shared,
|
||||
type: 0,
|
||||
@@ -691,7 +807,11 @@ function qunFeedCellId(
|
||||
lloc?: string,
|
||||
): string {
|
||||
const head = `421_1_0_${groupId}|${albumId}|${batchId}`;
|
||||
if (!lloc) return head;
|
||||
|
||||
if (!lloc) {
|
||||
return head;
|
||||
}
|
||||
|
||||
return `${head}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
|
||||
}
|
||||
|
||||
@@ -715,6 +835,7 @@ function commentPhotoInfo(
|
||||
batchId: feedMedia.batchId ?? batchId,
|
||||
};
|
||||
}
|
||||
|
||||
return { medias: [fallback], albumId, batchId };
|
||||
}
|
||||
|
||||
@@ -723,18 +844,35 @@ function findCommentMedia(
|
||||
mediaKey: string,
|
||||
): AlbumCommentMediaItem | undefined {
|
||||
for (const raw of mediaList) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
const item = raw as AlbumCommentMediaItem;
|
||||
if (item.image?.lloc === mediaKey) return item;
|
||||
if (item.video?.id === mediaKey || item.video?.cover?.lloc === mediaKey) return item;
|
||||
if (!raw || typeof raw !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const item = raw as AlbumCommentMediaItem;
|
||||
|
||||
if (item.image?.lloc === mediaKey) {
|
||||
return item;
|
||||
}
|
||||
|
||||
if (item.video?.id === mediaKey || item.video?.cover?.lloc === mediaKey) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function commentFromResponse(resp: DoQunCommentResponse): CommentRespData {
|
||||
const wrapped = resp.comment;
|
||||
if (!wrapped) return {};
|
||||
if (wrapped.data?.id) return wrapped.data;
|
||||
|
||||
if (!wrapped) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (wrapped.data?.id) {
|
||||
return wrapped.data;
|
||||
}
|
||||
|
||||
if (wrapped.id) {
|
||||
return {
|
||||
id: wrapped.id,
|
||||
@@ -744,6 +882,7 @@ function commentFromResponse(resp: DoQunCommentResponse): CommentRespData {
|
||||
user: wrapped.data?.user,
|
||||
};
|
||||
}
|
||||
|
||||
return wrapped.data ?? {};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
|
||||
import { FileChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import {
|
||||
FileChunkSource,
|
||||
fetchHighwaySession,
|
||||
uploadHighwayHttp,
|
||||
} from '@snowluma/protocol/highway';
|
||||
import { FILE_UPLOAD_MAX_BYTES } from '@snowluma/protocol/highway/utils';
|
||||
import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
|
||||
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
|
||||
@@ -26,14 +30,19 @@ import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-
|
||||
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
|
||||
import { RenameGroupFile } from '@snowluma/protocol/oidb-services/group-file/rename-group-file';
|
||||
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
|
||||
import { TransGroupFile, type TransGroupFileResult } from '@snowluma/protocol/oidb-services/group-file/trans-group-file';
|
||||
import {
|
||||
TransGroupFile,
|
||||
type TransGroupFileResult,
|
||||
} from '@snowluma/protocol/oidb-services/group-file/trans-group-file';
|
||||
import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request';
|
||||
import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request';
|
||||
import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
|
||||
|
||||
const log = createLogger('GroupFile');
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
function asBridge(ctx: BridgeContext): Bridge {
|
||||
return ctx as unknown as Bridge;
|
||||
}
|
||||
|
||||
// ─────────────── public result types ───────────────
|
||||
|
||||
@@ -78,7 +87,10 @@ export type { MediaIndexNode } from './shared';
|
||||
// ─────────────── file-specific helpers ───────────────
|
||||
|
||||
function normalizeDirectory(dir?: string): string {
|
||||
if (!dir || !dir.trim()) return '/';
|
||||
if (!dir || !dir.trim()) {
|
||||
return '/';
|
||||
}
|
||||
|
||||
return dir;
|
||||
}
|
||||
|
||||
@@ -88,16 +100,20 @@ function normalizeDirectory(dir?: string): string {
|
||||
// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000
|
||||
// into a negative number.
|
||||
function int32ToIpv4Dotted(value: number): string {
|
||||
const b1 = value & 0xFF;
|
||||
const b2 = (value >>> 8) & 0xFF;
|
||||
const b3 = (value >>> 16) & 0xFF;
|
||||
const b4 = (value >>> 24) & 0xFF;
|
||||
const b1 = value & 0xff;
|
||||
const b2 = (value >>> 8) & 0xff;
|
||||
const b3 = (value >>> 16) & 0xff;
|
||||
const b4 = (value >>> 24) & 0xff;
|
||||
return `${b1}.${b2}.${b3}.${b4}`;
|
||||
}
|
||||
|
||||
function normalizeUploadFileName(name: string, fallback: string): string {
|
||||
const trimmed = name.trim();
|
||||
if (trimmed) return trimmed;
|
||||
|
||||
if (trimmed) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const safeFallback = fallback.trim();
|
||||
return safeFallback || 'file.bin';
|
||||
}
|
||||
@@ -111,8 +127,12 @@ const MD5_HEAD_LIMIT = 10002432;
|
||||
/** Fail cleanly if the staged file changed since the streaming hash pass (a
|
||||
* local source mutated mid-send). The server's per-chunk md5 during the PUT is
|
||||
* the backstop; this is the cheap early check. */
|
||||
async function assertUnchanged(filePath: string, baseline: { size: number; mtimeMs: number }): Promise<void> {
|
||||
async function assertUnchanged(
|
||||
filePath: string,
|
||||
baseline: { size: number; mtimeMs: number },
|
||||
): Promise<void> {
|
||||
const now = await fsp.stat(filePath);
|
||||
|
||||
if (now.size !== baseline.size || now.mtimeMs !== baseline.mtimeMs) {
|
||||
throw new Error('file source changed during send (mutated between hashing and upload)');
|
||||
}
|
||||
@@ -241,12 +261,18 @@ export class GroupFileApi {
|
||||
// ─────────────── publish (group file → chat) ───────────────
|
||||
|
||||
publish(groupId: number, fileId: string): Promise<void> {
|
||||
if (!fileId) throw new Error('publish requires fileId');
|
||||
if (!fileId) {
|
||||
throw new Error('publish requires fileId');
|
||||
}
|
||||
|
||||
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
}
|
||||
|
||||
trans(groupId: number, fileId: string): Promise<TransGroupFileResult> {
|
||||
if (!fileId) throw new Error('trans requires fileId');
|
||||
if (!fileId) {
|
||||
throw new Error('trans requires fileId');
|
||||
}
|
||||
|
||||
return TransGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
}
|
||||
|
||||
@@ -276,8 +302,11 @@ export class GroupFileApi {
|
||||
// local disk path and stream-hash it — the (up to 4 GiB) file is never
|
||||
// buffered in RAM.
|
||||
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
|
||||
|
||||
try {
|
||||
if (staged.fileSize === 0) throw new Error('group file is empty');
|
||||
if (staged.fileSize === 0) {
|
||||
throw new Error('group file is empty');
|
||||
}
|
||||
|
||||
const fileName = normalizeUploadFileName(name, staged.fileName);
|
||||
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
|
||||
@@ -291,10 +320,19 @@ export class GroupFileApi {
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
});
|
||||
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
|
||||
ensureRetCodeZero(
|
||||
'group file upload',
|
||||
upload.retCode,
|
||||
upload.retMsg,
|
||||
upload.clientWording,
|
||||
);
|
||||
|
||||
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||
if (!fileId) throw new Error('group file upload response missing file_id');
|
||||
const fileId =
|
||||
typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||
|
||||
if (!fileId) {
|
||||
throw new Error('group file upload response missing file_id');
|
||||
}
|
||||
|
||||
// Remember the upload so a later `send_group_msg` carrying just the
|
||||
// file_id can route via `publish` without forcing the OneBot caller
|
||||
@@ -315,12 +353,17 @@ export class GroupFileApi {
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
|
||||
|
||||
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|
||||
|| '';
|
||||
if (senderUin <= 0) {
|
||||
throw new Error('invalid self uin for group file upload');
|
||||
}
|
||||
|
||||
const uploadHost =
|
||||
(typeof upload.uploadIp === 'string' && upload.uploadIp) ||
|
||||
(typeof upload.serverDns === 'string' && upload.serverDns) ||
|
||||
'';
|
||||
const uploadPort = toInt(upload.uploadPort);
|
||||
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
throw new Error('group file upload host is invalid');
|
||||
}
|
||||
@@ -366,8 +409,11 @@ export class GroupFileApi {
|
||||
// fail loud but don't lose the upload result the action handler
|
||||
// committed to returning. Callers can still resolve the file by
|
||||
// id; they'll just have to re-publish it themselves.
|
||||
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId, err instanceof Error ? err.message : String(err));
|
||||
log.warn(
|
||||
'group file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -389,14 +435,20 @@ export class GroupFileApi {
|
||||
// never buffered in RAM. headLimit = MD5_HEAD_LIMIT yields the offline-file
|
||||
// md510MCheckSum in the same single pass.
|
||||
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
|
||||
|
||||
try {
|
||||
if (staged.fileSize === 0) throw new Error('private file is empty');
|
||||
if (staged.fileSize === 0) {
|
||||
throw new Error('private file is empty');
|
||||
}
|
||||
|
||||
const targetUid = await this.ctx.resolveUserUid(userId);
|
||||
const selfUid = await resolveSelfUid(this.ctx);
|
||||
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
|
||||
|
||||
if (senderUin <= 0) {
|
||||
throw new Error('invalid self uin for private file upload');
|
||||
}
|
||||
|
||||
const fileName = normalizeUploadFileName(name, staged.fileName);
|
||||
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
|
||||
@@ -414,8 +466,12 @@ export class GroupFileApi {
|
||||
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
|
||||
|
||||
const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null;
|
||||
const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
|
||||
if (!fileId) throw new Error('private file upload response missing file_id');
|
||||
const fileHash =
|
||||
typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
|
||||
|
||||
if (!fileId) {
|
||||
throw new Error('private file upload response missing file_id');
|
||||
}
|
||||
|
||||
// Cache the metadata so a later `send_private_msg` carrying just
|
||||
// `{type:'file', file_id}` can resurrect the full c2c-file packet
|
||||
@@ -456,43 +512,65 @@ export class GroupFileApi {
|
||||
// uploadDns), so we fall through to those after rtpMediaPlatform.
|
||||
// Pair an HTTPS-flavored host with `uploadHttpsPort` if that's
|
||||
// what we picked.
|
||||
const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress)
|
||||
&& upload.rtpMediaPlatformUploadAddress[0])
|
||||
? upload.rtpMediaPlatformUploadAddress[0] : null;
|
||||
const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0
|
||||
? int32ToIpv4Dotted(rtpFirst.inIP) : '';
|
||||
const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number'
|
||||
? rtpFirst.inPort : 0;
|
||||
const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0])
|
||||
? upload.uploadIpList[0] : '';
|
||||
const uploadHost = (rtpInIP)
|
||||
|| (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
|| (typeof upload.uploadDomain === 'string' && upload.uploadDomain)
|
||||
|| (ipListFirst)
|
||||
|| (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain)
|
||||
|| (typeof upload.uploadDns === 'string' && upload.uploadDns)
|
||||
|| '';
|
||||
const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst
|
||||
&& typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain;
|
||||
const uploadPort = rtpInIP && rtpInPort > 0
|
||||
const rtpFirst =
|
||||
Array.isArray(upload.rtpMediaPlatformUploadAddress) &&
|
||||
upload.rtpMediaPlatformUploadAddress[0]
|
||||
? upload.rtpMediaPlatformUploadAddress[0]
|
||||
: null;
|
||||
const rtpInIP =
|
||||
rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0
|
||||
? int32ToIpv4Dotted(rtpFirst.inIP)
|
||||
: '';
|
||||
const rtpInPort =
|
||||
rtpFirst && typeof rtpFirst.inPort === 'number' ? rtpFirst.inPort : 0;
|
||||
const ipListFirst =
|
||||
Array.isArray(upload.uploadIpList) && upload.uploadIpList[0]
|
||||
? upload.uploadIpList[0]
|
||||
: '';
|
||||
const uploadHost =
|
||||
rtpInIP ||
|
||||
(typeof upload.uploadIp === 'string' && upload.uploadIp) ||
|
||||
(typeof upload.uploadDomain === 'string' && upload.uploadDomain) ||
|
||||
ipListFirst ||
|
||||
(typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain) ||
|
||||
(typeof upload.uploadDns === 'string' && upload.uploadDns) ||
|
||||
'';
|
||||
const httpsHostUsed =
|
||||
!rtpInIP &&
|
||||
!upload.uploadIp &&
|
||||
!upload.uploadDomain &&
|
||||
!ipListFirst &&
|
||||
typeof upload.uploadHttpsDomain === 'string' &&
|
||||
!!upload.uploadHttpsDomain;
|
||||
const uploadPort =
|
||||
rtpInIP && rtpInPort > 0
|
||||
? rtpInPort
|
||||
: httpsHostUsed && toInt(upload.uploadHttpsPort) > 0
|
||||
? toInt(upload.uploadHttpsPort)
|
||||
: toInt(upload.uploadPort);
|
||||
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress)
|
||||
? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({
|
||||
outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort,
|
||||
? JSON.stringify(
|
||||
upload.rtpMediaPlatformUploadAddress.map((e) => ({
|
||||
outIP: e.outIP,
|
||||
outPort: e.outPort,
|
||||
inIP: e.inIP,
|
||||
inPort: e.inPort,
|
||||
iPType: e.iPType,
|
||||
})))
|
||||
})),
|
||||
)
|
||||
: '[]';
|
||||
log.warn(
|
||||
'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s',
|
||||
rtpDump,
|
||||
upload.uploadIp ?? '', upload.uploadDomain ?? '',
|
||||
upload.uploadIp ?? '',
|
||||
upload.uploadDomain ?? '',
|
||||
JSON.stringify(upload.uploadIpList ?? []),
|
||||
upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '',
|
||||
upload.uploadLanip ?? '', upload.uploadPort ?? 0,
|
||||
upload.uploadHttpsDomain ?? '',
|
||||
upload.uploadDns ?? '',
|
||||
upload.uploadLanip ?? '',
|
||||
upload.uploadPort ?? 0,
|
||||
upload.uploadHttpsPort ?? 0,
|
||||
);
|
||||
throw new Error('private file upload host is invalid');
|
||||
@@ -507,7 +585,9 @@ export class GroupFileApi {
|
||||
fileId,
|
||||
upload.mediaPlatformUploadKey instanceof Uint8Array
|
||||
? upload.mediaPlatformUploadKey
|
||||
: (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
|
||||
: upload.uploadKey instanceof Uint8Array
|
||||
? upload.uploadKey
|
||||
: new Uint8Array(0),
|
||||
uploadHost,
|
||||
uploadPort,
|
||||
);
|
||||
@@ -537,8 +617,11 @@ export class GroupFileApi {
|
||||
fileHash: fileHash ?? '',
|
||||
});
|
||||
} catch (err) {
|
||||
log.warn('private file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId, err instanceof Error ? err.message : String(err));
|
||||
log.warn(
|
||||
'private file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -557,14 +640,22 @@ export class GroupFileApi {
|
||||
|
||||
const pageSize = 20;
|
||||
let startIndex = 0;
|
||||
|
||||
for (let page = 0; page < 200; page++) {
|
||||
const list = await ListGroupFilesPage.invoke(this.ctx, {
|
||||
groupId, targetDirectory, startIndex, pageSize,
|
||||
groupId,
|
||||
targetDirectory,
|
||||
startIndex,
|
||||
pageSize,
|
||||
});
|
||||
if (!list) break;
|
||||
|
||||
if (!list) {
|
||||
break;
|
||||
}
|
||||
|
||||
for (const item of list.items) {
|
||||
const type = toInt(item?.type);
|
||||
|
||||
if (type === 1 && item?.fileInfo) {
|
||||
const file = item.fileInfo;
|
||||
const uploader = toInt(file.uploaderUin);
|
||||
@@ -579,38 +670,47 @@ export class GroupFileApi {
|
||||
modifyTime: toInt(file.modifiedTime),
|
||||
downloadTimes: toInt(file.downloadedTimes),
|
||||
uploader,
|
||||
uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName)
|
||||
|| cached?.card
|
||||
|| cached?.nickname
|
||||
|| '',
|
||||
uploaderName:
|
||||
(typeof file.uploaderName === 'string' && file.uploaderName) ||
|
||||
cached?.card ||
|
||||
cached?.nickname ||
|
||||
'',
|
||||
});
|
||||
} else if (type === 2 && item?.folderInfo) {
|
||||
const folder = item.folderInfo;
|
||||
const creator = toInt(folder.creatorUin);
|
||||
const cached = this.ctx.identity.findGroupMember(groupId, creator);
|
||||
const lastUploader = toInt(folder.modifierUin);
|
||||
const lastUploaderCached = this.ctx.identity.findGroupMember(groupId, lastUploader);
|
||||
const lastUploaderCached = this.ctx.identity.findGroupMember(
|
||||
groupId,
|
||||
lastUploader,
|
||||
);
|
||||
folders.push({
|
||||
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
|
||||
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
|
||||
createTime: toInt(folder.createTime),
|
||||
creator,
|
||||
creatorName: (typeof folder.creatorName === 'string' && folder.creatorName)
|
||||
|| cached?.card
|
||||
|| cached?.nickname
|
||||
|| '',
|
||||
creatorName:
|
||||
(typeof folder.creatorName === 'string' && folder.creatorName) ||
|
||||
cached?.card ||
|
||||
cached?.nickname ||
|
||||
'',
|
||||
totalFileCount: toInt(folder.totalFileCount),
|
||||
lastUploadTime: toInt(folder.modifiedTime),
|
||||
lastUploader,
|
||||
lastUploaderName: (typeof folder.modifierName === 'string' && folder.modifierName)
|
||||
|| lastUploaderCached?.card
|
||||
|| lastUploaderCached?.nickname
|
||||
|| '',
|
||||
lastUploaderName:
|
||||
(typeof folder.modifierName === 'string' && folder.modifierName) ||
|
||||
lastUploaderCached?.card ||
|
||||
lastUploaderCached?.nickname ||
|
||||
'',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (list.isEnd) break;
|
||||
if (list.isEnd) {
|
||||
break;
|
||||
}
|
||||
|
||||
startIndex += pageSize;
|
||||
}
|
||||
|
||||
@@ -636,11 +736,26 @@ export class GroupFileApi {
|
||||
return DeleteGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
}
|
||||
|
||||
move(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> {
|
||||
return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory });
|
||||
move(
|
||||
groupId: number,
|
||||
fileId: string,
|
||||
parentDirectory: string,
|
||||
targetDirectory: string,
|
||||
): Promise<void> {
|
||||
return MoveGroupFile.invoke(this.ctx, {
|
||||
groupId,
|
||||
fileId,
|
||||
parentDirectory,
|
||||
targetDirectory,
|
||||
});
|
||||
}
|
||||
|
||||
rename(groupId: number, fileId: string, parentDirectory: string, newFileName: string): Promise<void> {
|
||||
rename(
|
||||
groupId: number,
|
||||
fileId: string,
|
||||
parentDirectory: string,
|
||||
newFileName: string,
|
||||
): Promise<void> {
|
||||
return RenameGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, newFileName });
|
||||
}
|
||||
|
||||
@@ -648,7 +763,9 @@ export class GroupFileApi {
|
||||
|
||||
createFolder(groupId: number, name: string, parentId = '/'): Promise<CreateGroupFolder.Result> {
|
||||
return CreateGroupFolder.invoke(this.ctx, {
|
||||
groupId, parentId: normalizeDirectory(parentId), folderName: name,
|
||||
groupId,
|
||||
parentId: normalizeDirectory(parentId),
|
||||
folderName: name,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -22,24 +22,24 @@ export class HistoryRequestGate {
|
||||
|
||||
constructor(private readonly clock: HistoryRequestGateClock = SYSTEM_CLOCK) {}
|
||||
|
||||
run<T>(
|
||||
minimumGapMs: number,
|
||||
operation: () => Promise<T>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<T> {
|
||||
run<T>(minimumGapMs: number, operation: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
||||
if (!Number.isSafeInteger(minimumGapMs) || minimumGapMs < 0) {
|
||||
return Promise.reject(new Error(`history request gap is invalid: ${String(minimumGapMs)}`));
|
||||
return Promise.reject(
|
||||
new Error(`history request gap is invalid: ${String(minimumGapMs)}`),
|
||||
);
|
||||
}
|
||||
|
||||
let operationStarted = false;
|
||||
const result = this.tail.then(async () => {
|
||||
throwIfAborted(signal);
|
||||
const now = this.clock.now();
|
||||
const requestedBoundary = this.lastStartedAt === null
|
||||
? now
|
||||
: this.lastStartedAt + minimumGapMs;
|
||||
const requestedBoundary =
|
||||
this.lastStartedAt === null ? now : this.lastStartedAt + minimumGapMs;
|
||||
const wait = Math.max(this.nextAllowedAt, requestedBoundary) - now;
|
||||
if (wait > 0) await this.clock.sleep(wait, signal);
|
||||
|
||||
if (wait > 0) {
|
||||
await this.clock.sleep(wait, signal);
|
||||
}
|
||||
|
||||
throwIfAborted(signal);
|
||||
const startedAt = this.clock.now();
|
||||
@@ -53,9 +53,7 @@ export class HistoryRequestGate {
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return signal
|
||||
? rejectWhileQueuedOnAbort(result, signal, () => operationStarted)
|
||||
: result;
|
||||
return signal ? rejectWhileQueuedOnAbort(result, signal, () => operationStarted) : result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,6 +65,7 @@ function throwIfAborted(signal?: AbortSignal): void {
|
||||
|
||||
function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
throwIfAborted(signal);
|
||||
|
||||
if (!signal) {
|
||||
return new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
@@ -76,11 +75,13 @@ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
reject(signal.reason ?? new Error('history request aborted'));
|
||||
};
|
||||
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
@@ -100,6 +101,7 @@ function rejectWhileQueuedOnAbort<T>(
|
||||
reject(signal.reason ?? new Error('history request aborted'));
|
||||
}
|
||||
};
|
||||
|
||||
signal.addEventListener('abort', onAbort);
|
||||
result.then(resolve, reject).finally(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
|
||||
@@ -43,7 +43,14 @@ export class InteractionApi {
|
||||
cookie = '',
|
||||
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
|
||||
try {
|
||||
return await GetEmojiLikes.invoke(this.ctx, { groupId, sequence, emojiId, emojiType, count, cookie });
|
||||
return await GetEmojiLikes.invoke(this.ctx, {
|
||||
groupId,
|
||||
sequence,
|
||||
emojiId,
|
||||
emojiType,
|
||||
count,
|
||||
cookie,
|
||||
});
|
||||
} catch {
|
||||
return { users: [], cookie: '', isLast: true };
|
||||
}
|
||||
@@ -55,7 +62,9 @@ export class InteractionApi {
|
||||
fetchReactionSummary(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>> {
|
||||
): Promise<
|
||||
Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>
|
||||
> {
|
||||
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,5 @@
|
||||
import type { JsonObject, JsonValue } from '@snowluma/common/json';
|
||||
import type {
|
||||
MiniAppShareReq,
|
||||
MiniAppShareResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { MiniAppShareReq, MiniAppShareResp } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
// Migrated OIDB cmds — facade methods are one-line forwarders.
|
||||
@@ -23,13 +20,21 @@ export class MiscApi {
|
||||
return ImageOcr.invoke(this.ctx, { imageUrl });
|
||||
}
|
||||
|
||||
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
|
||||
async getMiniAppArk(
|
||||
type: string,
|
||||
title: string,
|
||||
desc: string,
|
||||
picUrl: string,
|
||||
jumpUrl: string,
|
||||
): Promise<JsonObject> {
|
||||
let appid = '1109937557'; // default: bilibili
|
||||
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
|
||||
let iconUrl =
|
||||
'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
|
||||
|
||||
if (type === 'weibo') {
|
||||
appid = '1109224783';
|
||||
iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
|
||||
iconUrl =
|
||||
'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
|
||||
} else if (type !== 'bili') {
|
||||
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
|
||||
}
|
||||
@@ -39,7 +44,10 @@ export class MiscApi {
|
||||
body: { appid, title, desc, picUrl, jumpUrl, iconUrl },
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'LightAppSvc.mini_app_share.AdaptShareInfo',
|
||||
request,
|
||||
);
|
||||
|
||||
if (!result.success || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'get mini app ark failed');
|
||||
@@ -52,7 +60,10 @@ export class MiscApi {
|
||||
throw new Error('mini app share json empty');
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(jsonStr) as Record<string, JsonObject | string | number | boolean | null>;
|
||||
const parsed = JSON.parse(jsonStr) as Record<
|
||||
string,
|
||||
JsonObject | string | number | boolean | null
|
||||
>;
|
||||
|
||||
return {
|
||||
data: {
|
||||
@@ -75,7 +86,13 @@ export class MiscApi {
|
||||
callbackData: string,
|
||||
msgSeq: number,
|
||||
): Promise<JsonValue> {
|
||||
return ClickInlineKeyboardButton.invoke(this.ctx, { groupId, botAppid, buttonId, callbackData, msgSeq });
|
||||
return ClickInlineKeyboardButton.invoke(this.ctx, {
|
||||
groupId,
|
||||
botAppid,
|
||||
buttonId,
|
||||
callbackData,
|
||||
msgSeq,
|
||||
});
|
||||
}
|
||||
|
||||
sendGroupSign(groupId: number): Promise<void> {
|
||||
@@ -84,12 +101,17 @@ export class MiscApi {
|
||||
|
||||
async getDecryptKey(dbSalt: string): Promise<string> {
|
||||
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`);
|
||||
throw new Error(
|
||||
result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!result.dbKey) {
|
||||
throw new Error('Decrypt key is empty');
|
||||
}
|
||||
|
||||
return result.dbKey;
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,17 @@ import { FetchCustomFaceList } from '@snowluma/protocol/oidb-services/custom-fac
|
||||
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
|
||||
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
|
||||
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
|
||||
import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import {
|
||||
BufferChunkSource,
|
||||
fetchHighwaySession,
|
||||
uploadHighwayHttp,
|
||||
} from '@snowluma/protocol/highway';
|
||||
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
|
||||
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
|
||||
import {
|
||||
GetUnidirectionalFriendList,
|
||||
type UnidirectionalFriendEntry,
|
||||
} from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
|
||||
import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status';
|
||||
import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile';
|
||||
import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick';
|
||||
@@ -21,7 +28,9 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
function asBridge(ctx: BridgeContext): Bridge {
|
||||
return ctx as unknown as Bridge;
|
||||
}
|
||||
|
||||
export interface CustomFaceDetail {
|
||||
emojiId: string;
|
||||
@@ -72,10 +81,15 @@ export class ProfileApi {
|
||||
|
||||
if (result.responseData && result.responseData.length > 0) {
|
||||
const resp = protobuf_decode<SetStatusResp>(result.responseData);
|
||||
|
||||
if (!resp) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
throw new Error(
|
||||
result.errorMessage || 'set online status failed (network/timeout)',
|
||||
);
|
||||
}
|
||||
|
||||
const message = resp.errMsg ?? '';
|
||||
|
||||
if (message !== '' && message !== 'set status success') {
|
||||
throw new Error(message);
|
||||
}
|
||||
@@ -97,11 +111,21 @@ export class ProfileApi {
|
||||
async setAvatar(source: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const loaded = await loadBinarySource(source, 'avatar');
|
||||
if (!loaded.bytes.length) throw new Error('avatar file is empty');
|
||||
|
||||
if (!loaded.bytes.length) {
|
||||
throw new Error('avatar file is empty');
|
||||
}
|
||||
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 90, new BufferChunkSource(loaded.bytes), hashes.md5, new Uint8Array(0));
|
||||
await uploadHighwayHttp(
|
||||
bridge,
|
||||
session,
|
||||
90,
|
||||
new BufferChunkSource(loaded.bytes),
|
||||
hashes.md5,
|
||||
new Uint8Array(0),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,7 +141,10 @@ export class ProfileApi {
|
||||
async setGroupAvatar(groupId: number, source: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const loaded = await loadBinarySource(source, 'group-avatar');
|
||||
if (!loaded.bytes.length) throw new Error('group avatar file is empty');
|
||||
|
||||
if (!loaded.bytes.length) {
|
||||
throw new Error('group avatar file is empty');
|
||||
}
|
||||
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
@@ -128,7 +155,14 @@ export class ProfileApi {
|
||||
field5: 3,
|
||||
field6: 1,
|
||||
});
|
||||
await uploadHighwayHttp(bridge, session, 3000, new BufferChunkSource(loaded.bytes), hashes.md5, extra);
|
||||
await uploadHighwayHttp(
|
||||
bridge,
|
||||
session,
|
||||
3000,
|
||||
new BufferChunkSource(loaded.bytes),
|
||||
hashes.md5,
|
||||
extra,
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── queries on me / my contacts ───────────────
|
||||
@@ -148,7 +182,10 @@ export class ProfileApi {
|
||||
|
||||
async fetchCustomFaceDetails(count = 10): Promise<CustomFaceDetail[]> {
|
||||
const faceIds = await this.fetchCustomFaceIds(count);
|
||||
if (faceIds.length === 0) return [];
|
||||
|
||||
if (faceIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const emojis = faceIds.map((emojiId) => ({
|
||||
emojiId,
|
||||
@@ -170,7 +207,10 @@ export class ProfileApi {
|
||||
if (!Number.isInteger(count) || count < 0) {
|
||||
throw new Error('custom face count must be a non-negative integer');
|
||||
}
|
||||
if (count === 0) return [];
|
||||
|
||||
if (count === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
|
||||
return faceIds.slice(0, count);
|
||||
@@ -181,15 +221,25 @@ export class ProfileApi {
|
||||
}
|
||||
|
||||
/** Resolve an existing saved sticker by its resource id or content MD5. */
|
||||
async resolveCustomFace(identifier: string): Promise<Pick<CustomFaceDetail, 'emojiId' | 'url' | 'md5'>> {
|
||||
async resolveCustomFace(
|
||||
identifier: string,
|
||||
): Promise<Pick<CustomFaceDetail, 'emojiId' | 'url' | 'md5'>> {
|
||||
const wanted = identifier.trim();
|
||||
if (!wanted) throw new Error('custom face identifier is empty');
|
||||
|
||||
if (!wanted) {
|
||||
throw new Error('custom face identifier is empty');
|
||||
}
|
||||
|
||||
const ids = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
|
||||
const byMd5 = /^[a-fA-F0-9]{32}$/.test(wanted);
|
||||
const emojiId = ids.find((id) => byMd5
|
||||
? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase()
|
||||
: id === wanted);
|
||||
if (!emojiId) throw new Error('custom face is not in the saved sticker list');
|
||||
const emojiId = ids.find((id) =>
|
||||
byMd5 ? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase() : id === wanted,
|
||||
);
|
||||
|
||||
if (!emojiId) {
|
||||
throw new Error('custom face is not in the saved sticker list');
|
||||
}
|
||||
|
||||
return { emojiId, url: this.customFaceUrl(emojiId), md5: md5FromEmojiId(emojiId) };
|
||||
}
|
||||
|
||||
@@ -229,7 +279,11 @@ export class ProfileApi {
|
||||
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
|
||||
const ids = await this.fetchCustomFaceIds(1000);
|
||||
const idx = ids.indexOf(emojiId);
|
||||
if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`);
|
||||
|
||||
if (idx < 0) {
|
||||
throw new Error(`emoji_id not in list: ${emojiId}`);
|
||||
}
|
||||
|
||||
// 新顺序:目标挪到第一,其余按原顺序
|
||||
const reordered = ids.slice();
|
||||
reordered.splice(idx, 1);
|
||||
@@ -252,8 +306,10 @@ function md5FromEmojiId(emojiId: string): string {
|
||||
const parts = emojiId.split('_');
|
||||
// 期望形如 `<uin>_0_0_0_<md5>_0_0`,共 7 段,md5 在 index 4。
|
||||
const md5 = parts[4];
|
||||
|
||||
if (!md5 || md5.length !== 32 || !/^[0-9a-fA-F]{32}$/.test(md5)) {
|
||||
throw new Error(`invalid emoji_id (cannot extract md5): ${emojiId}`);
|
||||
}
|
||||
|
||||
return md5.toUpperCase();
|
||||
}
|
||||
@@ -68,7 +68,15 @@ export class QzoneApi {
|
||||
targetUins?: string,
|
||||
): Promise<QzonePublishResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval, ugcRight, targetUins);
|
||||
return publishQzoneMsg(
|
||||
cookieObject,
|
||||
this.ctx.identity.uin,
|
||||
content,
|
||||
richType,
|
||||
richval,
|
||||
ugcRight,
|
||||
targetUins,
|
||||
);
|
||||
}
|
||||
|
||||
/** 删除机器人自己空间的一条说说(按 tid)。 */
|
||||
@@ -81,7 +89,11 @@ export class QzoneApi {
|
||||
* 修改机器人自己空间一条已发说说的查看权限(按 tid)。
|
||||
* `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。
|
||||
*/
|
||||
async updateRight(tid: string, ugcRight: number, targetUins?: string): Promise<QzoneUpdateRightResult> {
|
||||
async updateRight(
|
||||
tid: string,
|
||||
ugcRight: number,
|
||||
targetUins?: string,
|
||||
): Promise<QzoneUpdateRightResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins);
|
||||
}
|
||||
@@ -90,7 +102,12 @@ export class QzoneApi {
|
||||
* 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说;
|
||||
* 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。
|
||||
*/
|
||||
async like(tid: string, targetUin: number | undefined, like: boolean, abstime = 0): Promise<void> {
|
||||
async like(
|
||||
tid: string,
|
||||
targetUin: number | undefined,
|
||||
like: boolean,
|
||||
abstime = 0,
|
||||
): Promise<void> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
export function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return Math.trunc(value);
|
||||
}
|
||||
|
||||
if (typeof value === 'bigint') {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? Math.trunc(n) : 0;
|
||||
}
|
||||
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? Math.trunc(n) : 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ export class SystemFaceApi {
|
||||
await sysFaceStore.refresh(this.ctx);
|
||||
return sysFaceStore.lookup(faceId);
|
||||
}
|
||||
|
||||
return sysFaceStore.resolve(this.ctx, faceId);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
|
||||
import {
|
||||
ForceFetchClientKey,
|
||||
type ClientKeyInfo as NamespaceClientKeyInfo,
|
||||
} from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
|
||||
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
|
||||
import {
|
||||
getGroupEssenceMsg,
|
||||
getGroupEssenceMsgAll,
|
||||
type GroupEssenceMsgRet,
|
||||
} from '@snowluma/protocol/web/group-essence';
|
||||
import { getFriendDressWebAPI, type WebFriendDress } from '@snowluma/protocol/web/friend-dress';
|
||||
import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor';
|
||||
import {
|
||||
getHonorListWebAPI,
|
||||
WebHonorType,
|
||||
type WebHonorItem,
|
||||
} from '@snowluma/protocol/web/group-honor';
|
||||
import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin';
|
||||
import {
|
||||
deleteGroupNotice as deleteGroupNoticeHttp,
|
||||
@@ -22,7 +33,9 @@ import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
function asBridge(ctx: BridgeContext): Bridge {
|
||||
return ctx as unknown as Bridge;
|
||||
}
|
||||
|
||||
export type ClientKeyInfo = NamespaceClientKeyInfo;
|
||||
|
||||
@@ -66,10 +79,17 @@ export interface SendNoticeOptions {
|
||||
}
|
||||
|
||||
function finiteNumber(value: unknown, field: string): number {
|
||||
const parsed = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN;
|
||||
const parsed =
|
||||
typeof value === 'number'
|
||||
? value
|
||||
: typeof value === 'string' && value.trim() !== ''
|
||||
? Number(value)
|
||||
: Number.NaN;
|
||||
|
||||
if (!Number.isFinite(parsed)) {
|
||||
throw new Error(`invalid group notice response: ${field} must be a finite number`);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
@@ -77,11 +97,18 @@ function collectionValues(
|
||||
collection: WebApiGroupNoticeCollection | undefined,
|
||||
field: 'feeds' | 'inst',
|
||||
): WebApiGroupNoticeFeed[] {
|
||||
if (collection === undefined) return [];
|
||||
if (Array.isArray(collection)) return collection;
|
||||
if (collection === undefined) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (Array.isArray(collection)) {
|
||||
return collection;
|
||||
}
|
||||
|
||||
if (collection === null || typeof collection !== 'object') {
|
||||
throw new Error(`invalid group notice response: ${field} must be an array or object`);
|
||||
}
|
||||
|
||||
return Object.values(collection);
|
||||
}
|
||||
|
||||
@@ -89,20 +116,26 @@ function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boole
|
||||
if (!feed || typeof feed !== 'object') {
|
||||
throw new Error('invalid group notice response: feed must be an object');
|
||||
}
|
||||
|
||||
if (typeof feed.fid !== 'string' || feed.fid.length === 0) {
|
||||
throw new Error('invalid group notice response: feed.fid must be a non-empty string');
|
||||
}
|
||||
|
||||
if (!feed.msg || typeof feed.msg !== 'object' || typeof feed.msg.text !== 'string') {
|
||||
throw new Error(`invalid group notice response: feed ${feed.fid} has no message text`);
|
||||
}
|
||||
|
||||
if (feed.settings === undefined) {
|
||||
throw new Error(`invalid group notice response: feed ${feed.fid} has no settings`);
|
||||
}
|
||||
|
||||
const image = (feed.msg.pics ?? []).map((pic, index) => {
|
||||
if (!pic || typeof pic !== 'object' || typeof pic.id !== 'string') {
|
||||
throw new Error(`invalid group notice response: feed ${feed.fid} image ${index} is malformed`);
|
||||
throw new Error(
|
||||
`invalid group notice response: feed ${feed.fid} image ${index} is malformed`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
id: pic.id,
|
||||
url: groupNoticeImageUrl(pic.id),
|
||||
@@ -110,8 +143,11 @@ function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boole
|
||||
width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`),
|
||||
};
|
||||
});
|
||||
const responseType = feed.type === undefined
|
||||
? sendToNewMembers ? GROUP_NOTICE_TYPE_NEW_MEMBERS : GROUP_NOTICE_TYPE_NORMAL
|
||||
const responseType =
|
||||
feed.type === undefined
|
||||
? sendToNewMembers
|
||||
? GROUP_NOTICE_TYPE_NEW_MEMBERS
|
||||
: GROUP_NOTICE_TYPE_NORMAL
|
||||
: finiteNumber(feed.type, `feed ${feed.fid}.type`);
|
||||
|
||||
return {
|
||||
@@ -126,7 +162,8 @@ function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boole
|
||||
settings: feed.settings,
|
||||
read_num: finiteNumber(feed.read_num, `feed ${feed.fid}.read_num`),
|
||||
type: responseType,
|
||||
pinned: feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`),
|
||||
pinned:
|
||||
feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`),
|
||||
send_to_new_members: sendToNewMembers || responseType === GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||
};
|
||||
}
|
||||
@@ -139,10 +176,16 @@ export function mapGroupNoticeResponse(ret: WebApiGroupNoticeRet): WebNoticeInfo
|
||||
|
||||
const notices: WebNoticeInfo[] = [];
|
||||
const indexByNoticeId = new Map<string, number>();
|
||||
const append = (collection: WebApiGroupNoticeCollection | undefined, sendToNewMembers: boolean, field: 'feeds' | 'inst') => {
|
||||
|
||||
const append = (
|
||||
collection: WebApiGroupNoticeCollection | undefined,
|
||||
sendToNewMembers: boolean,
|
||||
field: 'feeds' | 'inst',
|
||||
) => {
|
||||
for (const feed of collectionValues(collection, field)) {
|
||||
const mapped = mapGroupNoticeFeed(feed, sendToNewMembers);
|
||||
const existingIndex = indexByNoticeId.get(mapped.notice_id);
|
||||
|
||||
if (existingIndex === undefined) {
|
||||
indexByNoticeId.set(mapped.notice_id, notices.length);
|
||||
notices.push(mapped);
|
||||
@@ -165,7 +208,10 @@ function forceFetchClientKeyInner(bridge: Bridge): Promise<ClientKeyInfo> {
|
||||
return ForceFetchClientKey.invoke(bridge);
|
||||
}
|
||||
|
||||
function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
|
||||
function getPSkey(
|
||||
bridge: Bridge,
|
||||
domainList: string[],
|
||||
): Promise<{ domainPskeyMap: Map<string, string> }> {
|
||||
return GetPskey.invoke(bridge, { domainList });
|
||||
}
|
||||
|
||||
@@ -175,9 +221,17 @@ async function getCookies(bridge: Bridge, domain: string): Promise<Record<string
|
||||
// Build the ptlogin2 jump URL: this is the canonical way for the
|
||||
// bot to swap its clientKey for cookie-jar entries on a given
|
||||
// qq.com subdomain.
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
|
||||
const requestUrl =
|
||||
'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' +
|
||||
bridge.identity.uin +
|
||||
'&clientkey=' +
|
||||
ClientKeyData.clientKey +
|
||||
'&u1=https%3A%2F%2F' +
|
||||
domain +
|
||||
'%2F' +
|
||||
bridge.identity.uin +
|
||||
'%2Finfocenter&keyindex=' +
|
||||
ClientKeyData.keyIndex;
|
||||
|
||||
const data = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
|
||||
@@ -188,6 +242,7 @@ async function getCookies(bridge: Bridge, domain: string): Promise<Record<string
|
||||
try {
|
||||
const pskeyData = await getPSkey(bridge, [domain]);
|
||||
const pskey = pskeyData.domainPskeyMap.get(domain);
|
||||
|
||||
if (pskey) {
|
||||
data['p_skey'] = pskey;
|
||||
}
|
||||
@@ -206,12 +261,19 @@ async function getSKey(bridge: Bridge): Promise<string> {
|
||||
throw new Error('getClientKey Error: clientKey is empty');
|
||||
}
|
||||
|
||||
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
|
||||
'&clientuin=' + bridge.identity.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=' + u1 +
|
||||
'&keyindex=' + ClientKeyData.keyIndex;
|
||||
const u1 = encodeURIComponent(
|
||||
'https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0',
|
||||
);
|
||||
const requestUrl =
|
||||
'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
|
||||
'&clientuin=' +
|
||||
bridge.identity.uin +
|
||||
'&clientkey=' +
|
||||
ClientKeyData.clientKey +
|
||||
'&u1=' +
|
||||
u1 +
|
||||
'&keyindex=' +
|
||||
ClientKeyData.keyIndex;
|
||||
|
||||
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
const skey = cookies['skey'];
|
||||
@@ -229,9 +291,11 @@ async function getSKey(bridge: Bridge): Promise<string> {
|
||||
*/
|
||||
function getBknFromSKey(skey: string): number {
|
||||
let hash = 5381;
|
||||
|
||||
for (let i = 0; i < skey.length; i++) {
|
||||
hash += (hash << 5) + skey.charCodeAt(i);
|
||||
}
|
||||
|
||||
return hash & 2147483647;
|
||||
}
|
||||
|
||||
@@ -261,14 +325,18 @@ export class WebApi {
|
||||
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
|
||||
async getCsrfToken(): Promise<number> {
|
||||
const skey = await getSKey(asBridge(this.ctx));
|
||||
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
|
||||
return getBknFromSKey(skey);
|
||||
}
|
||||
|
||||
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
|
||||
async getCredentials(domain: string): Promise<{ cookies: string; token: number; csrf_token: number }> {
|
||||
async getCredentials(
|
||||
domain: string,
|
||||
): Promise<{ cookies: string; token: number; csrf_token: number }> {
|
||||
const cookieObject = await getCookies(asBridge(this.ctx), domain);
|
||||
const cookiesStr = Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
@@ -322,6 +390,7 @@ export class WebApi {
|
||||
|
||||
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
|
||||
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
|
||||
|
||||
if (talkativeList.length > 0) {
|
||||
honorInfo.current_talkative = talkativeList[0];
|
||||
honorInfo.talkative_list = talkativeList;
|
||||
@@ -350,7 +419,11 @@ export class WebApi {
|
||||
async getSignedList(groupId: number): Promise<SignedListMember[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return getDaySignedListWebAPI(cookieObject, groupId.toString(), bridge.identity.uin.toString());
|
||||
return getDaySignedListWebAPI(
|
||||
cookieObject,
|
||||
groupId.toString(),
|
||||
bridge.identity.uin.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── group notice ───────────────
|
||||
@@ -381,11 +454,7 @@ export class WebApi {
|
||||
imgHeight = picInfo.height;
|
||||
}
|
||||
|
||||
const ret = await setGroupNoticeWebAPI(
|
||||
cookieObject,
|
||||
groupCode,
|
||||
content,
|
||||
{
|
||||
const ret = await setGroupNoticeWebAPI(cookieObject, groupCode, content, {
|
||||
pinned: options?.pinned,
|
||||
type: options?.type,
|
||||
sendToNewMembers: options?.sendToNewMembers,
|
||||
@@ -395,8 +464,7 @@ export class WebApi {
|
||||
picId,
|
||||
imgWidth,
|
||||
imgHeight,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
if (ret.ec !== 0) {
|
||||
throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`);
|
||||
|
||||
@@ -5,4 +5,3 @@ export interface BridgeContext extends BaseBridgeContext {
|
||||
readonly apis: ApiHub;
|
||||
}
|
||||
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
@@ -1,27 +1,15 @@
|
||||
import {
|
||||
createLogger,
|
||||
renderTraceBytes,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import {
|
||||
MSG_PUSH_CMD,
|
||||
parseMsgPushOrThrow,
|
||||
SysMsgDedup,
|
||||
} from '@snowluma/protocol/msg-push';
|
||||
import { MSG_PUSH_CMD, parseMsgPushOrThrow, SysMsgDedup } from '@snowluma/protocol/msg-push';
|
||||
import { KICK_NT_CMD, parseKickNT } from '@snowluma/protocol/kick-nt';
|
||||
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
|
||||
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
|
||||
import { buildApiHub, type ApiHub } from './apis';
|
||||
import {
|
||||
AiVoiceChatType,
|
||||
type AiVoiceCategory,
|
||||
type StrangerStatus,
|
||||
} from './apis/extras';
|
||||
import { AiVoiceChatType, type AiVoiceCategory, type StrangerStatus } from './apis/extras';
|
||||
import type { BridgeInterface, RosterWarmupResult } from './bridge-interface';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
@@ -44,7 +32,7 @@ export class Bridge implements BridgeInterface {
|
||||
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
|
||||
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
|
||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
||||
private msgRandom_ = (Date.now() & 0xffffffff) >>> 0;
|
||||
// Per-account dedup for QQ NT's already-deduped system pushes (#137).
|
||||
private readonly sysMsgDedup_ = new SysMsgDedup();
|
||||
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
|
||||
@@ -76,58 +64,81 @@ export class Bridge implements BridgeInterface {
|
||||
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));
|
||||
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));
|
||||
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;
|
||||
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));
|
||||
|
||||
if (sequence) {
|
||||
return sequence;
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
} while (Date.now() < deadline);
|
||||
|
||||
return null;
|
||||
},
|
||||
rememberGroupInviteCardSequence: (groupUin, sequence) => {
|
||||
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence);
|
||||
},
|
||||
});
|
||||
this.pipeline.registerCmd(
|
||||
MSG_PUSH_CMD,
|
||||
(pkt, identity) => parseMsgPushOrThrow(
|
||||
pkt,
|
||||
identity,
|
||||
this.sysMsgDedup_,
|
||||
),
|
||||
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) =>
|
||||
parseMsgPushOrThrow(pkt, identity, this.sysMsgDedup_),
|
||||
);
|
||||
this.pipeline.registerCmd(KICK_NT_CMD, parseKickNT);
|
||||
this.events.on('online_devices_changed', (event) => {
|
||||
const snapshot = event.devices.map((device) => Object.freeze({ ...device }));
|
||||
this.onlineClients_ = Object.freeze(snapshot);
|
||||
log.debug('online-device snapshot updated: uin=%s clients=%d types=%s',
|
||||
this.identity.uin, snapshot.length,
|
||||
snapshot.map((device) => device.clientType).join(','));
|
||||
log.debug(
|
||||
'online-device snapshot updated: uin=%s clients=%d types=%s',
|
||||
this.identity.uin,
|
||||
snapshot.length,
|
||||
snapshot.map((device) => device.clientType).join(','),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -140,6 +151,7 @@ export class Bridge implements BridgeInterface {
|
||||
this.packetClient_ = null;
|
||||
this.packetClientPid_ = null;
|
||||
this.onlineClients_ = null;
|
||||
|
||||
try {
|
||||
this.identity.close();
|
||||
} finally {
|
||||
@@ -157,7 +169,11 @@ export class Bridge implements BridgeInterface {
|
||||
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);
|
||||
|
||||
if (pid !== null) {
|
||||
this.packetClientsByPid_.set(pid, client);
|
||||
}
|
||||
|
||||
this.maybeStartRosterWarmup();
|
||||
}
|
||||
|
||||
@@ -190,6 +206,7 @@ export class Bridge implements BridgeInterface {
|
||||
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',
|
||||
@@ -198,6 +215,7 @@ export class Bridge implements BridgeInterface {
|
||||
previousPid,
|
||||
);
|
||||
}
|
||||
|
||||
this.maybeStartRosterWarmup();
|
||||
}
|
||||
|
||||
@@ -220,36 +238,48 @@ export class Bridge implements BridgeInterface {
|
||||
this.packetClient_ = null;
|
||||
this.packetClientPid_ = null;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.selectFallbackPacketClient(pid);
|
||||
}
|
||||
hasPid(pid: number): boolean { return this.pids_.has(pid); }
|
||||
get empty(): boolean { return this.pids_.size === 0; }
|
||||
hasPid(pid: number): boolean {
|
||||
return this.pids_.has(pid);
|
||||
}
|
||||
get empty(): boolean {
|
||||
return this.pids_.size === 0;
|
||||
}
|
||||
get activePid(): number | null {
|
||||
if (this.packetClientPid_ !== null && this.pids_.has(this.packetClientPid_)) {
|
||||
return this.packetClientPid_;
|
||||
}
|
||||
|
||||
const pids = [...this.pids_];
|
||||
return pids.length > 0 ? pids[pids.length - 1]! : null;
|
||||
}
|
||||
get receiveHealthy(): boolean {
|
||||
for (const pid of this.pids_) {
|
||||
const healthy = this.receiveHealthByPid_.get(pid);
|
||||
|
||||
if (healthy === undefined) {
|
||||
const message = `Bridge receive-health invariant violated: PID=${pid} has no health state`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
if (healthy) return true;
|
||||
|
||||
if (healthy) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
setPidReceiveHealthy(pid: number, healthy: boolean): void {
|
||||
if (!this.pids_.has(pid)) {
|
||||
throw new Error(`Bridge receive-health invariant violated: PID=${pid} is not attached`);
|
||||
}
|
||||
|
||||
this.receiveHealthByPid_.set(pid, healthy);
|
||||
}
|
||||
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
|
||||
@@ -260,12 +290,14 @@ export class Bridge implements BridgeInterface {
|
||||
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);
|
||||
});
|
||||
}
|
||||
@@ -275,17 +307,27 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
|
||||
rememberUploadedFile(meta: UploadedFileMeta): void {
|
||||
if (!meta.fileId) return;
|
||||
if (!meta.fileId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
|
||||
// Map iteration order is insertion order — drop the oldest.
|
||||
const oldest = this.uploadedFileMeta_.keys().next().value;
|
||||
if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest);
|
||||
|
||||
if (oldest !== undefined) {
|
||||
this.uploadedFileMeta_.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
this.uploadedFileMeta_.set(meta.fileId, meta);
|
||||
}
|
||||
|
||||
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
|
||||
if (!fileId) return undefined;
|
||||
if (!fileId) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return this.uploadedFileMeta_.get(fileId);
|
||||
}
|
||||
|
||||
@@ -294,10 +336,14 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
|
||||
nextMessageRandom(): number {
|
||||
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
|
||||
return this.msgRandom_ & 0x7FFFFFFF;
|
||||
this.msgRandom_ = (this.msgRandom_ + 0x9e3779b9) >>> 0;
|
||||
return this.msgRandom_ & 0x7fffffff;
|
||||
}
|
||||
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
|
||||
async sendRawPacket(
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs = packetTimeoutMs(),
|
||||
): Promise<SendPacketResult> {
|
||||
if (!this.packetClient_) {
|
||||
return runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
@@ -321,36 +367,59 @@ export class Bridge implements BridgeInterface {
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
return {
|
||||
success: false, gotResponse: false, errorCode: -1,
|
||||
errorMessage: 'no packet sender attached', responseData: null,
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: 'no packet sender attached',
|
||||
responseData: null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
const result = await this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
const result = await this.packetClient_.sendPacket(
|
||||
serviceCmd,
|
||||
Buffer.from(body),
|
||||
timeoutMs,
|
||||
);
|
||||
const elapsed = Date.now() - startedAt;
|
||||
const respLen = result.responseData ? result.responseData.length : 0;
|
||||
|
||||
if (!result.success || result.errorCode !== 0) {
|
||||
// QQ-side rejection or transport failure — the usual root cause when an
|
||||
// action misbehaves. Warn (persisted) with cmd + code so a user's log
|
||||
// shows exactly where the chain broke.
|
||||
log.warn('packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)',
|
||||
serviceCmd, result.errorCode, result.gotResponse,
|
||||
result.errorMessage ?? '', this.identity.uin, body.length, elapsed);
|
||||
log.warn(
|
||||
'packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)',
|
||||
serviceCmd,
|
||||
result.errorCode,
|
||||
result.gotResponse,
|
||||
result.errorMessage ?? '',
|
||||
this.identity.uin,
|
||||
body.length,
|
||||
elapsed,
|
||||
);
|
||||
} else {
|
||||
// Happy path — memory-only trace so the full chain shows under the
|
||||
// request's [req#N] when debugging, without flooding disk.
|
||||
log.trace(() => [`packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`]);
|
||||
log.trace(() => [
|
||||
`packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`,
|
||||
]);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private selectFallbackPacketClient(detachedPid: number): void {
|
||||
const pids = [...this.pids_];
|
||||
|
||||
for (let index = pids.length - 1; index >= 0; index -= 1) {
|
||||
const fallbackPid = pids[index]!;
|
||||
const fallback = this.packetClientsByPid_.get(fallbackPid);
|
||||
if (!fallback) continue;
|
||||
|
||||
if (!fallback) {
|
||||
continue;
|
||||
}
|
||||
|
||||
this.packetClient_ = fallback;
|
||||
this.packetClientPid_ = fallbackPid;
|
||||
@@ -371,6 +440,7 @@ export class Bridge implements BridgeInterface {
|
||||
|
||||
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',
|
||||
@@ -385,11 +455,21 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
|
||||
private maybeStartRosterWarmup(): void {
|
||||
if (this.disposed_ || this.rosterWarmupStarted_ || !this.packetClient_) return;
|
||||
if (this.disposed_ || this.rosterWarmupStarted_ || !this.packetClient_) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.rosterWarmupStarted_ = true;
|
||||
if (!this.identity.nickname) this.identity.nickname = this.identity.uin;
|
||||
|
||||
if (!this.identity.nickname) {
|
||||
this.identity.nickname = this.identity.uin;
|
||||
}
|
||||
|
||||
void this.runRosterWarmup().then(
|
||||
(result) => this.settleRosterWarmup(this.disposed_ ? { friendsLoaded: false, groupsLoaded: false } : result),
|
||||
(result) =>
|
||||
this.settleRosterWarmup(
|
||||
this.disposed_ ? { friendsLoaded: false, groupsLoaded: false } : result,
|
||||
),
|
||||
(err) => {
|
||||
log.warn(
|
||||
'roster warmup failed: uin=%s err=%s',
|
||||
@@ -402,11 +482,17 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
|
||||
private settleRosterWarmup(result: RosterWarmupResult): void {
|
||||
if (this.rosterWarmupSettled_) return;
|
||||
if (this.rosterWarmupSettled_) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.rosterWarmupSettled_ = true;
|
||||
this.rosterWarmupResult_ = result;
|
||||
const waiters = this.rosterWarmupWaiters_.splice(0);
|
||||
for (const resolve of waiters) resolve(result);
|
||||
|
||||
for (const resolve of waiters) {
|
||||
resolve(result);
|
||||
}
|
||||
}
|
||||
|
||||
private stillOpen(): boolean {
|
||||
@@ -421,77 +507,147 @@ export class Bridge implements BridgeInterface {
|
||||
|
||||
try {
|
||||
const friends = await this.apis.contacts.fetchFriendList();
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
|
||||
if (!this.stillOpen()) {
|
||||
return { friendsLoaded: false, groupsLoaded: false };
|
||||
}
|
||||
|
||||
friendsLoaded = true;
|
||||
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
|
||||
|
||||
for (const friend of friends) {
|
||||
if (friend.uin === selfUin) {
|
||||
this.identity.setSelfProfile({
|
||||
uin: friend.uin, uid: friend.uid,
|
||||
uin: friend.uin,
|
||||
uid: friend.uid,
|
||||
nickname: friend.nickname || uin,
|
||||
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
|
||||
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
|
||||
remark: '',
|
||||
qid: '',
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
sign: '',
|
||||
avatar: '',
|
||||
level: 0,
|
||||
qidianMasterFlag: 0,
|
||||
qidianCrewFlag: 0,
|
||||
qidianCrewFlag2: 0,
|
||||
});
|
||||
this.identity.nickname = friend.nickname || uin;
|
||||
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, friend.uid, friend.nickname ?? '');
|
||||
log.debug(
|
||||
'self info: UIN=%s uid=%s nickname=%s',
|
||||
uin,
|
||||
friend.uid,
|
||||
friend.nickname ?? '',
|
||||
);
|
||||
selfResolved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||
if (!this.stillOpen()) {
|
||||
return { friendsLoaded: false, groupsLoaded: false };
|
||||
}
|
||||
|
||||
log.warn(
|
||||
'failed to load friends for UIN %s: %s',
|
||||
uin,
|
||||
e instanceof Error ? e.message : String(e),
|
||||
);
|
||||
}
|
||||
|
||||
if (!selfResolved && selfUin > 0 && this.stillOpen()) {
|
||||
try {
|
||||
const profile = await this.apis.contacts.fetchUserProfile(selfUin);
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
|
||||
if (!this.stillOpen()) {
|
||||
return { friendsLoaded: false, groupsLoaded: false };
|
||||
}
|
||||
|
||||
this.identity.setSelfProfile(profile);
|
||||
this.identity.nickname = profile.nickname || uin;
|
||||
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
|
||||
uin, profile.uid, profile.nickname);
|
||||
log.debug(
|
||||
'self info via profile: UIN=%s uid=%s nickname=%s',
|
||||
uin,
|
||||
profile.uid,
|
||||
profile.nickname,
|
||||
);
|
||||
} catch (e) {
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
log.warn('failed to load self profile for UIN %s: %s',
|
||||
uin, e instanceof Error ? e.message : String(e));
|
||||
if (!this.stillOpen()) {
|
||||
return { friendsLoaded: false, groupsLoaded: false };
|
||||
}
|
||||
|
||||
log.warn(
|
||||
'failed to load self profile for UIN %s: %s',
|
||||
uin,
|
||||
e instanceof Error ? e.message : String(e),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let groups: { groupId: number }[] = [];
|
||||
let groupsLoaded = false;
|
||||
|
||||
try {
|
||||
groups = await this.apis.contacts.fetchGroupList();
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
|
||||
if (!this.stillOpen()) {
|
||||
return { friendsLoaded: false, groupsLoaded: false };
|
||||
}
|
||||
|
||||
groupsLoaded = true;
|
||||
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
|
||||
} catch (e) {
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||
if (!this.stillOpen()) {
|
||||
return { friendsLoaded: false, groupsLoaded: false };
|
||||
}
|
||||
|
||||
log.warn(
|
||||
'failed to load groups for UIN %s: %s',
|
||||
uin,
|
||||
e instanceof Error ? e.message : String(e),
|
||||
);
|
||||
}
|
||||
|
||||
let loadedGroupCount = 0;
|
||||
let loadedMemberCount = 0;
|
||||
let failedGroupCount = 0;
|
||||
|
||||
for (const group of groups) {
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
if (!this.stillOpen()) {
|
||||
return { friendsLoaded: false, groupsLoaded: false };
|
||||
}
|
||||
|
||||
try {
|
||||
const members = await this.apis.contacts.fetchGroupMemberList(group.groupId);
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
|
||||
if (!this.stillOpen()) {
|
||||
return { friendsLoaded: false, groupsLoaded: false };
|
||||
}
|
||||
|
||||
loadedGroupCount += 1;
|
||||
loadedMemberCount += members.length;
|
||||
|
||||
if (VERBOSE_WARMUP) {
|
||||
log.debug('members loaded: group=%d count=%d', group.groupId, members.length);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
if (!this.stillOpen()) {
|
||||
return { friendsLoaded: false, groupsLoaded: false };
|
||||
}
|
||||
|
||||
failedGroupCount += 1;
|
||||
log.warn('failed to load members for group %d: %s', group.groupId, e instanceof Error ? e.message : String(e));
|
||||
log.warn(
|
||||
'failed to load members for group %d: %s',
|
||||
group.groupId,
|
||||
e instanceof Error ? e.message : String(e),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
if (!this.stillOpen()) {
|
||||
return { friendsLoaded: false, groupsLoaded: false };
|
||||
}
|
||||
|
||||
log.info(
|
||||
'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d',
|
||||
uin,
|
||||
@@ -539,7 +695,7 @@ export interface DownloadRKeyInfo {
|
||||
export interface ClientKeyInfo {
|
||||
clientKey: string;
|
||||
expireTime: string;
|
||||
keyIndex: string
|
||||
keyIndex: string;
|
||||
}
|
||||
export { AiVoiceChatType };
|
||||
export type { AiVoiceCategory, StrangerStatus };
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
createLogger,
|
||||
renderTraceBytes,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
@@ -44,7 +40,10 @@ export class BridgeManager {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn('session-started listener threw: %s', err instanceof Error ? err.message : String(err));
|
||||
log.warn(
|
||||
'session-started listener threw: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,25 +53,29 @@ export class BridgeManager {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn('session-closed listener threw: %s', err instanceof Error ? err.message : String(err));
|
||||
log.warn(
|
||||
'session-closed listener threw: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onPidDisconnected(pid: number): void {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
if (!uin) return;
|
||||
|
||||
if (!uin) {
|
||||
return;
|
||||
}
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_start pid=%d uin=%j',
|
||||
pid,
|
||||
uin,
|
||||
);
|
||||
runtimeLog.trace('bridge_detach_start pid=%d uin=%j', pid, uin);
|
||||
|
||||
try {
|
||||
const closed = this.detachPidFromSession(pid, uin);
|
||||
const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null;
|
||||
|
||||
if (closed) {
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_branch pid=%d uin=%j branch=session_closed',
|
||||
@@ -80,6 +83,7 @@ export class BridgeManager {
|
||||
uin,
|
||||
);
|
||||
}
|
||||
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_terminal pid=%d uin=%j outcome=completed reason=%s activePid=%j elapsedMs=%d',
|
||||
pid,
|
||||
@@ -103,6 +107,7 @@ export class BridgeManager {
|
||||
|
||||
onPidReceiveHealthChanged(pid: number, healthy: boolean): void {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
|
||||
if (!uin) {
|
||||
const message = `BridgeManager invariant violated: receive health for unmapped PID=${pid}`;
|
||||
log.error(message);
|
||||
@@ -110,16 +115,20 @@ export class BridgeManager {
|
||||
}
|
||||
|
||||
const session = this.sessions_.get(uin);
|
||||
|
||||
if (!session || !session.bridge.hasPid(pid)) {
|
||||
const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
session.bridge.setPidReceiveHealthy(pid, healthy);
|
||||
}
|
||||
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||
if (!isRealUin(uin)) return;
|
||||
if (!isRealUin(uin)) {
|
||||
return;
|
||||
}
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
@@ -133,6 +142,7 @@ export class BridgeManager {
|
||||
|
||||
try {
|
||||
const { session, created } = this.bindPid(pid, uin, packetClient, 'login');
|
||||
|
||||
if (previousUin && previousUin !== uin) {
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_branch pid=%d uin=%j branch=account_rebind previousUin=%j',
|
||||
@@ -160,6 +170,7 @@ export class BridgeManager {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_terminal pid=%d uin=%j source=login outcome=completed reason=%s created=%s activePid=%j elapsedMs=%d',
|
||||
pid,
|
||||
@@ -199,6 +210,7 @@ export class BridgeManager {
|
||||
pkt.body.byteLength,
|
||||
renderTraceBytes(pkt.body),
|
||||
]);
|
||||
|
||||
if (!pkt.uin || !isRealUin(pkt.uin)) {
|
||||
packetLog.trace(() => [
|
||||
'packet_terminal serviceCmd=%j seqId=%d outcome=dropped reason=invalid_uin events=0 dispatched=0 elapsedMs=%d',
|
||||
@@ -208,10 +220,12 @@ export class BridgeManager {
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
const uin = pkt.uin;
|
||||
|
||||
let completion: Promise<void>;
|
||||
let handedToPipeline = false;
|
||||
|
||||
try {
|
||||
// A packet may be the first trustworthy observation that a live PID moved
|
||||
// to another UIN. Apply the exact same ownership transition as login so a
|
||||
@@ -235,20 +249,14 @@ export class BridgeManager {
|
||||
this.tracePacketFailure(
|
||||
pkt,
|
||||
startedAt,
|
||||
handedToPipeline
|
||||
? 'pipeline_failed'
|
||||
: 'routing_failed',
|
||||
handedToPipeline ? 'pipeline_failed' : 'routing_failed',
|
||||
error,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
void completion.catch((error) => {
|
||||
this.tracePacketFailure(
|
||||
pkt,
|
||||
startedAt,
|
||||
'pipeline_failed',
|
||||
error,
|
||||
);
|
||||
this.tracePacketFailure(pkt, startedAt, 'pipeline_failed', error);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -268,9 +276,7 @@ export class BridgeManager {
|
||||
]);
|
||||
log.error(
|
||||
'packet %s failed for %s: %s',
|
||||
reason === 'routing_failed'
|
||||
? 'routing'
|
||||
: 'pipeline',
|
||||
reason === 'routing_failed' ? 'routing' : 'pipeline',
|
||||
pkt.serviceCmd,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
@@ -286,6 +292,7 @@ export class BridgeManager {
|
||||
source: 'login' | 'packet',
|
||||
): { session: QQSession; created: boolean } {
|
||||
const previousUin = this.pidToUin_.get(pid);
|
||||
|
||||
if (previousUin && previousUin !== uin) {
|
||||
log.warn(
|
||||
'PID ownership changed: PID=%d UIN=%s -> UIN=%s source=%s',
|
||||
@@ -305,9 +312,13 @@ export class BridgeManager {
|
||||
|
||||
private packetClientForPid(pid: number): PacketSender | null {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
if (!uin) return null;
|
||||
|
||||
if (!uin) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const session = this.sessions_.get(uin);
|
||||
|
||||
if (!session) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
|
||||
log.error(message);
|
||||
@@ -315,7 +326,10 @@ export class BridgeManager {
|
||||
}
|
||||
|
||||
const packetClient = session.bridge.packetClientForPid(pid);
|
||||
if (packetClient) return packetClient;
|
||||
|
||||
if (packetClient) {
|
||||
return packetClient;
|
||||
}
|
||||
|
||||
const message = `BridgeManager invariant violated: PID=${pid} has no sender in UIN=${uin} session`;
|
||||
log.error(message);
|
||||
@@ -324,6 +338,7 @@ export class BridgeManager {
|
||||
|
||||
private detachPidFromSession(pid: number, uin: string): boolean {
|
||||
const mappedUin = this.pidToUin_.get(pid);
|
||||
|
||||
if (mappedUin !== uin) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`;
|
||||
log.error(message);
|
||||
@@ -331,6 +346,7 @@ export class BridgeManager {
|
||||
}
|
||||
|
||||
const session = this.sessions_.get(uin);
|
||||
|
||||
if (!session) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
|
||||
log.error(message);
|
||||
@@ -342,6 +358,7 @@ export class BridgeManager {
|
||||
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);
|
||||
@@ -352,7 +369,10 @@ export class BridgeManager {
|
||||
// invariant is known to hold, so a fail-fast error preserves the evidence.
|
||||
this.pidToUin_.delete(pid);
|
||||
session.bridge.detachPid(pid);
|
||||
if (!session.bridge.empty) return false;
|
||||
|
||||
if (!session.bridge.empty) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
@@ -364,7 +384,10 @@ export class BridgeManager {
|
||||
|
||||
private ensureSession(uin: string): { session: QQSession; created: boolean } {
|
||||
let session = this.sessions_.get(uin);
|
||||
if (session) return { session, created: false };
|
||||
|
||||
if (session) {
|
||||
return { session, created: false };
|
||||
}
|
||||
|
||||
const bridge = new Bridge(IdentityService.openForUin(uin));
|
||||
session = { bridge };
|
||||
|
||||
+78
-20
@@ -33,8 +33,10 @@ function installProcessGuards(): void {
|
||||
// known paths (e.g. the hook-client send deferreds) — these only catch what
|
||||
// slips through, and surface its stack so the real source can be fixed.
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
log.error('unhandledRejection (kept alive): %s',
|
||||
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
|
||||
log.error(
|
||||
'unhandledRejection (kept alive): %s',
|
||||
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason),
|
||||
);
|
||||
});
|
||||
process.on('uncaughtException', (error) => {
|
||||
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
|
||||
@@ -77,6 +79,7 @@ async function main() {
|
||||
autoLoadOnDiscovery,
|
||||
onSessionsChanged: stateWiring.onSessionsChanged,
|
||||
});
|
||||
|
||||
if (autoLoadOnDiscovery) {
|
||||
log.info('hook auto-load enabled: every discovered QQ process will be injected');
|
||||
}
|
||||
@@ -90,18 +93,25 @@ async function main() {
|
||||
notificationManager.bind(bridgeManager);
|
||||
|
||||
let stopWebUI: (() => Promise<void>) | undefined;
|
||||
|
||||
if (
|
||||
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
|
||||
process.env.SNOWLUMA_DEV_WEBUI === '1'
|
||||
) {
|
||||
try {
|
||||
const { initWebUI } = await import('./webui/server');
|
||||
const started = await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, {
|
||||
const started = await initWebUI(
|
||||
runtimeConfig.webuiPort || 5099,
|
||||
oneBotManager,
|
||||
hookManager,
|
||||
notificationManager,
|
||||
{
|
||||
host: runtimeConfig.webuiHost,
|
||||
tlsEnabled: runtimeConfig.webuiTls?.enabled,
|
||||
trustProxy: runtimeConfig.trustProxy,
|
||||
stateBus: stateWiring.bus,
|
||||
});
|
||||
},
|
||||
);
|
||||
stopWebUI = started.stop;
|
||||
} catch (err) {
|
||||
log.error('Failed to start WebUI: ', err);
|
||||
@@ -111,56 +121,104 @@ async function main() {
|
||||
// Graceful shutdown: dispose managers, await log flush, then exit.
|
||||
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
|
||||
let shutdownStarted = false;
|
||||
|
||||
const shutdown = (signal: string) => async () => {
|
||||
if (shutdownStarted) return;
|
||||
if (shutdownStarted) {
|
||||
return;
|
||||
}
|
||||
|
||||
shutdownStarted = true;
|
||||
log.warn(`Shutting down (${signal})...`);
|
||||
let exitCode = 0;
|
||||
|
||||
try {
|
||||
await oneBotManager.dispose();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('OneBot shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
try { notificationManager.dispose(); } catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
log.error(
|
||||
'OneBot shutdown failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
if (stopWebUI) await stopWebUI();
|
||||
notificationManager.dispose();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('WebUI shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
log.error(
|
||||
'notification shutdown failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
if (stopWebUI) {
|
||||
await stopWebUI();
|
||||
}
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error(
|
||||
'WebUI shutdown failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
// Observers go deaf before Hook teardown. Hook dispose then emits the
|
||||
// same disconnected → PID detach → Bridge closed path as a live drop;
|
||||
// those closed edges must not look like a runtime offline.
|
||||
try { stateWiring.dispose(); } catch (error) {
|
||||
try {
|
||||
stateWiring.dispose();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('state wiring shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
log.error(
|
||||
'state wiring shutdown failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
try { stopNativeStageSync.stop(); } catch (error) {
|
||||
|
||||
try {
|
||||
stopNativeStageSync.stop();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('stage sync shutdown failed: %s', error instanceof Error ? error.message : String(error));
|
||||
log.error(
|
||||
'stage sync shutdown failed: %s',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
try { hookManager.dispose(); } catch (error) {
|
||||
|
||||
try {
|
||||
hookManager.dispose();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
log.error(
|
||||
'hook shutdown failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
await closeLogger();
|
||||
process.exit(exitCode);
|
||||
};
|
||||
|
||||
process.on('SIGINT', shutdown('SIGINT'));
|
||||
process.on('SIGTERM', shutdown('SIGTERM'));
|
||||
}
|
||||
|
||||
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
|
||||
const envRaw = process.env.SNOWLUMA_HOOK_AUTOLOAD;
|
||||
|
||||
if (typeof envRaw === 'string' && envRaw.trim()) {
|
||||
const v = envRaw.trim().toLowerCase();
|
||||
if (v === '1' || v === 'true' || v === 'yes' || v === 'on') return true;
|
||||
if (v === '0' || v === 'false' || v === 'no' || v === 'off') return false;
|
||||
|
||||
if (v === '1' || v === 'true' || v === 'yes' || v === 'on') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (v === '0' || v === 'false' || v === 'no' || v === 'off') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return fromConfig === true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import { readFileSync, writeFileSync, mkdirSync, statSync, openSync, readSync, closeSync, fstatSync } from 'node:fs';
|
||||
import {
|
||||
readFileSync,
|
||||
writeFileSync,
|
||||
mkdirSync,
|
||||
statSync,
|
||||
openSync,
|
||||
readSync,
|
||||
closeSync,
|
||||
fstatSync,
|
||||
} from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
@@ -22,23 +31,36 @@ export function publicLine(version: string, raw: string): string {
|
||||
}
|
||||
|
||||
function byteSize(lines: readonly string[]): number {
|
||||
if (lines.length === 0) return 0;
|
||||
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;
|
||||
|
||||
if (lines.length <= 1) {
|
||||
break;
|
||||
}
|
||||
|
||||
lines.shift();
|
||||
}
|
||||
if (lines.length === 0) return '';
|
||||
|
||||
if (lines.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
@@ -49,15 +71,27 @@ export function appendEvents(
|
||||
limit = MIRROR_LIMIT_BYTES,
|
||||
): string {
|
||||
const fresh = events.map((line) => line.trim()).filter((line) => line.length > 0);
|
||||
if (fresh.length === 0) return mirror;
|
||||
|
||||
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;
|
||||
if (isVersionHeader(line)) {
|
||||
lastHeader = line;
|
||||
}
|
||||
}
|
||||
|
||||
const next = [...lines];
|
||||
if (lastHeader !== header) next.push(header);
|
||||
|
||||
if (lastHeader !== header) {
|
||||
next.push(header);
|
||||
}
|
||||
|
||||
next.push(...fresh);
|
||||
return trimMirror(`${next.join('\n')}\n`, limit);
|
||||
}
|
||||
@@ -70,27 +104,39 @@ export function tempStagePath(
|
||||
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__;
|
||||
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();
|
||||
|
||||
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;
|
||||
|
||||
if (typeof code === 'string' && code) {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
return 'ERR';
|
||||
}
|
||||
|
||||
@@ -121,6 +167,7 @@ export function ingestTemp(args: {
|
||||
if (args.missing) {
|
||||
return { mirror: args.mirror, offset: args.offset, lines: [], missing: true };
|
||||
}
|
||||
|
||||
if (args.errorCode) {
|
||||
return {
|
||||
mirror: args.mirror,
|
||||
@@ -130,14 +177,20 @@ export function ingestTemp(args: {
|
||||
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);
|
||||
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,
|
||||
@@ -158,27 +211,42 @@ function readOffset(file: string): number {
|
||||
|
||||
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;
|
||||
|
||||
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 };
|
||||
|
||||
if (code === 'ENOENT') {
|
||||
return { text: '', missing: true };
|
||||
}
|
||||
|
||||
return { text: '', missing: false, errorCode: code };
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
if (fd !== undefined) {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,30 +259,50 @@ export function startNativeStageSync(options: StageSyncOptions): { stop: () => v
|
||||
let stopped = false;
|
||||
|
||||
const tick = () => {
|
||||
if (stopped) return;
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
|
||||
let tempSize = 0;
|
||||
|
||||
try {
|
||||
tempSize = statSync(options.tempPath).size;
|
||||
} catch (error) {
|
||||
const code = errorCode(error);
|
||||
if (code === 'ENOENT') return;
|
||||
|
||||
if (code === 'ENOENT') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', code);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
if (tempSize < offset) offset = 0;
|
||||
|
||||
if (tempSize < offset) {
|
||||
offset = 0;
|
||||
}
|
||||
|
||||
const temp = readTemp(options.tempPath);
|
||||
if (temp.missing) return;
|
||||
|
||||
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) {
|
||||
@@ -223,19 +311,23 @@ export function startNativeStageSync(options: StageSyncOptions): { stop: () => v
|
||||
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);
|
||||
@@ -247,12 +339,18 @@ export function startNativeStageSync(options: StageSyncOptions): { stop: () => v
|
||||
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);
|
||||
|
||||
if (lineSeverity(line) === 'error') {
|
||||
log.error('%s', text);
|
||||
} else {
|
||||
log.info('%s', text);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -125,16 +125,24 @@ export function defaultNotificationsConfig(): NotificationsConfig {
|
||||
* become `\\` and double-quotes become `\"`.
|
||||
*/
|
||||
export function renderTemplate(template: string, vars: Record<string, string>): string {
|
||||
if (typeof template !== 'string') return '';
|
||||
if (typeof template !== 'string') {
|
||||
return '';
|
||||
}
|
||||
|
||||
let isJson = false;
|
||||
|
||||
try {
|
||||
JSON.parse(template);
|
||||
isJson = true;
|
||||
} catch {
|
||||
// not JSON — plain text mode
|
||||
}
|
||||
|
||||
return template.replace(/\{(\w+)\}/g, (match, key: string) => {
|
||||
if (!Object.prototype.hasOwnProperty.call(vars, key)) return match;
|
||||
if (!Object.prototype.hasOwnProperty.call(vars, key)) {
|
||||
return match;
|
||||
}
|
||||
|
||||
const val = vars[key];
|
||||
return isJson ? val.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : val;
|
||||
});
|
||||
@@ -149,10 +157,20 @@ function strOr(value: unknown, fallback: string, maxLen: number): string {
|
||||
}
|
||||
|
||||
function normalizeChannelId(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = value.trim();
|
||||
if (v.length === 0 || v.length > CHANNEL_ID_MAX) return null;
|
||||
if (!CHANNEL_ID_RE.test(v)) return null;
|
||||
|
||||
if (v.length === 0 || v.length > CHANNEL_ID_MAX) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!CHANNEL_ID_RE.test(v)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
@@ -166,49 +184,100 @@ function isHttpUrl(value: string): boolean {
|
||||
}
|
||||
|
||||
function normalizeHeaders(value: unknown): Record<string, string> | undefined {
|
||||
if (!isObject(value)) return undefined;
|
||||
if (!isObject(value)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const out: Record<string, string> = {};
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const [rawName, rawValue] of Object.entries(value)) {
|
||||
if (Object.keys(out).length >= HEADERS_MAX) break;
|
||||
if (typeof rawValue !== 'string') continue;
|
||||
if (Object.keys(out).length >= HEADERS_MAX) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (typeof rawValue !== 'string') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = rawName.trim();
|
||||
if (name.length === 0 || name.length > HEADER_NAME_MAX) continue;
|
||||
if (!HEADER_NAME_RE.test(name)) continue;
|
||||
|
||||
if (name.length === 0 || name.length > HEADER_NAME_MAX) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!HEADER_NAME_RE.test(name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const folded = name.toLowerCase();
|
||||
if (seen.has(folded)) continue;
|
||||
|
||||
if (seen.has(folded)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const headerValue = rawValue.trim();
|
||||
if (headerValue.length === 0 || headerValue.length > HEADER_VALUE_MAX) continue;
|
||||
if (headerValue.includes('\r') || headerValue.includes('\n')) continue;
|
||||
|
||||
if (headerValue.length === 0 || headerValue.length > HEADER_VALUE_MAX) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (headerValue.includes('\r') || headerValue.includes('\n')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(folded);
|
||||
out[name] = headerValue;
|
||||
}
|
||||
|
||||
return Object.keys(out).length > 0 ? out : undefined;
|
||||
}
|
||||
|
||||
function normalizeSmtpHost(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = value.trim();
|
||||
if (!v || v.length > SMTP_HOST_MAX) return null;
|
||||
if (/\s/.test(v) || v.includes('/') || v.includes('://')) return null;
|
||||
|
||||
if (!v || v.length > SMTP_HOST_MAX) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (/\s/.test(v) || v.includes('/') || v.includes('://')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
function normalizeFrom(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = value.trim().slice(0, EMAIL_FIELD_MAX);
|
||||
return extractAddress(v) ? v : null;
|
||||
}
|
||||
|
||||
function normalizeTo(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const addrs = parseRecipients(value.trim().slice(0, EMAIL_FIELD_MAX));
|
||||
return addrs.length > 0 ? addrs.join(', ') : null;
|
||||
}
|
||||
|
||||
function normalizeChannelType(value: unknown): NotificationChannelType | null {
|
||||
if (value === 'email') return 'email';
|
||||
if (value === 'webhook' || value === undefined || value === '') return 'webhook';
|
||||
if (value === 'email') {
|
||||
return 'email';
|
||||
}
|
||||
|
||||
if (value === 'webhook' || value === undefined || value === '') {
|
||||
return 'webhook';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -220,20 +289,25 @@ function normalizeEmailChannel(
|
||||
const smtpHost = normalizeSmtpHost(raw.smtpHost);
|
||||
const from = normalizeFrom(raw.from);
|
||||
const to = normalizeTo(raw.to);
|
||||
if (!smtpHost || !from || !to) return null;
|
||||
|
||||
if (!smtpHost || !from || !to) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const portRaw = raw.smtpPort;
|
||||
const portProvided = portRaw !== undefined && portRaw !== null && portRaw !== '';
|
||||
const secureProvided = typeof raw.smtpSecure === 'boolean';
|
||||
const port = portProvided
|
||||
? clampInt(portRaw, SMTP_PORT_MIN, SMTP_PORT_MAX, 0)
|
||||
: 0;
|
||||
if (portProvided && port === 0) return null;
|
||||
const port = portProvided ? clampInt(portRaw, SMTP_PORT_MIN, SMTP_PORT_MAX, 0) : 0;
|
||||
|
||||
if (portProvided && port === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const smtpSecure = secureProvided ? Boolean(raw.smtpSecure) : port === 465 || port === 0;
|
||||
const smtpPort = port === 0 ? (smtpSecure ? 465 : 587) : port;
|
||||
|
||||
const smtpUser = typeof raw.smtpUser === 'string' ? raw.smtpUser.trim().slice(0, SMTP_USER_MAX) : '';
|
||||
const smtpUser =
|
||||
typeof raw.smtpUser === 'string' ? raw.smtpUser.trim().slice(0, SMTP_USER_MAX) : '';
|
||||
const smtpPass = typeof raw.smtpPass === 'string' ? raw.smtpPass.slice(0, SMTP_PASS_MAX) : '';
|
||||
|
||||
return {
|
||||
@@ -250,7 +324,9 @@ function normalizeEmailChannel(
|
||||
...(smtpPass ? { smtpPass } : {}),
|
||||
from,
|
||||
to,
|
||||
subjectTemplate: strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) || DEFAULT_SUBJECT_TEMPLATE,
|
||||
subjectTemplate:
|
||||
strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) ||
|
||||
DEFAULT_SUBJECT_TEMPLATE,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -258,16 +334,34 @@ function normalizeEmailChannel(
|
||||
* http(s) URL for webhooks, SMTP host + from/to for email. Anything else
|
||||
* is dropped (total normalize). */
|
||||
function normalizeChannel(raw: unknown): NotificationChannel | null {
|
||||
if (!isObject(raw)) return null;
|
||||
if (!isObject(raw)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const id = normalizeChannelId(raw.id);
|
||||
if (!id) return null;
|
||||
|
||||
if (!id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const type = normalizeChannelType(raw.type);
|
||||
if (!type) return null;
|
||||
|
||||
if (!type) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
|
||||
if (type === 'email') return normalizeEmailChannel(raw, id, name);
|
||||
|
||||
if (type === 'email') {
|
||||
return normalizeEmailChannel(raw, id, name);
|
||||
}
|
||||
|
||||
const url = typeof raw.url === 'string' ? raw.url.trim() : '';
|
||||
if (!isHttpUrl(url)) return null;
|
||||
|
||||
if (!isHttpUrl(url)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const headers = normalizeHeaders(raw.headers);
|
||||
return {
|
||||
id,
|
||||
@@ -281,16 +375,28 @@ function normalizeChannel(raw: unknown): NotificationChannel | null {
|
||||
}
|
||||
|
||||
function normalizeChannels(value: unknown): NotificationChannel[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
const out: NotificationChannel[] = [];
|
||||
|
||||
for (const raw of value) {
|
||||
const ch = normalizeChannel(raw);
|
||||
if (!ch) continue;
|
||||
if (seen.has(ch.id)) continue; // dedupe by id — first occurrence wins
|
||||
|
||||
if (!ch) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (seen.has(ch.id)) {
|
||||
continue;
|
||||
} // dedupe by id — first occurrence wins
|
||||
|
||||
seen.add(ch.id);
|
||||
out.push(ch);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -317,7 +423,9 @@ function ensureConfigDir(): void {
|
||||
function enforceSensitiveFileMode(file: string): void {
|
||||
// POSIX mode bits do not model Windows ACLs; on Windows the inherited ACL
|
||||
// remains authoritative. Avoid pretending chmod provides equivalent policy.
|
||||
if (process.platform !== 'win32') fs.chmodSync(file, 0o600);
|
||||
if (process.platform !== 'win32') {
|
||||
fs.chmodSync(file, 0o600);
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(config: NotificationsConfig): void {
|
||||
@@ -336,16 +444,24 @@ let cached: NotificationsConfig | null = null;
|
||||
|
||||
/** Load + normalize the channel store, creating it from defaults if absent. */
|
||||
export function loadNotificationsConfig(): NotificationsConfig {
|
||||
if (cached) return cached;
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
ensureConfigDir();
|
||||
|
||||
if (!fs.existsSync(NOTIFICATIONS_CONFIG_PATH)) {
|
||||
const fresh = defaultNotificationsConfig();
|
||||
|
||||
try {
|
||||
atomicWrite(fresh);
|
||||
} catch (err) {
|
||||
log.warn('failed to write initial notifications.json: %s', err instanceof Error ? err.message : String(err));
|
||||
log.warn(
|
||||
'failed to write initial notifications.json: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
@@ -358,18 +474,26 @@ export function loadNotificationsConfig(): NotificationsConfig {
|
||||
const raw = fs.readFileSync(NOTIFICATIONS_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
const normalized = normalizeNotificationsConfig(parsed);
|
||||
|
||||
// Self-heal on disk only if normalization changed something (corrupt/old).
|
||||
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
|
||||
try {
|
||||
atomicWrite(normalized);
|
||||
} catch (err) {
|
||||
log.warn('failed to normalize notifications.json on disk: %s', err instanceof Error ? err.message : String(err));
|
||||
log.warn(
|
||||
'failed to normalize notifications.json on disk: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
cached = normalized;
|
||||
return normalized;
|
||||
} catch (err) {
|
||||
log.warn('notifications.json unreadable; using defaults: %s', err instanceof Error ? err.message : String(err));
|
||||
log.warn(
|
||||
'notifications.json unreadable; using defaults: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
const fresh = defaultNotificationsConfig();
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
@@ -388,7 +512,12 @@ export function saveNotificationsConfig(incoming: unknown): NotificationsConfig
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds:
|
||||
v.debounceSeconds !== undefined
|
||||
? clampInt(v.debounceSeconds, DEBOUNCE_SECONDS_MIN, DEBOUNCE_SECONDS_MAX, DEFAULT_DEBOUNCE_SECONDS)
|
||||
? clampInt(
|
||||
v.debounceSeconds,
|
||||
DEBOUNCE_SECONDS_MIN,
|
||||
DEBOUNCE_SECONDS_MAX,
|
||||
DEFAULT_DEBOUNCE_SECONDS,
|
||||
)
|
||||
: current.debounceSeconds,
|
||||
channels: Array.isArray(v.channels) ? normalizeChannels(v.channels) : current.channels,
|
||||
};
|
||||
|
||||
@@ -29,10 +29,12 @@ export class DebounceMachine {
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -40,7 +42,11 @@ export class DebounceMachine {
|
||||
* reload takes effect on the next transition. */
|
||||
onOffline(uin: string, debounceSeconds: number): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (s.firedOffline || s.pending) return { kind: 'none' }; // already down / already counting
|
||||
|
||||
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.
|
||||
@@ -48,6 +54,7 @@ export class DebounceMachine {
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
|
||||
s.pending = true;
|
||||
return { kind: 'schedule', delayMs: debounceSeconds * 1000 };
|
||||
}
|
||||
@@ -55,21 +62,28 @@ export class DebounceMachine {
|
||||
/** Account came online. */
|
||||
onOnline(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
|
||||
if (s.pending) {
|
||||
s.pending = false;
|
||||
return { kind: 'cancel' }; // self-heal within the debounce window — nothing fired
|
||||
}
|
||||
|
||||
if (s.firedOffline) {
|
||||
s.firedOffline = false;
|
||||
return { kind: 'emit', event: 'online' }; // recovery, paired with the fired offline
|
||||
}
|
||||
|
||||
return { kind: 'none' }; // cold online / already up
|
||||
}
|
||||
|
||||
/** The offline debounce window elapsed (the armed timer fired). */
|
||||
onTimerElapsed(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (!s.pending) return { kind: 'none' }; // cancelled before firing
|
||||
|
||||
if (!s.pending) {
|
||||
return { kind: 'none' };
|
||||
} // cancelled before firing
|
||||
|
||||
s.pending = false;
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
|
||||
@@ -79,7 +79,10 @@ function errMsg(err: unknown): string {
|
||||
* Pure: the channels a UIN should be notified through — globally enabled AND
|
||||
* opted into by the UIN — preserving config order. Exported for unit tests.
|
||||
*/
|
||||
export function selectChannels(channels: NotificationChannel[], enabledIds: string[]): NotificationChannel[] {
|
||||
export function selectChannels(
|
||||
channels: NotificationChannel[],
|
||||
enabledIds: string[],
|
||||
): NotificationChannel[] {
|
||||
const wanted = new Set(enabledIds);
|
||||
return channels.filter((c) => c.enabled && wanted.has(c.id));
|
||||
}
|
||||
@@ -101,19 +104,35 @@ export class NotificationManager {
|
||||
/** Subscribe to the global session online/offline edges. Register AFTER
|
||||
* OneBotManager so the nickname fallback is already populated. */
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) => this.handleOnline(uin, bridge.identity.nickname));
|
||||
bridgeManager.addSessionClosedListener((uin, bridge) => this.handleOffline(uin, bridge.identity.nickname));
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) =>
|
||||
this.handleOnline(uin, bridge.identity.nickname),
|
||||
);
|
||||
bridgeManager.addSessionClosedListener((uin, bridge) =>
|
||||
this.handleOffline(uin, bridge.identity.nickname),
|
||||
);
|
||||
}
|
||||
|
||||
handleOnline(uin: string, nickname?: string): void {
|
||||
if (this.disposed) return;
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nickname) {
|
||||
this.nicknames.set(uin, nickname);
|
||||
}
|
||||
|
||||
this.apply(uin, this.machine.onOnline(uin));
|
||||
}
|
||||
|
||||
handleOffline(uin: string, nickname?: string): void {
|
||||
if (this.disposed) return;
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nickname) {
|
||||
this.nicknames.set(uin, nickname);
|
||||
}
|
||||
|
||||
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
|
||||
}
|
||||
|
||||
@@ -129,26 +148,36 @@ export class NotificationManager {
|
||||
switch (decision.kind) {
|
||||
case 'schedule': {
|
||||
const existing = this.timers.get(uin);
|
||||
if (existing) clearTimeout(existing);
|
||||
|
||||
if (existing) {
|
||||
clearTimeout(existing);
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
this.timers.delete(uin);
|
||||
this.apply(uin, this.machine.onTimerElapsed(uin));
|
||||
}, decision.delayMs);
|
||||
|
||||
// Don't let a pending notification timer keep the process alive.
|
||||
if (typeof (timer as { unref?: () => void }).unref === 'function') {
|
||||
(timer as { unref: () => void }).unref();
|
||||
}
|
||||
|
||||
this.timers.set(uin, timer);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'cancel': {
|
||||
const timer = this.timers.get(uin);
|
||||
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.timers.delete(uin);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 'emit':
|
||||
void this.notify(uin, decision.event);
|
||||
break;
|
||||
@@ -161,6 +190,7 @@ export class NotificationManager {
|
||||
* 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));
|
||||
@@ -168,7 +198,10 @@ export class NotificationManager {
|
||||
log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err));
|
||||
return;
|
||||
}
|
||||
if (channels.length === 0) return;
|
||||
|
||||
if (channels.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nickname = this.nicknames.get(uin) || uin;
|
||||
const vars: Record<string, string> = {
|
||||
@@ -187,19 +220,36 @@ export class NotificationManager {
|
||||
channelId: ch.id,
|
||||
ok: result.ok,
|
||||
status: result.status,
|
||||
error: result.ok ? undefined : (result.error ?? (result.status ? `HTTP ${result.status}` : 'delivery failed')),
|
||||
error: result.ok
|
||||
? undefined
|
||||
: (result.error ??
|
||||
(result.status ? `HTTP ${result.status}` : 'delivery failed')),
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
log.warn('notify %s→%s channel=%s failed: %s', uin, event, ch.id, result.error ?? `HTTP ${result.status ?? '?'}`);
|
||||
log.warn(
|
||||
'notify %s→%s channel=%s failed: %s',
|
||||
uin,
|
||||
event,
|
||||
ch.id,
|
||||
result.error ?? `HTTP ${result.status ?? '?'}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async deliver(ch: NotificationChannel, vars: Record<string, string>): Promise<PostResult> {
|
||||
private async deliver(
|
||||
ch: NotificationChannel,
|
||||
vars: Record<string, string>,
|
||||
): Promise<PostResult> {
|
||||
try {
|
||||
if (isEmailChannel(ch)) {
|
||||
const send = this.deps.sendMail;
|
||||
if (!send) return { ok: false, error: 'email delivery is not configured' };
|
||||
|
||||
if (!send) {
|
||||
return { ok: false, error: 'email delivery is not configured' };
|
||||
}
|
||||
|
||||
return await send({
|
||||
host: ch.smtpHost,
|
||||
port: ch.smtpPort,
|
||||
@@ -212,6 +262,7 @@ export class NotificationManager {
|
||||
text: renderTemplate(ch.bodyTemplate, vars),
|
||||
});
|
||||
}
|
||||
|
||||
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
|
||||
} catch (err) {
|
||||
// Injected collaborators are contracted not to throw, but guard anyway.
|
||||
@@ -225,12 +276,17 @@ export class NotificationManager {
|
||||
* `found:false` means the channel id is unknown. */
|
||||
async testSend(channelId: string): Promise<PostResult & { found: boolean }> {
|
||||
let channel: NotificationChannel | undefined;
|
||||
|
||||
try {
|
||||
channel = this.deps.loadConfig().channels.find((c) => c.id === channelId);
|
||||
} catch (err) {
|
||||
return { ok: false, found: false, error: errMsg(err) };
|
||||
}
|
||||
if (!channel) return { ok: false, found: false };
|
||||
|
||||
if (!channel) {
|
||||
return { ok: false, found: false };
|
||||
}
|
||||
|
||||
const vars = {
|
||||
uin: '10000',
|
||||
nickname: '测试账号',
|
||||
@@ -242,6 +298,7 @@ export class NotificationManager {
|
||||
|
||||
private record(rec: DeliveryRecord): void {
|
||||
this.history.push(rec);
|
||||
|
||||
if (this.history.length > this.historyLimit) {
|
||||
this.history.splice(0, this.history.length - this.historyLimit);
|
||||
}
|
||||
@@ -254,9 +311,16 @@ export class NotificationManager {
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.disposed = true;
|
||||
for (const timer of this.timers.values()) clearTimeout(timer);
|
||||
|
||||
for (const timer of this.timers.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
this.timers.clear();
|
||||
}
|
||||
}
|
||||
@@ -274,7 +338,11 @@ export function createDefaultPost(
|
||||
body,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
return { ok: res.ok, status: res.status, error: res.ok ? undefined : `HTTP ${res.status}` };
|
||||
return {
|
||||
ok: res.ok,
|
||||
status: res.status,
|
||||
error: res.ok ? undefined : `HTTP ${res.status}`,
|
||||
};
|
||||
} catch (err) {
|
||||
return { ok: false, error: errMsg(err) };
|
||||
}
|
||||
@@ -284,10 +352,13 @@ export function createDefaultPost(
|
||||
const DEFAULT_SMTP_TIMEOUT_MS = 15_000;
|
||||
|
||||
/** Default SMTP send. Never throws. */
|
||||
export function createDefaultSendMail(timeoutMs = DEFAULT_SMTP_TIMEOUT_MS): NonNullable<NotificationManagerDeps['sendMail']> {
|
||||
export function createDefaultSendMail(
|
||||
timeoutMs = DEFAULT_SMTP_TIMEOUT_MS,
|
||||
): NonNullable<NotificationManagerDeps['sendMail']> {
|
||||
return async (mail) => {
|
||||
try {
|
||||
await sendSmtpMail({
|
||||
await sendSmtpMail(
|
||||
{
|
||||
host: mail.host,
|
||||
port: mail.port,
|
||||
secure: mail.secure,
|
||||
@@ -297,7 +368,9 @@ export function createDefaultSendMail(timeoutMs = DEFAULT_SMTP_TIMEOUT_MS): NonN
|
||||
to: parseRecipients(mail.to),
|
||||
subject: mail.subject,
|
||||
body: mail.text,
|
||||
}, { timeoutMs });
|
||||
},
|
||||
{ timeoutMs },
|
||||
);
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
return { ok: false, error: formatSmtpError(err, mail.host, mail.port) };
|
||||
|
||||
@@ -45,7 +45,11 @@ export function looksLikeEmail(value: string): boolean {
|
||||
/** Address from `Name <user@host>` or a bare addr; null if neither is usable. */
|
||||
export function extractAddress(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const angled = /<([^<>]+)>/.exec(trimmed);
|
||||
const addr = (angled ? angled[1] : trimmed).trim();
|
||||
return looksLikeEmail(addr) ? addr : null;
|
||||
@@ -55,19 +59,32 @@ export function extractAddress(value: string): string | null {
|
||||
export function parseRecipients(value: string): string[] {
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
|
||||
for (const part of value.split(/[,;\n]+/)) {
|
||||
const addr = extractAddress(part);
|
||||
if (!addr) continue;
|
||||
|
||||
if (!addr) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = addr.toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
|
||||
if (seen.has(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(key);
|
||||
out.push(addr);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
function encodeHeader(value: string): string {
|
||||
if (/^[\x20-\x7E]*$/.test(value) && !/[\r\n]/.test(value)) return value;
|
||||
if (/^[\x20-\x7E]*$/.test(value) && !/[\r\n]/.test(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`;
|
||||
}
|
||||
|
||||
@@ -117,19 +134,30 @@ function consumeReply(buf: string): { reply: SmtpReply; rest: string } | null {
|
||||
let offset = 0;
|
||||
const lines: string[] = [];
|
||||
let code = 0;
|
||||
|
||||
while (offset < buf.length) {
|
||||
const nl = buf.indexOf('\n', offset);
|
||||
if (nl === -1) return null;
|
||||
|
||||
if (nl === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const line = buf.slice(offset, nl).replace(/\r$/, '');
|
||||
offset = nl + 1;
|
||||
const m = /^(\d{3})([ -])(.*)$/.exec(line);
|
||||
if (!m) continue;
|
||||
|
||||
if (!m) {
|
||||
continue;
|
||||
}
|
||||
|
||||
code = Number(m[1]);
|
||||
lines.push(m[3]);
|
||||
|
||||
if (m[2] === ' ') {
|
||||
return { reply: { code, lines, text: lines.join('\n') }, rest: buf.slice(offset) };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -138,15 +166,23 @@ type SmtpSock = net.Socket | tls.TLSSocket;
|
||||
function parseCapabilities(reply: SmtpReply): { starttls: boolean; auth: Set<string> } {
|
||||
const auth = new Set<string>();
|
||||
let starttls = false;
|
||||
|
||||
for (const line of reply.lines) {
|
||||
const u = line.toUpperCase();
|
||||
if (u === 'STARTTLS' || u.startsWith('STARTTLS ')) starttls = true;
|
||||
|
||||
if (u === 'STARTTLS' || u.startsWith('STARTTLS ')) {
|
||||
starttls = true;
|
||||
}
|
||||
|
||||
if (u.startsWith('AUTH ')) {
|
||||
for (const mech of u.slice(5).split(/\s+/)) {
|
||||
if (mech) auth.add(mech);
|
||||
if (mech) {
|
||||
auth.add(mech);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { starttls, auth };
|
||||
}
|
||||
|
||||
@@ -166,12 +202,16 @@ function connectSocket(
|
||||
rejectUnauthorized,
|
||||
})
|
||||
: net.connect({ host, port });
|
||||
|
||||
const fail = (err: Error) => {
|
||||
sock.destroy();
|
||||
reject(err);
|
||||
};
|
||||
|
||||
sock.setTimeout(timeoutMs);
|
||||
sock.once('timeout', () => fail(new SmtpError('SMTP connection timed out', { code: 'ETIMEDOUT' })));
|
||||
sock.once('timeout', () =>
|
||||
fail(new SmtpError('SMTP connection timed out', { code: 'ETIMEDOUT' })),
|
||||
);
|
||||
sock.once('error', fail);
|
||||
sock.once(secure ? 'secureConnect' : 'connect', () => {
|
||||
sock.removeAllListeners('timeout');
|
||||
@@ -188,11 +228,14 @@ function upgradeTls(
|
||||
rejectUnauthorized: boolean,
|
||||
): Promise<tls.TLSSocket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const tlsSocket = tls.connect({
|
||||
const tlsSocket = tls.connect(
|
||||
{
|
||||
socket,
|
||||
servername: net.isIP(host) === 0 ? host : undefined,
|
||||
rejectUnauthorized,
|
||||
}, () => resolve(tlsSocket));
|
||||
},
|
||||
() => resolve(tlsSocket),
|
||||
);
|
||||
tlsSocket.setTimeout(timeoutMs);
|
||||
tlsSocket.once('timeout', () => {
|
||||
tlsSocket.destroy();
|
||||
@@ -218,32 +261,42 @@ class SmtpSession {
|
||||
|
||||
async read(): Promise<SmtpReply> {
|
||||
const ready = consumeReply(this.buf);
|
||||
|
||||
if (ready) {
|
||||
this.buf = ready.rest;
|
||||
return ready.reply;
|
||||
}
|
||||
|
||||
return new Promise<SmtpReply>((resolve, reject) => {
|
||||
const onData = (chunk: Buffer) => {
|
||||
this.buf += chunk.toString('utf8');
|
||||
const got = consumeReply(this.buf);
|
||||
if (!got) return;
|
||||
|
||||
if (!got) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.buf = got.rest;
|
||||
cleanup();
|
||||
resolve(got.reply);
|
||||
};
|
||||
|
||||
const onError = (err: Error) => {
|
||||
cleanup();
|
||||
reject(err);
|
||||
};
|
||||
|
||||
const onClose = () => {
|
||||
cleanup();
|
||||
reject(new SmtpError('SMTP connection closed'));
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
this.socket.removeListener('data', onData);
|
||||
this.socket.removeListener('error', onError);
|
||||
this.socket.removeListener('close', onClose);
|
||||
};
|
||||
|
||||
this.socket.on('data', onData);
|
||||
this.socket.once('error', onError);
|
||||
this.socket.once('close', onClose);
|
||||
@@ -257,12 +310,14 @@ class SmtpSession {
|
||||
async command(line: string, ok: (code: number) => boolean, label?: string): Promise<SmtpReply> {
|
||||
this.write(line + CRLF);
|
||||
const reply = await this.read();
|
||||
|
||||
if (!ok(reply.code)) {
|
||||
const name = label ?? line.split(' ')[0] ?? 'SMTP';
|
||||
throw new SmtpError(`${name} failed: ${reply.code} ${reply.text}`.trim(), {
|
||||
responseCode: reply.code,
|
||||
});
|
||||
}
|
||||
|
||||
return reply;
|
||||
}
|
||||
|
||||
@@ -277,19 +332,28 @@ export function formatSmtpError(err: unknown, host: string, port: number): strin
|
||||
if (err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND' || err.code === 'ETIMEDOUT') {
|
||||
return `无法连接 SMTP:${host}:${port}`;
|
||||
}
|
||||
if (err.responseCode === 535) return 'SMTP 认证失败';
|
||||
|
||||
if (err.responseCode === 535) {
|
||||
return 'SMTP 认证失败';
|
||||
}
|
||||
|
||||
return err.message;
|
||||
}
|
||||
|
||||
if (err instanceof Error) {
|
||||
const code = (err as NodeJS.ErrnoException).code;
|
||||
|
||||
if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'ETIMEDOUT') {
|
||||
return `无法连接 SMTP:${host}:${port}`;
|
||||
}
|
||||
|
||||
if (/self-signed|unable to verify/i.test(err.message)) {
|
||||
return `SMTP 证书不受信任:${host}`;
|
||||
}
|
||||
|
||||
return err.message || '邮件发送失败';
|
||||
}
|
||||
|
||||
return '邮件发送失败';
|
||||
}
|
||||
|
||||
@@ -297,20 +361,38 @@ export async function sendSmtpMail(mail: SmtpMail, opts: SendSmtpOptions = {}):
|
||||
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const rejectUnauthorized = opts.rejectUnauthorized ?? true;
|
||||
const fromAddr = extractAddress(mail.from);
|
||||
if (!fromAddr) throw new SmtpError('invalid from address');
|
||||
if (mail.to.length === 0) throw new SmtpError('no recipients');
|
||||
|
||||
let sock = await connectSocket(mail.host, mail.port, mail.secure, timeoutMs, rejectUnauthorized);
|
||||
if (!fromAddr) {
|
||||
throw new SmtpError('invalid from address');
|
||||
}
|
||||
|
||||
if (mail.to.length === 0) {
|
||||
throw new SmtpError('no recipients');
|
||||
}
|
||||
|
||||
let sock = await connectSocket(
|
||||
mail.host,
|
||||
mail.port,
|
||||
mail.secure,
|
||||
timeoutMs,
|
||||
rejectUnauthorized,
|
||||
);
|
||||
const session = new SmtpSession(sock);
|
||||
let finished = false;
|
||||
|
||||
const failTimeout = () => {
|
||||
if (finished) return;
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
|
||||
session.destroy();
|
||||
};
|
||||
|
||||
session.attachTimeout(timeoutMs, failTimeout);
|
||||
|
||||
try {
|
||||
const greeting = await session.read();
|
||||
|
||||
if (greeting.code !== 220) {
|
||||
throw new SmtpError(`SMTP greeting failed: ${greeting.code} ${greeting.text}`.trim(), {
|
||||
responseCode: greeting.code,
|
||||
@@ -322,7 +404,12 @@ export async function sendSmtpMail(mail: SmtpMail, opts: SendSmtpOptions = {}):
|
||||
|
||||
if (!mail.secure && caps.starttls) {
|
||||
await session.command('STARTTLS', (c) => c === 220);
|
||||
const upgraded = await upgradeTls(sock as net.Socket, mail.host, timeoutMs, rejectUnauthorized);
|
||||
const upgraded = await upgradeTls(
|
||||
sock as net.Socket,
|
||||
mail.host,
|
||||
timeoutMs,
|
||||
rejectUnauthorized,
|
||||
);
|
||||
session.replaceSocket(upgraded);
|
||||
session.attachTimeout(timeoutMs, failTimeout);
|
||||
sock = upgraded;
|
||||
@@ -330,22 +417,27 @@ export async function sendSmtpMail(mail: SmtpMail, opts: SendSmtpOptions = {}):
|
||||
}
|
||||
|
||||
const user = mail.user?.trim() ?? '';
|
||||
|
||||
if (user) {
|
||||
await authenticate(session, caps.auth, user, mail.pass ?? '');
|
||||
}
|
||||
|
||||
await session.command(`MAIL FROM:<${fromAddr}>`, (c) => c === 250);
|
||||
|
||||
for (const rcpt of mail.to) {
|
||||
await session.command(`RCPT TO:<${rcpt}>`, (c) => c === 250 || c === 251);
|
||||
}
|
||||
|
||||
await session.command('DATA', (c) => c === 354);
|
||||
session.write(dotStuff(buildMimeMessage(mail)));
|
||||
await session.command('.', (c) => c === 250, 'DATA');
|
||||
|
||||
try {
|
||||
await session.command('QUIT', (c) => c === 221);
|
||||
} catch {
|
||||
// Some relays drop the socket after 250; delivery already succeeded.
|
||||
}
|
||||
|
||||
finished = true;
|
||||
} catch (err) {
|
||||
finished = true;
|
||||
@@ -363,16 +455,23 @@ async function authenticate(
|
||||
): Promise<void> {
|
||||
const hasPlain = mechs.has('PLAIN');
|
||||
const hasLogin = mechs.has('LOGIN');
|
||||
|
||||
if (hasPlain || !hasLogin) {
|
||||
try {
|
||||
const token = Buffer.from(`\0${user}\0${pass}`, 'utf8').toString('base64');
|
||||
await session.command(`AUTH PLAIN ${token}`, (c) => c === 235, 'AUTH');
|
||||
return;
|
||||
} catch (err) {
|
||||
if (hasPlain && !hasLogin) throw err;
|
||||
if (err instanceof SmtpError && err.responseCode === 535) throw err;
|
||||
if (hasPlain && !hasLogin) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (err instanceof SmtpError && err.responseCode === 535) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await loginAuth(session, user, pass);
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,9 @@ export function bindSystemFaceCatalog(
|
||||
options: SystemFaceCatalogBindingOptions = {},
|
||||
): void {
|
||||
const store = options.store ?? sysFaceStore;
|
||||
const storage = options.storage ?? new JsonSysFaceCatalogStorage(
|
||||
const storage =
|
||||
options.storage ??
|
||||
new JsonSysFaceCatalogStorage(
|
||||
path.join(options.dataRoot ?? 'data', 'sys-face-catalog.json'),
|
||||
);
|
||||
store.configureStorage(storage);
|
||||
|
||||
@@ -27,8 +27,15 @@ export function isDevAuthMode(): boolean {
|
||||
|
||||
function envBootstrapPassword(): string | null {
|
||||
const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
|
||||
if (!raw || typeof raw !== 'string') return null;
|
||||
if (raw.length < 8) return null;
|
||||
|
||||
if (!raw || typeof raw !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (raw.length < 8) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return raw;
|
||||
}
|
||||
|
||||
@@ -55,7 +62,9 @@ export const PASSWORD_RULES: PasswordRule[] = [
|
||||
{ id: 'no-space', label: '不包含空格', test: (p) => !/\s/.test(p) && p.length > 0 },
|
||||
];
|
||||
|
||||
export function evaluatePasswordRules(password: string): { id: string; label: string; ok: boolean }[] {
|
||||
export function evaluatePasswordRules(
|
||||
password: string,
|
||||
): { id: string; label: string; ok: boolean }[] {
|
||||
return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, ok: r.test(password) }));
|
||||
}
|
||||
|
||||
@@ -82,25 +91,43 @@ export function prepareWebuiAuthStateForRestore(value: unknown): WebuiAuthState
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('credential state must be an object');
|
||||
}
|
||||
|
||||
const v = value as Record<string, unknown>;
|
||||
|
||||
if (typeof v.passwordHash !== 'string' || !/^[0-9a-f]{128}$/i.test(v.passwordHash)) {
|
||||
throw new Error('passwordHash must be exactly 128 hexadecimal characters');
|
||||
}
|
||||
|
||||
if (typeof v.passwordSalt !== 'string' || !/^[0-9a-f]{32}$/i.test(v.passwordSalt)) {
|
||||
throw new Error('passwordSalt must be exactly 32 hexadecimal characters');
|
||||
}
|
||||
|
||||
if (typeof v.mustChangePassword !== 'boolean') {
|
||||
throw new Error('mustChangePassword must be a boolean');
|
||||
}
|
||||
|
||||
if (typeof v.generatedAt !== 'string' || !Number.isFinite(Date.parse(v.generatedAt))) {
|
||||
throw new Error('generatedAt must be a valid timestamp');
|
||||
}
|
||||
|
||||
if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) {
|
||||
throw new Error('updatedAt must be a valid timestamp');
|
||||
}
|
||||
const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt', 'totp']);
|
||||
|
||||
const allowed = new Set([
|
||||
'passwordHash',
|
||||
'passwordSalt',
|
||||
'mustChangePassword',
|
||||
'generatedAt',
|
||||
'updatedAt',
|
||||
'totp',
|
||||
]);
|
||||
const unknown = Object.keys(v).find((key) => !allowed.has(key));
|
||||
if (unknown) throw new Error(`unknown field $.${unknown}`);
|
||||
|
||||
if (unknown) {
|
||||
throw new Error(`unknown field $.${unknown}`);
|
||||
}
|
||||
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: v.passwordHash,
|
||||
passwordSalt: v.passwordSalt,
|
||||
@@ -108,30 +135,41 @@ export function prepareWebuiAuthStateForRestore(value: unknown): WebuiAuthState
|
||||
generatedAt: v.generatedAt,
|
||||
updatedAt: v.updatedAt,
|
||||
};
|
||||
|
||||
if (!Object.prototype.hasOwnProperty.call(v, 'totp') || v.totp === undefined) {
|
||||
return state;
|
||||
}
|
||||
|
||||
state.totp = prepareTotpStateForRestore(v.totp);
|
||||
return state;
|
||||
}
|
||||
|
||||
function parseLiveAuthState(value: unknown): WebuiAuthState | null {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = value as Record<string, unknown>;
|
||||
const totpValue = v.totp;
|
||||
const withoutTotp = { ...v };
|
||||
delete withoutTotp.totp;
|
||||
|
||||
try {
|
||||
const state = prepareWebuiAuthStateForRestore(
|
||||
Object.prototype.hasOwnProperty.call(v, 'totp')
|
||||
? withoutTotp
|
||||
: value,
|
||||
Object.prototype.hasOwnProperty.call(v, 'totp') ? withoutTotp : value,
|
||||
);
|
||||
const totp = parseTotpStateLenient(totpValue);
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(v, 'totp') && totpValue !== undefined && !totp) {
|
||||
log.warn('webui.json totp field is invalid and will be ignored; password credentials are unchanged');
|
||||
log.warn(
|
||||
'webui.json totp field is invalid and will be ignored; password credentials are unchanged',
|
||||
);
|
||||
}
|
||||
if (totp) state.totp = totp;
|
||||
|
||||
if (totp) {
|
||||
state.totp = totp;
|
||||
}
|
||||
|
||||
return state;
|
||||
} catch {
|
||||
return null;
|
||||
@@ -157,7 +195,10 @@ function backupCorruptConfig(): void {
|
||||
fs.renameSync(WEBUI_CONFIG_PATH, dest);
|
||||
log.warn('previous webui.json moved to %s', dest);
|
||||
} catch (err) {
|
||||
log.warn('failed to back up corrupt webui.json: %s', err instanceof Error ? err.message : String(err));
|
||||
log.warn(
|
||||
'failed to back up corrupt webui.json: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,11 +206,13 @@ function atomicWrite(state: WebuiAuthState): void {
|
||||
ensureConfigDir();
|
||||
const tmp = WEBUI_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 });
|
||||
|
||||
try {
|
||||
fs.chmodSync(tmp, 0o600);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
fs.renameSync(tmp, WEBUI_CONFIG_PATH);
|
||||
}
|
||||
|
||||
@@ -198,12 +241,15 @@ export class WebuiAuth {
|
||||
};
|
||||
return new WebuiAuth(state, null, true);
|
||||
}
|
||||
|
||||
ensureConfigDir();
|
||||
|
||||
if (fs.existsSync(WEBUI_CONFIG_PATH)) {
|
||||
try {
|
||||
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
const live = parseLiveAuthState(parsed);
|
||||
|
||||
if (live) {
|
||||
if (live.mustChangePassword) {
|
||||
// Previous start generated a bootstrap password but the operator
|
||||
@@ -213,11 +259,15 @@ export class WebuiAuth {
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
log.warn('previous bootstrap password was never rotated; regenerated a new one');
|
||||
log.warn(
|
||||
'previous bootstrap password was never rotated; regenerated a new one',
|
||||
);
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
|
||||
return new WebuiAuth(live, null, false);
|
||||
}
|
||||
|
||||
log.error('webui.json schema invalid; backing up and regenerating credentials');
|
||||
backupCorruptConfig();
|
||||
} catch (err) {
|
||||
@@ -228,7 +278,9 @@ export class WebuiAuth {
|
||||
backupCorruptConfig();
|
||||
}
|
||||
}
|
||||
|
||||
const envPassword = envBootstrapPassword();
|
||||
|
||||
if (envPassword !== null) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(envPassword, salt);
|
||||
@@ -244,6 +296,7 @@ export class WebuiAuth {
|
||||
log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD');
|
||||
return new WebuiAuth(state, null, false);
|
||||
}
|
||||
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
@@ -272,12 +325,19 @@ export class WebuiAuth {
|
||||
}
|
||||
|
||||
verify(password: string): boolean {
|
||||
if (typeof password !== 'string' || password.length === 0) return false;
|
||||
if (typeof password !== 'string' || password.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const salt = Buffer.from(this.state.passwordSalt, 'hex');
|
||||
const expected = Buffer.from(this.state.passwordHash, 'hex');
|
||||
const got = hashPassword(password, salt);
|
||||
if (got.length !== expected.length) return false;
|
||||
|
||||
if (got.length !== expected.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return timingSafeEqual(got, expected);
|
||||
} catch {
|
||||
return false;
|
||||
@@ -288,16 +348,21 @@ export class WebuiAuth {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
|
||||
}
|
||||
|
||||
if (!isStrongPassword(newPassword)) {
|
||||
throw new Error('密码不符合强度要求');
|
||||
}
|
||||
|
||||
let totp = this.state.totp;
|
||||
|
||||
if (totp) {
|
||||
if (typeof currentPassword !== 'string' || currentPassword.length === 0) {
|
||||
throw new Error('修改密码需要当前密码以重新保护 2FA 密钥');
|
||||
}
|
||||
|
||||
totp = rewrapTotpSecret(currentPassword, newPassword, totp);
|
||||
}
|
||||
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(newPassword, salt);
|
||||
const next: WebuiAuthState = {
|
||||
@@ -316,9 +381,14 @@ export class WebuiAuth {
|
||||
return this.state.totp !== undefined;
|
||||
}
|
||||
|
||||
totpStatus(): { enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } {
|
||||
totpStatus():
|
||||
{ enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } {
|
||||
const totp = this.state.totp;
|
||||
if (!totp) return { enabled: false };
|
||||
|
||||
if (!totp) {
|
||||
return { enabled: false };
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: true,
|
||||
remainingRecoveryCodes: totp.recoveryCodeHashes.length,
|
||||
@@ -334,9 +404,15 @@ export class WebuiAuth {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA');
|
||||
}
|
||||
|
||||
const next: WebuiAuthState = { ...this.state, updatedAt: new Date().toISOString() };
|
||||
if (totp) next.totp = totp;
|
||||
else delete next.totp;
|
||||
|
||||
if (totp) {
|
||||
next.totp = totp;
|
||||
} else {
|
||||
delete next.totp;
|
||||
}
|
||||
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
|
||||
@@ -62,12 +62,22 @@ function isPerUinOneBotName(name: string): boolean {
|
||||
/** Resolve a file name (static or per-uin onebot pattern) to its spec, or null. */
|
||||
export function specFor(name: string): BackupFileSpec | null {
|
||||
const s = SPEC_BY_NAME.get(name);
|
||||
if (s) return s;
|
||||
if (isPerUinOneBotName(name)) return { name, binary: false, credential: true };
|
||||
|
||||
if (s) {
|
||||
return s;
|
||||
}
|
||||
|
||||
if (isPerUinOneBotName(name)) {
|
||||
return { name, binary: false, credential: true };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface BackupEntry { encoding: 'utf8' | 'base64'; data: string }
|
||||
export interface BackupEntry {
|
||||
encoding: 'utf8' | 'base64';
|
||||
data: string;
|
||||
}
|
||||
export interface Backup {
|
||||
version: number;
|
||||
app: string;
|
||||
@@ -88,16 +98,27 @@ export function buildBackup(
|
||||
const files: Record<string, BackupEntry> = {};
|
||||
const all: BackupFileSpec[] = [
|
||||
...BACKUP_FILES,
|
||||
...perUinOnebotNames.filter(isPerUinOneBotName).map((n) => ({ name: n, binary: false, credential: true })),
|
||||
...perUinOnebotNames
|
||||
.filter(isPerUinOneBotName)
|
||||
.map((n) => ({ name: n, binary: false, credential: true })),
|
||||
];
|
||||
|
||||
for (const spec of all) {
|
||||
if (spec.credential && !opts.includeCredentials) continue;
|
||||
if (spec.credential && !opts.includeCredentials) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const buf = readFile(spec.name);
|
||||
if (!buf) continue;
|
||||
|
||||
if (!buf) {
|
||||
continue;
|
||||
}
|
||||
|
||||
files[spec.name] = spec.binary
|
||||
? { encoding: 'base64', data: buf.toString('base64') }
|
||||
: { encoding: 'utf8', data: buf.toString('utf8') };
|
||||
}
|
||||
|
||||
return { version: BACKUP_VERSION, app: BACKUP_APP, createdAt, files };
|
||||
}
|
||||
|
||||
@@ -108,23 +129,58 @@ function validateBackupEntries(
|
||||
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
||||
return { ok: false, error: 'backup must be an object' };
|
||||
}
|
||||
|
||||
const b = parsed as Record<string, unknown>;
|
||||
if (b.app !== BACKUP_APP) return { ok: false, error: 'not a SnowLuma backup' };
|
||||
if (b.version !== BACKUP_VERSION) return { ok: false, error: `unsupported backup version ${String(b.version)}` };
|
||||
|
||||
if (b.app !== BACKUP_APP) {
|
||||
return { ok: false, error: 'not a SnowLuma backup' };
|
||||
}
|
||||
|
||||
if (b.version !== BACKUP_VERSION) {
|
||||
return { ok: false, error: `unsupported backup version ${String(b.version)}` };
|
||||
}
|
||||
|
||||
if (typeof b.files !== 'object' || b.files === null || Array.isArray(b.files)) {
|
||||
return { ok: false, error: 'backup.files must be an object' };
|
||||
}
|
||||
|
||||
const files = b.files as Record<string, unknown>;
|
||||
|
||||
for (const [name, entry] of Object.entries(files)) {
|
||||
const spec = specFor(name);
|
||||
if (!spec) return { ok: false, error: `unknown file in backup: ${name}` };
|
||||
if (skipEntryValidation(spec)) continue;
|
||||
if (typeof entry !== 'object' || entry === null) return { ok: false, error: `malformed entry: ${name}` };
|
||||
const e = entry as Record<string, unknown>;
|
||||
if (e.encoding !== 'utf8' && e.encoding !== 'base64') return { ok: false, error: `bad encoding for ${name}` };
|
||||
if (typeof e.data !== 'string') return { ok: false, error: `bad data for ${name}` };
|
||||
|
||||
if (!spec) {
|
||||
return { ok: false, error: `unknown file in backup: ${name}` };
|
||||
}
|
||||
return { ok: true, backup: { version: BACKUP_VERSION, app: BACKUP_APP, createdAt: typeof b.createdAt === 'string' ? b.createdAt : undefined, files: files as Record<string, BackupEntry> } };
|
||||
|
||||
if (skipEntryValidation(spec)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof entry !== 'object' || entry === null) {
|
||||
return { ok: false, error: `malformed entry: ${name}` };
|
||||
}
|
||||
|
||||
const e = entry as Record<string, unknown>;
|
||||
|
||||
if (e.encoding !== 'utf8' && e.encoding !== 'base64') {
|
||||
return { ok: false, error: `bad encoding for ${name}` };
|
||||
}
|
||||
|
||||
if (typeof e.data !== 'string') {
|
||||
return { ok: false, error: `bad data for ${name}` };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
backup: {
|
||||
version: BACKUP_VERSION,
|
||||
app: BACKUP_APP,
|
||||
createdAt: typeof b.createdAt === 'string' ? b.createdAt : undefined,
|
||||
files: files as Record<string, BackupEntry>,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface PreparedRestoreFile {
|
||||
@@ -166,9 +222,18 @@ export class RestorePreflightError extends Error {
|
||||
* Validate every selected file semantically and materialize canonical bytes
|
||||
* before the transaction is allowed to touch live configuration.
|
||||
*/
|
||||
export function prepareRestorePlan(parsed: unknown, opts: PrepareRestoreOptions): PreparedRestorePlan {
|
||||
const checked = validateBackupEntries(parsed, (spec) => spec.credential && !opts.restoreCredentials);
|
||||
if (!checked.ok) throw new RestorePreflightError('<backup>', checked.error);
|
||||
export function prepareRestorePlan(
|
||||
parsed: unknown,
|
||||
opts: PrepareRestoreOptions,
|
||||
): PreparedRestorePlan {
|
||||
const checked = validateBackupEntries(
|
||||
parsed,
|
||||
(spec) => spec.credential && !opts.restoreCredentials,
|
||||
);
|
||||
|
||||
if (!checked.ok) {
|
||||
throw new RestorePreflightError('<backup>', checked.error);
|
||||
}
|
||||
|
||||
const restore: PreparedRestoreFile[] = [];
|
||||
const skipped: string[] = [];
|
||||
@@ -178,19 +243,31 @@ export function prepareRestorePlan(parsed: unknown, opts: PrepareRestoreOptions)
|
||||
|
||||
for (const [name, entry] of Object.entries(checked.backup.files)) {
|
||||
const spec = specFor(name);
|
||||
if (!spec) throw new RestorePreflightError(name, 'file is not in the restore allowlist');
|
||||
|
||||
if (!spec) {
|
||||
throw new RestorePreflightError(name, 'file is not in the restore allowlist');
|
||||
}
|
||||
|
||||
if (spec.credential && !opts.restoreCredentials) {
|
||||
skipped.push(name);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.encoding !== (spec.binary ? 'base64' : 'utf8')) {
|
||||
throw new RestorePreflightError(name, `encoding must be ${spec.binary ? 'base64' : 'utf8'}`);
|
||||
throw new RestorePreflightError(
|
||||
name,
|
||||
`encoding must be ${spec.binary ? 'base64' : 'utf8'}`,
|
||||
);
|
||||
}
|
||||
|
||||
const decoded = decodeEntryStrict(name, entry);
|
||||
decodedBytes += decoded.length;
|
||||
|
||||
if (decodedBytes > MAX_BACKUP_DECODED_BYTES) {
|
||||
throw new RestorePreflightError(name, `selected files exceed ${String(MAX_BACKUP_DECODED_BYTES)} decoded bytes`);
|
||||
throw new RestorePreflightError(
|
||||
name,
|
||||
`selected files exceed ${String(MAX_BACKUP_DECODED_BYTES)} decoded bytes`,
|
||||
);
|
||||
}
|
||||
|
||||
selected.push({ name, data: decoded, spec });
|
||||
@@ -198,19 +275,29 @@ export function prepareRestorePlan(parsed: unknown, opts: PrepareRestoreOptions)
|
||||
|
||||
const selectedGlobal = selected.find((file) => file.name === 'onebot.json');
|
||||
const selectedPerUin = selected.filter((file) => isPerUinOneBotName(file.name));
|
||||
const selectedPerUinRaw = new Map(selectedPerUin.map((file) => [file.name, parseJson(file.name, file.data)]));
|
||||
const perUinNeedsGlobal = [...selectedPerUinRaw.values()].some((raw) => !isPlainObject(raw) || raw.mode !== 'snapshot');
|
||||
const selectedPerUinRaw = new Map(
|
||||
selectedPerUin.map((file) => [file.name, parseJson(file.name, file.data)]),
|
||||
);
|
||||
const perUinNeedsGlobal = [...selectedPerUinRaw.values()].some(
|
||||
(raw) => !isPlainObject(raw) || raw.mode !== 'snapshot',
|
||||
);
|
||||
let effectiveGlobalOneBot: unknown;
|
||||
let preparedGlobalOneBot: ReturnType<typeof prepareOneBotConfigForRestore> | null = null;
|
||||
|
||||
if (selectedGlobal) {
|
||||
if (!opts.listCurrentOneBotNames) {
|
||||
throw new RestorePreflightError('onebot.json', 'current per-account config listing is required to validate the effective overlay');
|
||||
throw new RestorePreflightError(
|
||||
'onebot.json',
|
||||
'current per-account config listing is required to validate the effective overlay',
|
||||
);
|
||||
}
|
||||
|
||||
const raw = parseJson(selectedGlobal.name, selectedGlobal.data);
|
||||
preparedGlobalOneBot = prepareOneBotOrThrow(selectedGlobal.name, raw, 'global');
|
||||
effectiveGlobalOneBot = preparedGlobalOneBot.value;
|
||||
} else if (perUinNeedsGlobal) {
|
||||
const current = readCurrentForPreflight(opts, 'onebot.json');
|
||||
|
||||
if (current) {
|
||||
const raw = parseJson('onebot.json', current);
|
||||
effectiveGlobalOneBot = prepareOneBotOrThrow('onebot.json', raw, 'global').value;
|
||||
@@ -219,6 +306,7 @@ export function prepareRestorePlan(parsed: unknown, opts: PrepareRestoreOptions)
|
||||
|
||||
for (const { name, data, spec } of selected) {
|
||||
let prepared: { data: Buffer; migratedFields: string[] };
|
||||
|
||||
if (name === 'onebot.json') {
|
||||
const global = preparedGlobalOneBot!;
|
||||
prepared = { data: serializeJson(global.value), migratedFields: global.migratedFields };
|
||||
@@ -229,7 +317,9 @@ export function prepareRestorePlan(parsed: unknown, opts: PrepareRestoreOptions)
|
||||
} else {
|
||||
prepared = prepareFile(name, data);
|
||||
}
|
||||
|
||||
restore.push({ name, data: prepared.data, mode: spec.credential ? 0o600 : 0o644 });
|
||||
|
||||
if (prepared.migratedFields.length > 0) {
|
||||
migrated.push({ name, fields: [...prepared.migratedFields].sort() });
|
||||
}
|
||||
@@ -238,15 +328,28 @@ export function prepareRestorePlan(parsed: unknown, opts: PrepareRestoreOptions)
|
||||
if (selectedGlobal) {
|
||||
const selectedNames = new Set(selected.map((file) => file.name));
|
||||
let currentNames: string[];
|
||||
|
||||
try {
|
||||
currentNames = opts.listCurrentOneBotNames!();
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError('onebot.json', `failed to list current per-account configs: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
||||
throw new RestorePreflightError(
|
||||
'onebot.json',
|
||||
`failed to list current per-account configs: ${error instanceof Error ? error.message : String(error)}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
|
||||
for (const name of currentNames) {
|
||||
if (!isPerUinOneBotName(name) || selectedNames.has(name)) continue;
|
||||
if (!isPerUinOneBotName(name) || selectedNames.has(name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const current = readCurrentForPreflight(opts, name);
|
||||
if (!current) continue;
|
||||
|
||||
if (!current) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const raw = parseJson(name, current);
|
||||
prepareOneBotOrThrow(name, raw, 'per-uin', effectiveGlobalOneBot);
|
||||
}
|
||||
@@ -258,18 +361,29 @@ export function prepareRestorePlan(parsed: unknown, opts: PrepareRestoreOptions)
|
||||
}
|
||||
|
||||
function decodeEntryStrict(name: string, entry: BackupEntry): Buffer {
|
||||
if (entry.encoding === 'utf8') return Buffer.from(entry.data, 'utf8');
|
||||
if (entry.encoding === 'utf8') {
|
||||
return Buffer.from(entry.data, 'utf8');
|
||||
}
|
||||
|
||||
if (!isCanonicalBase64(entry.data)) {
|
||||
throw new RestorePreflightError(name, 'data is not canonical base64');
|
||||
}
|
||||
|
||||
return Buffer.from(entry.data, 'base64');
|
||||
}
|
||||
|
||||
function isCanonicalBase64(value: string): boolean {
|
||||
if (value.length === 0) return true;
|
||||
if (value.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
|
||||
if (value.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (
|
||||
value.length % 4 !== 0 ||
|
||||
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Buffer.from(value, 'base64').toString('base64') === value;
|
||||
}
|
||||
|
||||
@@ -284,27 +398,45 @@ function prepareFile(name: string, data: Buffer): { data: Buffer; migratedFields
|
||||
return prepareNormalizedJson(name, data, normalizeNotificationsConfig);
|
||||
case 'snowluma.json':
|
||||
return prepareGlobalSettingsJson(name, data);
|
||||
|
||||
case 'webui.json': {
|
||||
const value = parseJson(name, data);
|
||||
const canonical = prepareWebuiAuthStateForRestore(value);
|
||||
return { data: serializeJson(canonical), migratedFields: [] };
|
||||
}
|
||||
|
||||
case 'ui-assets/background':
|
||||
if (data.length > MAX_BACKGROUND_BYTES) {
|
||||
throw new Error(`image exceeds ${String(MAX_BACKGROUND_BYTES)} bytes`);
|
||||
}
|
||||
if (!sniffImageMime(data)) throw new Error('image must be PNG, JPEG, or WebP');
|
||||
|
||||
if (!sniffImageMime(data)) {
|
||||
throw new Error('image must be PNG, JPEG, or WebP');
|
||||
}
|
||||
|
||||
return { data, migratedFields: [] };
|
||||
case 'cert.pem':
|
||||
case 'key.pem':
|
||||
if (!data.toString('utf8').trim()) throw new Error('PEM file must not be empty');
|
||||
if (!data.toString('utf8').trim()) {
|
||||
throw new Error('PEM file must not be empty');
|
||||
}
|
||||
|
||||
return { data, migratedFields: [] };
|
||||
default:
|
||||
throw new Error('file is not in the restore allowlist');
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof RestorePreflightError) throw error;
|
||||
throw new RestorePreflightError(name, error instanceof Error ? error.message : String(error), { cause: error });
|
||||
if (error instanceof RestorePreflightError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new RestorePreflightError(
|
||||
name,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
{
|
||||
cause: error,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -317,7 +449,13 @@ function prepareOneBotOrThrow(
|
||||
try {
|
||||
return prepareOneBotConfigForRestore(value, scope, inheritedGlobal);
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError(name, error instanceof Error ? error.message : String(error), { cause: error });
|
||||
throw new RestorePreflightError(
|
||||
name,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
{
|
||||
cause: error,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,7 +463,11 @@ function readCurrentForPreflight(opts: PrepareRestoreOptions, name: string): Buf
|
||||
try {
|
||||
return opts.readCurrent(name);
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
||||
throw new RestorePreflightError(
|
||||
name,
|
||||
`failed to read current file: ${error instanceof Error ? error.message : String(error)}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,7 +482,11 @@ function parseJson(name: string, data: Buffer): unknown {
|
||||
}
|
||||
}
|
||||
|
||||
function prepareNormalizedJson<T>(name: string, data: Buffer, normalize: (value: unknown) => T): {
|
||||
function prepareNormalizedJson<T>(
|
||||
name: string,
|
||||
data: Buffer,
|
||||
normalize: (value: unknown) => T,
|
||||
): {
|
||||
data: Buffer;
|
||||
migratedFields: string[];
|
||||
} {
|
||||
@@ -351,30 +497,42 @@ function prepareNormalizedJson<T>(name: string, data: Buffer, normalize: (value:
|
||||
return { data: serializeJson(canonical), migratedFields };
|
||||
}
|
||||
|
||||
function prepareRuntimeJson(name: string, data: Buffer): {
|
||||
function prepareRuntimeJson(
|
||||
name: string,
|
||||
data: Buffer,
|
||||
): {
|
||||
data: Buffer;
|
||||
migratedFields: string[];
|
||||
} {
|
||||
const prepared = prepareNormalizedJson(name, data, normalizeRuntimeConfig);
|
||||
const runtime = JSON.parse(prepared.data.toString('utf8')) as ReturnType<typeof normalizeRuntimeConfig>;
|
||||
const runtime = JSON.parse(prepared.data.toString('utf8')) as ReturnType<
|
||||
typeof normalizeRuntimeConfig
|
||||
>;
|
||||
|
||||
if (!runtime.webuiHost || !isValidBindHost(runtime.webuiHost)) {
|
||||
throw new RestorePreflightError(name, '$.webuiHost is not a valid TCP bind host');
|
||||
}
|
||||
|
||||
return prepared;
|
||||
}
|
||||
|
||||
function prepareGlobalSettingsJson(name: string, data: Buffer): {
|
||||
function prepareGlobalSettingsJson(
|
||||
name: string,
|
||||
data: Buffer,
|
||||
): {
|
||||
data: Buffer;
|
||||
migratedFields: string[];
|
||||
} {
|
||||
const raw = parseJson(name, data);
|
||||
const normalized = normalizeGlobalSettings(raw);
|
||||
const canonical: Record<string, unknown> = { rkey: normalized.rkey };
|
||||
|
||||
// Missing is the existing one-shot migration sentinel: startup scans legacy
|
||||
// onebot*.json only until snowluma.json first carries this key.
|
||||
if (isPlainObject(raw) && Object.prototype.hasOwnProperty.call(raw, 'musicSignUrl')) {
|
||||
canonical.musicSignUrl = normalized.musicSignUrl;
|
||||
}
|
||||
|
||||
const migratedFields: string[] = [];
|
||||
assertNoLossyNormalization(name, raw, canonical, '$', migratedFields);
|
||||
return { data: serializeJson(canonical), migratedFields };
|
||||
@@ -388,57 +546,96 @@ function assertNoLossyNormalization(
|
||||
additions: string[],
|
||||
): void {
|
||||
if (isPlainObject(raw)) {
|
||||
if (!isPlainObject(canonical)) throw new RestorePreflightError(name, `${at} has an invalid type`);
|
||||
if (!isPlainObject(canonical)) {
|
||||
throw new RestorePreflightError(name, `${at} has an invalid type`);
|
||||
}
|
||||
|
||||
for (const [key, rawValue] of Object.entries(raw)) {
|
||||
const child = `${at}.${key}`;
|
||||
|
||||
if (!Object.prototype.hasOwnProperty.call(canonical, key)) {
|
||||
throw new RestorePreflightError(name, `${child} is unsupported or would be discarded`);
|
||||
throw new RestorePreflightError(
|
||||
name,
|
||||
`${child} is unsupported or would be discarded`,
|
||||
);
|
||||
}
|
||||
|
||||
assertNoLossyNormalization(name, rawValue, canonical[key], child, additions);
|
||||
}
|
||||
|
||||
for (const key of Object.keys(canonical)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(raw, key)) additions.push(`${at}.${key}`);
|
||||
if (!Object.prototype.hasOwnProperty.call(raw, key)) {
|
||||
additions.push(`${at}.${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(raw)) {
|
||||
if (!Array.isArray(canonical) || raw.length !== canonical.length) {
|
||||
throw new RestorePreflightError(name, `${at} contains an invalid, duplicate, or discarded item`);
|
||||
throw new RestorePreflightError(
|
||||
name,
|
||||
`${at} contains an invalid, duplicate, or discarded item`,
|
||||
);
|
||||
}
|
||||
|
||||
raw.forEach((value, index) => {
|
||||
assertNoLossyNormalization(name, value, canonical[index], `${at}[${String(index)}]`, additions);
|
||||
assertNoLossyNormalization(
|
||||
name,
|
||||
value,
|
||||
canonical[index],
|
||||
`${at}[${String(index)}]`,
|
||||
additions,
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Object.is(raw, canonical)) {
|
||||
if (isKnownLosslessScalarCoercion(name, at, raw, canonical)) {
|
||||
additions.push(at);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new RestorePreflightError(name, `${at} is invalid or would be changed`);
|
||||
}
|
||||
}
|
||||
|
||||
function isKnownLosslessScalarCoercion(name: string, at: string, raw: unknown, canonical: unknown): boolean {
|
||||
function isKnownLosslessScalarCoercion(
|
||||
name: string,
|
||||
at: string,
|
||||
raw: unknown,
|
||||
canonical: unknown,
|
||||
): boolean {
|
||||
if (typeof raw === 'string' && typeof canonical === 'string' && raw.trim() === canonical) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof raw === 'string' && typeof canonical === 'number') {
|
||||
const parsed = Number(raw.trim());
|
||||
return raw.trim().length > 0 && Number.isFinite(parsed) && Object.is(parsed, canonical);
|
||||
}
|
||||
|
||||
if (
|
||||
name === 'runtime.json' &&
|
||||
(at === '$.hookAutoLoad' || at === '$.webuiTls.enabled') &&
|
||||
typeof canonical === 'boolean'
|
||||
) {
|
||||
if (raw === 1 || raw === 0) return canonical === (raw === 1);
|
||||
if (typeof raw !== 'string') return false;
|
||||
if (raw === 1 || raw === 0) {
|
||||
return canonical === (raw === 1);
|
||||
}
|
||||
|
||||
if (typeof raw !== 'string') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const token = raw.trim().toLowerCase();
|
||||
const truthy = new Set(['true', '1', 'yes', 'on']);
|
||||
const falsy = new Set(['false', '0', 'no', 'off', '']);
|
||||
return (canonical && truthy.has(token)) || (!canonical && falsy.has(token));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -454,77 +651,148 @@ function validateEffectiveTls(restore: PreparedRestoreFile[], opts: PrepareResto
|
||||
const byName = new Map(restore.map((file) => [file.name, file.data]));
|
||||
const pairTouched = byName.has('cert.pem') || byName.has('key.pem');
|
||||
const tlsRelated = pairTouched || byName.has('runtime.json');
|
||||
if (!tlsRelated) return;
|
||||
|
||||
if (!tlsRelated) {
|
||||
return;
|
||||
}
|
||||
|
||||
const readEffective = (name: string): Buffer | null => {
|
||||
const prepared = byName.get(name);
|
||||
if (prepared) return prepared;
|
||||
|
||||
if (prepared) {
|
||||
return prepared;
|
||||
}
|
||||
|
||||
try {
|
||||
return opts.readCurrent(name);
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
||||
throw new RestorePreflightError(
|
||||
name,
|
||||
`failed to read current file: ${error instanceof Error ? error.message : String(error)}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const runtime = readEffective('runtime.json');
|
||||
let tlsEnabled = false;
|
||||
|
||||
if (runtime) {
|
||||
try {
|
||||
tlsEnabled = normalizeRuntimeConfig(JSON.parse(runtime.toString('utf8')) as unknown).webuiTls?.enabled === true;
|
||||
tlsEnabled =
|
||||
normalizeRuntimeConfig(JSON.parse(runtime.toString('utf8')) as unknown).webuiTls
|
||||
?.enabled === true;
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError('runtime.json', 'effective runtime config is invalid JSON', { cause: error });
|
||||
throw new RestorePreflightError(
|
||||
'runtime.json',
|
||||
'effective runtime config is invalid JSON',
|
||||
{
|
||||
cause: error,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!tlsEnabled && !pairTouched) return;
|
||||
if (!tlsEnabled && !pairTouched) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cert = readEffective('cert.pem');
|
||||
const key = readEffective('key.pem');
|
||||
|
||||
if (cert && key) {
|
||||
const valid = validateTlsPair(cert, key);
|
||||
if (!valid.ok) throw new RestorePreflightError('cert.pem + key.pem', valid.reason ?? 'TLS pair is invalid');
|
||||
|
||||
if (!valid.ok) {
|
||||
throw new RestorePreflightError(
|
||||
'cert.pem + key.pem',
|
||||
valid.reason ?? 'TLS pair is invalid',
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (tlsEnabled) {
|
||||
throw new RestorePreflightError('cert.pem + key.pem', 'TLS is enabled but the effective certificate/private-key pair is incomplete');
|
||||
throw new RestorePreflightError(
|
||||
'cert.pem + key.pem',
|
||||
'TLS is enabled but the effective certificate/private-key pair is incomplete',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function validateEffectiveUi(restore: PreparedRestoreFile[], opts: PrepareRestoreOptions): void {
|
||||
const byName = new Map(restore.map((file) => [file.name, file.data]));
|
||||
if (!byName.has('ui.json') && !byName.has('ui-assets/background')) return;
|
||||
|
||||
if (!byName.has('ui.json') && !byName.has('ui-assets/background')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const readEffective = (name: string): Buffer | null => {
|
||||
const prepared = byName.get(name);
|
||||
if (prepared) return prepared;
|
||||
|
||||
if (prepared) {
|
||||
return prepared;
|
||||
}
|
||||
|
||||
try {
|
||||
return opts.readCurrent(name);
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
||||
throw new RestorePreflightError(
|
||||
name,
|
||||
`failed to read current file: ${error instanceof Error ? error.message : String(error)}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const uiBytes = readEffective('ui.json');
|
||||
if (!uiBytes) return;
|
||||
|
||||
if (!uiBytes) {
|
||||
return;
|
||||
}
|
||||
|
||||
let ui;
|
||||
|
||||
try {
|
||||
ui = normalizeStoredUiConfig(JSON.parse(uiBytes.toString('utf8')) as unknown);
|
||||
} catch (error) {
|
||||
throw new RestorePreflightError('ui.json', 'effective UI config is invalid JSON', { cause: error });
|
||||
throw new RestorePreflightError('ui.json', 'effective UI config is invalid JSON', {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const background = ui.appearance.background;
|
||||
if (!background.hasImage) return;
|
||||
|
||||
if (!background.hasImage) {
|
||||
return;
|
||||
}
|
||||
|
||||
const image = readEffective('ui-assets/background');
|
||||
|
||||
if (!image) {
|
||||
throw new RestorePreflightError('ui.json + ui-assets/background', 'background metadata says an image exists, but the effective image is missing');
|
||||
throw new RestorePreflightError(
|
||||
'ui.json + ui-assets/background',
|
||||
'background metadata says an image exists, but the effective image is missing',
|
||||
);
|
||||
}
|
||||
|
||||
if (image.length > MAX_BACKGROUND_BYTES) {
|
||||
throw new RestorePreflightError('ui.json + ui-assets/background', `effective background exceeds ${String(MAX_BACKGROUND_BYTES)} bytes`);
|
||||
throw new RestorePreflightError(
|
||||
'ui.json + ui-assets/background',
|
||||
`effective background exceeds ${String(MAX_BACKGROUND_BYTES)} bytes`,
|
||||
);
|
||||
}
|
||||
|
||||
const mime = sniffImageMime(image);
|
||||
|
||||
if (!mime) {
|
||||
throw new RestorePreflightError('ui.json + ui-assets/background', 'effective background is not PNG, JPEG, or WebP');
|
||||
throw new RestorePreflightError(
|
||||
'ui.json + ui-assets/background',
|
||||
'effective background is not PNG, JPEG, or WebP',
|
||||
);
|
||||
}
|
||||
|
||||
if (mime !== background.imageMime) {
|
||||
throw new RestorePreflightError(
|
||||
'ui.json + ui-assets/background',
|
||||
|
||||
@@ -9,43 +9,75 @@ export type TrustProxyMode =
|
||||
|
||||
export function parseTrustProxy(raw: string | undefined): TrustProxyMode {
|
||||
const value = raw?.trim().toLowerCase() ?? '';
|
||||
if (!value) return { kind: 'none' };
|
||||
if (value === '1' || value === 'true' || value === 'all') return { kind: 'all' };
|
||||
if (value === 'loopback') return { kind: 'loopback' };
|
||||
|
||||
if (!value) {
|
||||
return { kind: 'none' };
|
||||
}
|
||||
|
||||
if (value === '1' || value === 'true' || value === 'all') {
|
||||
return { kind: 'all' };
|
||||
}
|
||||
|
||||
if (value === 'loopback') {
|
||||
return { kind: 'loopback' };
|
||||
}
|
||||
|
||||
const ips = new Set(
|
||||
value.split(',').map((s) => s.trim()).filter(Boolean),
|
||||
value
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
);
|
||||
if (ips.size === 0) return { kind: 'none' };
|
||||
|
||||
if (ips.size === 0) {
|
||||
return { kind: 'none' };
|
||||
}
|
||||
|
||||
return { kind: 'ip-list', ips };
|
||||
}
|
||||
|
||||
export function describeTrustProxy(mode: TrustProxyMode): string {
|
||||
switch (mode.kind) {
|
||||
case 'none': return 'socket peer (default)';
|
||||
case 'all': return 'X-Real-IP / X-Forwarded-For from any peer';
|
||||
case 'loopback': return 'X-Real-IP / X-Forwarded-For when socket peer is loopback';
|
||||
case 'ip-list': return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`;
|
||||
case 'none':
|
||||
return 'socket peer (default)';
|
||||
case 'all':
|
||||
return 'X-Real-IP / X-Forwarded-For from any peer';
|
||||
case 'loopback':
|
||||
return 'X-Real-IP / X-Forwarded-For when socket peer is loopback';
|
||||
case 'ip-list':
|
||||
return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`;
|
||||
}
|
||||
}
|
||||
|
||||
export function isLoopbackClientIp(ip: string): boolean {
|
||||
const normalized = ip.trim().toLowerCase();
|
||||
if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') return true;
|
||||
|
||||
if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (normalized.startsWith('::ffff:')) {
|
||||
return isLoopbackClientIp(normalized.slice('::ffff:'.length));
|
||||
}
|
||||
|
||||
const octets = normalized.split('.');
|
||||
return octets.length === 4
|
||||
&& octets[0] === '127'
|
||||
&& octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
|
||||
return (
|
||||
octets.length === 4 &&
|
||||
octets[0] === '127' &&
|
||||
octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255)
|
||||
);
|
||||
}
|
||||
|
||||
function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
|
||||
switch (mode.kind) {
|
||||
case 'none': return false;
|
||||
case 'all': return true;
|
||||
case 'loopback': return isLoopbackClientIp(socketIp);
|
||||
case 'ip-list': return mode.ips.has(socketIp);
|
||||
case 'none':
|
||||
return false;
|
||||
case 'all':
|
||||
return true;
|
||||
case 'loopback':
|
||||
return isLoopbackClientIp(socketIp);
|
||||
case 'ip-list':
|
||||
return mode.ips.has(socketIp);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,22 +88,37 @@ export function pickClientIp(
|
||||
fallbackIp = '127.0.0.1',
|
||||
): string {
|
||||
let socketIp: string;
|
||||
|
||||
try {
|
||||
socketIp = getSocketIp();
|
||||
} catch {
|
||||
return fallbackIp;
|
||||
}
|
||||
if (!socketIp) return fallbackIp;
|
||||
|
||||
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
|
||||
if (!socketIp) {
|
||||
return fallbackIp;
|
||||
}
|
||||
|
||||
if (!shouldTrustHeaders(mode, socketIp)) {
|
||||
return socketIp;
|
||||
}
|
||||
|
||||
const realIp = c.req.header('x-real-ip')?.trim();
|
||||
if (realIp) return realIp;
|
||||
|
||||
if (realIp) {
|
||||
return realIp;
|
||||
}
|
||||
|
||||
const xff = c.req.header('x-forwarded-for');
|
||||
|
||||
if (xff) {
|
||||
const first = xff.split(',')[0].trim();
|
||||
if (first) return first;
|
||||
|
||||
if (first) {
|
||||
return first;
|
||||
}
|
||||
}
|
||||
|
||||
return socketIp;
|
||||
}
|
||||
|
||||
@@ -80,10 +127,6 @@ export function makeClientIpResolver(
|
||||
mode: TrustProxyMode,
|
||||
fallbackIp = '127.0.0.1',
|
||||
): (c: Context) => string {
|
||||
return (c) => pickClientIp(
|
||||
c,
|
||||
mode,
|
||||
() => getConnInfo(c).remote.address ?? fallbackIp,
|
||||
fallbackIp,
|
||||
);
|
||||
return (c) =>
|
||||
pickClientIp(c, mode, () => getConnInfo(c).remote.address ?? fallbackIp, fallbackIp);
|
||||
}
|
||||
@@ -11,10 +11,7 @@
|
||||
* something update.
|
||||
*/
|
||||
|
||||
import {
|
||||
createLogger,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { createLogger, runWithTraceRequest } from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import type { StateBus } from './state-bus';
|
||||
|
||||
@@ -54,8 +51,12 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
|
||||
let warnedProjectorThrew = false;
|
||||
|
||||
const tick = (): void => {
|
||||
if (disposed) return;
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
let snap: unknown;
|
||||
|
||||
try {
|
||||
snap = opts.getSnapshot();
|
||||
} catch (err) {
|
||||
@@ -71,12 +72,15 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Snapshot read failed (e.g. mid-shutdown). Skip this tick; the
|
||||
// next one will retry. Don't reset the baseline so we don't
|
||||
// spuriously republish when the snapshot starts working again.
|
||||
return;
|
||||
}
|
||||
|
||||
let comparable: unknown;
|
||||
|
||||
try {
|
||||
comparable = opts.pickComparable ? opts.pickComparable(snap) : snap;
|
||||
} catch (err) {
|
||||
@@ -102,9 +106,12 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const serialized = JSON.stringify(comparable);
|
||||
|
||||
if (!haveBaseline) {
|
||||
// First successful observation. The SSE handler's sendAllInitial
|
||||
// already shipped a `connections` frame to every connected client
|
||||
@@ -114,14 +121,15 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
|
||||
haveBaseline = true;
|
||||
return;
|
||||
}
|
||||
if (serialized === lastSerialized) return;
|
||||
|
||||
if (serialized === lastSerialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastSerialized = serialized;
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace(() => [
|
||||
'connection_diff_start snapshot=%s',
|
||||
renderParamsVerbose(snap),
|
||||
]);
|
||||
log.trace(() => ['connection_diff_start snapshot=%s', renderParamsVerbose(snap)]);
|
||||
log.trace('connection_diff_branch branch=publish resource=connections');
|
||||
opts.bus.publish('connections');
|
||||
log.trace(
|
||||
@@ -140,7 +148,10 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
|
||||
|
||||
return {
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
disposed = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { AccountConnections } from '@snowluma/onebot/manager';
|
||||
|
||||
export function comparableConnectionSnapshot(snapshot: unknown): unknown {
|
||||
if (!Array.isArray(snapshot)) return snapshot;
|
||||
if (!Array.isArray(snapshot)) {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
return (snapshot as AccountConnections[]).map((account) => ({
|
||||
uin: account.uin,
|
||||
nickname: account.nickname,
|
||||
|
||||
@@ -63,15 +63,21 @@ export interface AgreementsPayload {
|
||||
}
|
||||
|
||||
function parseEnvironmentAcceptance(name: string, raw: string | undefined): boolean {
|
||||
if (raw === undefined || raw.trim() === '') return false;
|
||||
if (raw === undefined || raw.trim() === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === '1' || normalized === 'true') return true;
|
||||
if (normalized === '0' || normalized === 'false') return false;
|
||||
|
||||
throw new Error(
|
||||
`${name} must be one of: 1, true, 0, false; received ${JSON.stringify(raw)}`,
|
||||
);
|
||||
if (normalized === '1' || normalized === 'true') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (normalized === '0' || normalized === 'false') {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw new Error(`${name} must be one of: 1, true, 0, false; received ${JSON.stringify(raw)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -107,13 +113,17 @@ function resolveAgreementFile(file: string): string | null {
|
||||
path.resolve(process.cwd(), file), // started from repo root
|
||||
path.resolve(process.cwd(), '..', '..', file), // dev cwd = packages/core
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (fs.existsSync(candidate)) return candidate;
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
} catch {
|
||||
/* unreadable candidate, try next */
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -140,12 +150,14 @@ export function parseAgreementMeta(text: string): {
|
||||
*/
|
||||
export function computeAgreementsVersion(docs: { id: string; text: string }[]): string {
|
||||
const hash = createHash('sha256');
|
||||
|
||||
for (const doc of docs) {
|
||||
hash.update(doc.id);
|
||||
hash.update('\0');
|
||||
hash.update(doc.text);
|
||||
hash.update('\0');
|
||||
}
|
||||
|
||||
return hash.digest('hex').slice(0, 16);
|
||||
}
|
||||
|
||||
@@ -153,21 +165,39 @@ let cache: { docs: AgreementDoc[]; version: string } | null = null;
|
||||
|
||||
/** Load + parse both agreements and compute the version. Cached per process. */
|
||||
export function loadAgreements(): { docs: AgreementDoc[]; version: string } {
|
||||
if (cache) return cache;
|
||||
if (cache) {
|
||||
return cache;
|
||||
}
|
||||
|
||||
const docs: AgreementDoc[] = AGREEMENT_FILES.map(({ id, file }) => {
|
||||
const resolved = resolveAgreementFile(file);
|
||||
let text = '';
|
||||
|
||||
if (resolved) {
|
||||
try {
|
||||
text = fs.readFileSync(resolved, 'utf8');
|
||||
} catch (err) {
|
||||
log.warn('failed to read %s: %s', file, err instanceof Error ? err.message : String(err));
|
||||
log.warn(
|
||||
'failed to read %s: %s',
|
||||
file,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
log.warn('agreement file not found (looked for %s near the bundle and repo root)', file);
|
||||
log.warn(
|
||||
'agreement file not found (looked for %s near the bundle and repo root)',
|
||||
file,
|
||||
);
|
||||
}
|
||||
|
||||
const meta = parseAgreementMeta(text);
|
||||
return { id, title: meta.title, declaredVersion: meta.declaredVersion, effectiveDate: meta.effectiveDate, text };
|
||||
return {
|
||||
id,
|
||||
title: meta.title,
|
||||
declaredVersion: meta.declaredVersion,
|
||||
effectiveDate: meta.effectiveDate,
|
||||
text,
|
||||
};
|
||||
});
|
||||
cache = { docs, version: computeAgreementsVersion(docs) };
|
||||
return cache;
|
||||
@@ -180,18 +210,29 @@ function ensureConfigDir(): void {
|
||||
}
|
||||
|
||||
function isConsentRecord(value: unknown): value is ConsentRecord {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
if (!value || typeof value !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const v = value as Record<string, unknown>;
|
||||
return typeof v.version === 'string' && v.version.length > 0 && typeof v.acceptedAt === 'string';
|
||||
return (
|
||||
typeof v.version === 'string' && v.version.length > 0 && typeof v.acceptedAt === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
export function loadConsentRecord(): ConsentRecord | null {
|
||||
try {
|
||||
if (!fs.existsSync(CONSENT_CONFIG_PATH)) return null;
|
||||
if (!fs.existsSync(CONSENT_CONFIG_PATH)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(fs.readFileSync(CONSENT_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isConsentRecord(parsed) ? parsed : null;
|
||||
} catch (err) {
|
||||
log.warn('consent.json unreadable, treating as no consent: %s', err instanceof Error ? err.message : String(err));
|
||||
log.warn(
|
||||
'consent.json unreadable, treating as no consent: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -212,11 +253,17 @@ export function recordConsent(version: string): ConsentRecord {
|
||||
|
||||
/** True when neither environment nor stored consent covers the current agreements. */
|
||||
export function isConsentRequired(env: ConsentEnvironment = process.env): boolean {
|
||||
if (resolveEnvironmentConsent(env).accepted) return false;
|
||||
if (resolveEnvironmentConsent(env).accepted) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const { docs, version } = loadAgreements();
|
||||
const hasContent = docs.some((d) => d.text.trim().length > 0);
|
||||
if (!hasContent) return false; // fail open: never brick the panel on a broken bundle
|
||||
|
||||
if (!hasContent) {
|
||||
return false;
|
||||
} // fail open: never brick the panel on a broken bundle
|
||||
|
||||
return loadConsentRecord()?.version !== version;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,13 +16,22 @@ export interface FramePusherOptions {
|
||||
export function createFramePusher(opts: FramePusherOptions): (payload: unknown) => void {
|
||||
const encode = opts.encode ?? ((s: string) => new TextEncoder().encode(s));
|
||||
let dropped = 0;
|
||||
|
||||
return (payload: unknown): void => {
|
||||
const d = opts.desiredSize();
|
||||
if (d !== null && d <= 0) { dropped += 1; return; }
|
||||
|
||||
if (d !== null && d <= 0) {
|
||||
dropped += 1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (dropped > 0) {
|
||||
opts.enqueue(encode(`data: ${JSON.stringify({ kind: 'dropped', count: dropped })}\n\n`));
|
||||
opts.enqueue(
|
||||
encode(`data: ${JSON.stringify({ kind: 'dropped', count: dropped })}\n\n`),
|
||||
);
|
||||
dropped = 0;
|
||||
}
|
||||
|
||||
opts.enqueue(encode(`data: ${JSON.stringify(payload)}\n\n`));
|
||||
};
|
||||
}
|
||||
@@ -52,9 +52,11 @@ export function uploadDestPath(safeName: string): string {
|
||||
const id = randomBytes(12).toString('hex');
|
||||
const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`);
|
||||
const rel = path.relative(DEBUG_UPLOAD_DIR, dest);
|
||||
|
||||
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
|
||||
throw new Error('invalid upload path');
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
@@ -67,7 +69,10 @@ export async function streamUploadToDisk(
|
||||
filename: string | undefined,
|
||||
opts: { maxBytes?: number } = {},
|
||||
): Promise<{ path: string; size: number }> {
|
||||
if (!body) throw new Error('empty body');
|
||||
if (!body) {
|
||||
throw new Error('empty body');
|
||||
}
|
||||
|
||||
const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES;
|
||||
await mkdir(DEBUG_UPLOAD_DIR, { recursive: true });
|
||||
void sweepOldUploads(); // fire-and-forget TTL cleanup
|
||||
@@ -81,25 +86,50 @@ export async function streamUploadToDisk(
|
||||
// + leaked fd). So turn it into a rejection and race it into every await; the
|
||||
// catch below then destroys + unlinks the partial.
|
||||
const errored = new Promise<never>((_, rej) => out.once('error', rej));
|
||||
errored.catch(() => { /* swallow a late error after success (still raced below) */ });
|
||||
errored.catch(() => {
|
||||
/* swallow a late error after success (still raced below) */
|
||||
});
|
||||
let size = 0;
|
||||
|
||||
try {
|
||||
const reader = body.getReader();
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await Promise.race([errored, reader.read()]);
|
||||
if (done) break;
|
||||
if (!value || value.byteLength === 0) continue;
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (!value || value.byteLength === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const offset = size;
|
||||
size += value.byteLength;
|
||||
traceWebuiMutationRequestChunk(value, offset);
|
||||
if (size > maxBytes) throw new Error('上传超出大小上限');
|
||||
|
||||
if (size > maxBytes) {
|
||||
throw new Error('上传超出大小上限');
|
||||
}
|
||||
|
||||
// Respect the write stream's backpressure (but never hang on an error).
|
||||
if (!out.write(value)) {
|
||||
await Promise.race([errored, new Promise<void>((res) => out.once('drain', res))]);
|
||||
}
|
||||
}
|
||||
await Promise.race([errored, new Promise<void>((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())))]);
|
||||
if (size === 0) throw new Error('empty body');
|
||||
|
||||
await Promise.race([
|
||||
errored,
|
||||
new Promise<void>((res, rej) =>
|
||||
out.end((err?: Error | null) => (err ? rej(err) : res())),
|
||||
),
|
||||
]);
|
||||
|
||||
if (size === 0) {
|
||||
throw new Error('empty body');
|
||||
}
|
||||
|
||||
return { path: dest, size };
|
||||
} catch (err) {
|
||||
// Wait for the stream to fully close BEFORE unlinking: createWriteStream
|
||||
@@ -107,8 +137,14 @@ export async function streamUploadToDisk(
|
||||
// file even exists on disk — then the late open would re-create it and leak
|
||||
// the partial. 'close' guarantees the fd is settled and no more writes land.
|
||||
out.destroy();
|
||||
if (!out.closed) await new Promise<void>((res) => out.once('close', () => res()));
|
||||
await rm(dest, { force: true }).catch(() => { /* best-effort */ });
|
||||
|
||||
if (!out.closed) {
|
||||
await new Promise<void>((res) => out.once('close', () => res()));
|
||||
}
|
||||
|
||||
await rm(dest, { force: true }).catch(() => {
|
||||
/* best-effort */
|
||||
});
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -116,21 +152,29 @@ export async function streamUploadToDisk(
|
||||
/** Remove upload temp files older than the TTL. Best-effort; never throws. */
|
||||
export async function sweepOldUploads(now: number = Date.now()): Promise<number> {
|
||||
let removed = 0;
|
||||
|
||||
try {
|
||||
const names = await readdir(DEBUG_UPLOAD_DIR);
|
||||
await Promise.all(
|
||||
names.map(async (n) => {
|
||||
const p = path.join(DEBUG_UPLOAD_DIR, n);
|
||||
|
||||
try {
|
||||
const s = await stat(p);
|
||||
|
||||
if (now - s.mtimeMs > UPLOAD_TTL_MS) {
|
||||
await rm(p, { force: true, recursive: true });
|
||||
removed += 1;
|
||||
}
|
||||
} catch { /* racing cleanup / vanished file */ }
|
||||
} catch {
|
||||
/* racing cleanup / vanished file */
|
||||
}
|
||||
}),
|
||||
);
|
||||
} catch { /* dir absent yet */ }
|
||||
} catch {
|
||||
/* dir absent yet */
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
@@ -163,19 +207,31 @@ export function buildStreamInvokeResponse(
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
let closed = false;
|
||||
const onAbort = () => { closed = true; };
|
||||
|
||||
const onAbort = () => {
|
||||
closed = true;
|
||||
};
|
||||
|
||||
signal.addEventListener('abort', onAbort);
|
||||
const isAlive = () => !closed && !signal.aborted;
|
||||
|
||||
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;
|
||||
|
||||
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');
|
||||
|
||||
if (!isAlive()) {
|
||||
throw new Error('stream transport closed');
|
||||
}
|
||||
|
||||
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
||||
};
|
||||
|
||||
@@ -184,17 +240,33 @@ export function buildStreamInvokeResponse(
|
||||
} catch (err) {
|
||||
if (isAlive()) {
|
||||
const msg = err instanceof Error ? err.message : 'stream error';
|
||||
|
||||
try {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`));
|
||||
} catch { /* controller already torn down */ }
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`,
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
/* controller already torn down */
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
try { controller.close(); } catch { /* already closed */ }
|
||||
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
Connection: 'keep-alive',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,17 +1,24 @@
|
||||
import { isIP } from 'node:net';
|
||||
|
||||
export type ListenerExposureCheck =
|
||||
| { ok: true }
|
||||
| { ok: false; code: 'invalid-bind-host' | 'tls-pair-required' };
|
||||
{ ok: true } | { ok: false; code: 'invalid-bind-host' | 'tls-pair-required' };
|
||||
|
||||
/** TCP bind-host accepted by WebUI Listener Exposure (settings, restore, boot). */
|
||||
export function isValidBindHost(value: string): boolean {
|
||||
const host = value.trim();
|
||||
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) return false;
|
||||
if (host.includes(':')) return isIP(host) === 6;
|
||||
|
||||
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (host.includes(':')) {
|
||||
return isIP(host) === 6;
|
||||
}
|
||||
|
||||
if (/^[\d.]+$/.test(host)) {
|
||||
return isIP(host) === 4;
|
||||
}
|
||||
|
||||
const normalized = host.endsWith('.') ? host.slice(0, -1) : host;
|
||||
return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/.test(label));
|
||||
}
|
||||
@@ -21,7 +28,13 @@ export function checkListenerExposure(input: {
|
||||
tlsEnabled: boolean;
|
||||
pairOk: boolean;
|
||||
}): ListenerExposureCheck {
|
||||
if (!isValidBindHost(input.webuiHost)) return { ok: false, code: 'invalid-bind-host' };
|
||||
if (input.tlsEnabled && !input.pairOk) return { ok: false, code: 'tls-pair-required' };
|
||||
if (!isValidBindHost(input.webuiHost)) {
|
||||
return { ok: false, code: 'invalid-bind-host' };
|
||||
}
|
||||
|
||||
if (input.tlsEnabled && !input.pairOk) {
|
||||
return { ok: false, code: 'tls-pair-required' };
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -9,7 +9,8 @@ export interface FullTraceExportMetadata {
|
||||
exportedAt: string;
|
||||
}
|
||||
|
||||
const PRIVACY_WARNING = 'WARNING: This export may contain unredacted private data and credentials. Sanitize it before submission.';
|
||||
const PRIVACY_WARNING =
|
||||
'WARNING: This export may contain unredacted private data and credentials. Sanitize it before submission.';
|
||||
|
||||
export interface FullTraceDownload {
|
||||
body: string;
|
||||
@@ -24,9 +25,7 @@ export function buildFullTraceDownload(
|
||||
entries: readonly LogEntry[],
|
||||
metadata: FullTraceExportMetadata,
|
||||
): FullTraceDownload {
|
||||
const timestamp = metadata.exportedAt
|
||||
.slice(0, 19)
|
||||
.replace(/[:.]/g, '-');
|
||||
const timestamp = metadata.exportedAt.slice(0, 19).replace(/[:.]/g, '-');
|
||||
return {
|
||||
body: formatFullTraceExport(entries, metadata),
|
||||
headers: {
|
||||
|
||||
@@ -14,10 +14,7 @@ const STREAMED_REQUEST_PATHS = new Set(['/api/debug/upload']);
|
||||
const STREAMED_RESPONSE_PATHS = new Set(['/api/debug/invoke-stream']);
|
||||
// This route can disable TRACE while its own operation is in flight; its
|
||||
// existing WebUI info record is the authoritative result.
|
||||
const TRACE_EXCLUDED_PATHS = new Set([
|
||||
'/api/auth/check-strength',
|
||||
'/api/logs/level',
|
||||
]);
|
||||
const TRACE_EXCLUDED_PATHS = new Set(['/api/auth/check-strength', '/api/logs/level']);
|
||||
|
||||
interface CapturedBody {
|
||||
bytes: Uint8Array;
|
||||
@@ -25,8 +22,14 @@ interface CapturedBody {
|
||||
}
|
||||
|
||||
function shouldTraceMutation(request: Request): boolean {
|
||||
if (getLogLevel() !== 'trace') return false;
|
||||
if (READ_ONLY_METHODS.has(request.method.toUpperCase())) return false;
|
||||
if (getLogLevel() !== 'trace') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (READ_ONLY_METHODS.has(request.method.toUpperCase())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !TRACE_EXCLUDED_PATHS.has(new URL(request.url).pathname);
|
||||
}
|
||||
|
||||
@@ -91,41 +94,66 @@ function traceStreamedResponse(
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const requestId = currentRequestId();
|
||||
const inContext = <T>(fn: () => T): T => requestId === undefined
|
||||
? fn()
|
||||
: runWithRequestId(requestId, fn);
|
||||
const inContext = <T>(fn: () => T): T =>
|
||||
requestId === undefined ? fn() : runWithRequestId(requestId, fn);
|
||||
let offset = 0;
|
||||
let settled = false;
|
||||
const terminal = (outcome: 'completed' | 'failed' | 'cancelled', reason: string, error?: unknown) => {
|
||||
if (settled) return;
|
||||
|
||||
const terminal = (
|
||||
outcome: 'completed' | 'failed' | 'cancelled',
|
||||
reason: string,
|
||||
error?: unknown,
|
||||
) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
void inContext(() => traceRequestBody(requestBody)).then(() => {
|
||||
inContext(() => log.trace(
|
||||
inContext(() =>
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s status=%d%s elapsedMs=%d',
|
||||
outcome,
|
||||
reason,
|
||||
response.status,
|
||||
error === undefined ? '' : ` error=${JSON.stringify(error instanceof Error ? error.message : String(error))}`,
|
||||
error === undefined
|
||||
? ''
|
||||
: ` error=${JSON.stringify(error instanceof Error ? error.message : String(error))}`,
|
||||
Date.now() - startedAt,
|
||||
));
|
||||
),
|
||||
);
|
||||
});
|
||||
};
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
|
||||
const body = new ReadableStream<Uint8Array>(
|
||||
{
|
||||
async pull(controller) {
|
||||
try {
|
||||
const result = await reader.read();
|
||||
|
||||
if (result.done) {
|
||||
terminal(response.ok ? 'completed' : 'failed', response.ok ? 'response_completed' : 'http_status');
|
||||
terminal(
|
||||
response.ok ? 'completed' : 'failed',
|
||||
response.ok ? 'response_completed' : 'http_status',
|
||||
);
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const chunk = result.value;
|
||||
inContext(() => traceStreamChunk('response_chunk', chunk, offset));
|
||||
offset += chunk.byteLength;
|
||||
controller.enqueue(chunk);
|
||||
} catch (error) {
|
||||
terminal(error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
|
||||
error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed', error);
|
||||
terminal(
|
||||
error instanceof Error && error.name === 'AbortError'
|
||||
? 'cancelled'
|
||||
: 'failed',
|
||||
error instanceof Error && error.name === 'AbortError'
|
||||
? 'body_cancelled'
|
||||
: 'body_read_failed',
|
||||
error,
|
||||
);
|
||||
controller.error(error);
|
||||
}
|
||||
},
|
||||
@@ -133,12 +161,17 @@ function traceStreamedResponse(
|
||||
terminal('cancelled', 'body_cancelled', reason);
|
||||
await reader.cancel(reason);
|
||||
},
|
||||
}, { highWaterMark: 0 });
|
||||
},
|
||||
{ highWaterMark: 0 },
|
||||
);
|
||||
return new Response(body, response);
|
||||
}
|
||||
|
||||
async function traceRequestBody(requestBody: Promise<CapturedBody> | null): Promise<void> {
|
||||
if (!requestBody) return;
|
||||
if (!requestBody) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
traceBody('request_body', await requestBody);
|
||||
} catch (error) {
|
||||
@@ -161,26 +194,41 @@ async function settleMutation(
|
||||
responseBody,
|
||||
]);
|
||||
const [requestResult, responseResult] = results;
|
||||
if (requestBody && requestResult.status === 'fulfilled') traceBody('request_body', requestResult.value);
|
||||
if (requestBody && requestResult.status === 'rejected') {
|
||||
log.trace('webui_mutation_branch branch=request_body_failed error=%j',
|
||||
requestResult.reason instanceof Error ? requestResult.reason.message : String(requestResult.reason));
|
||||
|
||||
if (requestBody && requestResult.status === 'fulfilled') {
|
||||
traceBody('request_body', requestResult.value);
|
||||
}
|
||||
if (responseResult.status === 'fulfilled') traceBody('response', responseResult.value, response);
|
||||
else {
|
||||
|
||||
if (requestBody && requestResult.status === 'rejected') {
|
||||
log.trace(
|
||||
'webui_mutation_branch branch=request_body_failed error=%j',
|
||||
requestResult.reason instanceof Error
|
||||
? requestResult.reason.message
|
||||
: String(requestResult.reason),
|
||||
);
|
||||
}
|
||||
|
||||
if (responseResult.status === 'fulfilled') {
|
||||
traceBody('response', responseResult.value, response);
|
||||
} else {
|
||||
log.trace(() => [
|
||||
'webui_mutation_branch branch=response_body_failed status=%d statusText=%j headers=%s error=%j',
|
||||
response.status,
|
||||
response.statusText,
|
||||
renderParamsVerbose([...response.headers.entries()]),
|
||||
responseResult.reason instanceof Error ? responseResult.reason.message : String(responseResult.reason),
|
||||
responseResult.reason instanceof Error
|
||||
? responseResult.reason.message
|
||||
: String(responseResult.reason),
|
||||
]);
|
||||
}
|
||||
const error = responseResult.status === 'rejected'
|
||||
|
||||
const error =
|
||||
responseResult.status === 'rejected'
|
||||
? responseResult.reason
|
||||
: requestResult.status === 'rejected'
|
||||
? requestResult.reason
|
||||
: undefined;
|
||||
|
||||
if (error === undefined) {
|
||||
if (requestCancelled) {
|
||||
log.trace(
|
||||
@@ -190,6 +238,7 @@ async function settleMutation(
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s status=%d elapsedMs=%d',
|
||||
response.ok ? 'completed' : 'failed',
|
||||
@@ -199,10 +248,13 @@ async function settleMutation(
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
|
||||
error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
|
||||
error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed',
|
||||
error instanceof Error && error.name === 'AbortError'
|
||||
? 'body_cancelled'
|
||||
: 'body_read_failed',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
@@ -215,9 +267,11 @@ function failureOutcome(error: unknown): {
|
||||
if (error instanceof Error && error.name === 'TimeoutError') {
|
||||
return { outcome: 'timeout', reason: 'handler_timeout' };
|
||||
}
|
||||
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return { outcome: 'cancelled', reason: 'handler_cancelled' };
|
||||
}
|
||||
|
||||
return { outcome: 'failed', reason: 'handler_threw' };
|
||||
}
|
||||
|
||||
@@ -226,7 +280,9 @@ export function traceAuthenticatedWebuiMutation(
|
||||
request: Request,
|
||||
next: () => Promise<Response>,
|
||||
): Promise<Response> {
|
||||
if (!shouldTraceMutation(request)) return next();
|
||||
if (!shouldTraceMutation(request)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
@@ -256,10 +312,13 @@ export function traceAuthenticatedWebuiMutation(
|
||||
|
||||
try {
|
||||
const response = await next();
|
||||
|
||||
if (STREAMED_RESPONSE_PATHS.has(pathname)) {
|
||||
return traceStreamedResponse(response, requestBody, startedAt);
|
||||
}
|
||||
|
||||
let responseBody: Promise<CapturedBody>;
|
||||
|
||||
try {
|
||||
responseBody = captureBody(response.clone());
|
||||
} catch (error) {
|
||||
|
||||
@@ -3,9 +3,21 @@ import type { OneBotConfig } from '@snowluma/onebot/types';
|
||||
import { isLoopbackClientIp } from './client-ip';
|
||||
|
||||
function isLoopbackBindHost(host: string | undefined): boolean {
|
||||
const value = host?.trim().toLowerCase().replace(/^\[|\]$/gu, '').replace(/\.$/u, '') ?? '';
|
||||
if (!value) return false;
|
||||
if (value === 'localhost' || value.endsWith('.localhost')) return true;
|
||||
const value =
|
||||
host
|
||||
?.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^\[|\]$/gu, '')
|
||||
.replace(/\.$/u, '') ?? '';
|
||||
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (value === 'localhost' || value.endsWith('.localhost')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return isLoopbackClientIp(value);
|
||||
}
|
||||
|
||||
@@ -33,13 +45,19 @@ function sameTokenAtPreviousIdentity(
|
||||
index: number,
|
||||
): boolean {
|
||||
const named = previous.find((adapter) => adapter.name === nextName);
|
||||
if (named && (named.accessToken ?? '') === nextToken) return true;
|
||||
|
||||
if (named && (named.accessToken ?? '') === nextToken) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Preserve a legacy token when the operator only renames the same list item.
|
||||
// Reordering keeps names stable and is covered by the lookup above.
|
||||
const sameIndex = previous[index];
|
||||
return sameIndex !== undefined
|
||||
&& !next.some((adapter) => adapter.name === sameIndex.name)
|
||||
&& (sameIndex.accessToken ?? '') === nextToken;
|
||||
return (
|
||||
sameIndex !== undefined &&
|
||||
!next.some((adapter) => adapter.name === sameIndex.name) &&
|
||||
(sameIndex.accessToken ?? '') === nextToken
|
||||
);
|
||||
}
|
||||
|
||||
export function validateOneBotAccessTokenChanges(
|
||||
@@ -48,13 +66,18 @@ export function validateOneBotAccessTokenChanges(
|
||||
options: OneBotAccessTokenPolicyOptions,
|
||||
): void {
|
||||
const allowEmptyFromClient = isLoopbackClientIp(options.clientIp);
|
||||
|
||||
for (const kind of INBOUND_KINDS) {
|
||||
const previousList = previous?.networks[kind] ?? [];
|
||||
const nextList = next.networks[kind];
|
||||
|
||||
for (let index = 0; index < nextList.length; index += 1) {
|
||||
const adapter = nextList[index];
|
||||
const token = adapter.accessToken ?? '';
|
||||
if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) continue;
|
||||
|
||||
if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
if (!allowEmptyFromClient && !isLoopbackBindHost(adapter.host)) {
|
||||
@@ -62,6 +85,7 @@ export function validateOneBotAccessTokenChanges(
|
||||
`节点“${adapter.name}”未绑定本机地址,远程保存必须填写令牌;请生成令牌或将主机改为 127.0.0.1。`,
|
||||
);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -73,11 +97,13 @@ export function validateOneBotAccessTokenChanges(
|
||||
host,
|
||||
adapter.port,
|
||||
]);
|
||||
|
||||
if (assessment.reason === 'too-short') {
|
||||
throw new OneBotAccessTokenPolicyError(
|
||||
`节点“${adapter.name}”的令牌至少需要 16 个字符;请重新生成或继续补充。`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!assessment.acceptable) {
|
||||
throw new OneBotAccessTokenPolicyError(
|
||||
`节点“${adapter.name}”的令牌容易被猜中;请重新生成随机令牌。`,
|
||||
|
||||
@@ -4,17 +4,24 @@ function isPortAvailable(port: number, host = '127.0.0.1'): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
let settled = false;
|
||||
|
||||
const finalize = (ok: boolean) => {
|
||||
if (settled) return;
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
|
||||
try {
|
||||
server.close(() => resolve(ok));
|
||||
} catch {
|
||||
resolve(ok);
|
||||
}
|
||||
};
|
||||
|
||||
server.once('error', () => finalize(false));
|
||||
server.once('listening', () => finalize(true));
|
||||
|
||||
try {
|
||||
server.listen(port, host);
|
||||
} catch {
|
||||
@@ -33,10 +40,18 @@ export async function findAvailablePort(
|
||||
): Promise<number> {
|
||||
const { maxTries = 50, host = '127.0.0.1' } = options;
|
||||
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
|
||||
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
if (port > 65535) break;
|
||||
if (await isPortAvailable(port, host)) return port;
|
||||
if (port > 65535) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (await isPortAvailable(port, host)) {
|
||||
return port;
|
||||
}
|
||||
|
||||
port += 1;
|
||||
}
|
||||
|
||||
throw new Error(`No available TCP port found near ${start}`);
|
||||
}
|
||||
@@ -13,14 +13,18 @@ function isJsonMediaType(value: string | undefined): boolean {
|
||||
|
||||
/** Install guards before the login route is registered. */
|
||||
export function registerLoginRequestSecurity(app: Hono): void {
|
||||
app.use('/api/login', bodyLimit({
|
||||
app.use(
|
||||
'/api/login',
|
||||
bodyLimit({
|
||||
maxSize: LOGIN_BODY_LIMIT_BYTES,
|
||||
onError: (c) => c.json({ success: false, message: '请求体过大' }, 413),
|
||||
}));
|
||||
}),
|
||||
);
|
||||
app.use('/api/login', async (c, next) => {
|
||||
if (!isJsonMediaType(c.req.header('content-type'))) {
|
||||
return c.json({ success: false, message: 'Content-Type 必须为 application/json' }, 415);
|
||||
}
|
||||
|
||||
return next();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,11 +2,7 @@ import { createLogger } from '@snowluma/common/logger';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
prepareRestorePlan,
|
||||
RestorePreflightError,
|
||||
type RestoreMigration,
|
||||
} from './backup';
|
||||
import { prepareRestorePlan, RestorePreflightError, type RestoreMigration } from './backup';
|
||||
|
||||
const log = createLogger('WebUI.Restore');
|
||||
|
||||
@@ -86,30 +82,42 @@ interface CommittedFile {
|
||||
*/
|
||||
export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): RestoreBackupResult {
|
||||
const transactionId = options.transactionId ?? randomUUID();
|
||||
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(transactionId)) {
|
||||
throw new Error('restore transactionId must contain only letters, numbers, _ or -');
|
||||
}
|
||||
|
||||
const configDir = path.resolve(options.configDir);
|
||||
|
||||
const readCurrent = (name: string): Buffer | null => {
|
||||
const file = path.join(configDir, name);
|
||||
|
||||
try {
|
||||
return fs.readFileSync(file);
|
||||
} catch (error) {
|
||||
if (isMissingPathError(error)) return null;
|
||||
if (isMissingPathError(error)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const listCurrentOneBotNames = (): string[] => {
|
||||
try {
|
||||
return fs.readdirSync(configDir);
|
||||
} catch (error) {
|
||||
if (isMissingPathError(error)) return [];
|
||||
if (isMissingPathError(error)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
log.info('restore transaction=%s phase=preflight', transactionId);
|
||||
let prepared: ReturnType<typeof prepareRestorePlan>;
|
||||
|
||||
try {
|
||||
prepared = prepareRestorePlan(parsed, {
|
||||
restoreCredentials: options.restoreCredentials,
|
||||
@@ -132,8 +140,13 @@ export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): R
|
||||
failedFiles: file ? [file] : [],
|
||||
});
|
||||
}
|
||||
|
||||
const names = prepared.restore.map((file) => file.name);
|
||||
log.info('restore transaction=%s phase=preflight-complete files=%s', transactionId, names.join(','));
|
||||
log.info(
|
||||
'restore transaction=%s phase=preflight-complete files=%s',
|
||||
transactionId,
|
||||
names.join(','),
|
||||
);
|
||||
|
||||
if (prepared.restore.length === 0) {
|
||||
return {
|
||||
@@ -162,19 +175,29 @@ export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): R
|
||||
fs.chmodSync(transactionDir, 0o700);
|
||||
|
||||
log.info('restore transaction=%s phase=snapshot files=%s', transactionId, names.join(','));
|
||||
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const live = path.join(configDir, file.name);
|
||||
let wasPresent: boolean;
|
||||
|
||||
try {
|
||||
fs.lstatSync(live);
|
||||
wasPresent = true;
|
||||
} catch (error) {
|
||||
if (!isMissingPathError(error)) throw error;
|
||||
if (!isMissingPathError(error)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
wasPresent = false;
|
||||
}
|
||||
|
||||
existed.set(file.name, wasPresent);
|
||||
if (!wasPresent) continue;
|
||||
|
||||
if (!wasPresent) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const snapshot = path.join(snapshotRoot, file.name);
|
||||
fs.mkdirSync(path.dirname(snapshot), { recursive: true });
|
||||
invoke(options, { phase: 'snapshot', operation: 'copy-current', file: file.name });
|
||||
@@ -183,6 +206,7 @@ export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): R
|
||||
|
||||
phase = 'stage';
|
||||
log.info('restore transaction=%s phase=stage files=%s', transactionId, names.join(','));
|
||||
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const staged = path.join(stagedRoot, file.name);
|
||||
@@ -195,6 +219,7 @@ export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): R
|
||||
|
||||
phase = 'commit';
|
||||
log.info('restore transaction=%s phase=commit files=%s', transactionId, names.join(','));
|
||||
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const staged = path.join(stagedRoot, file.name);
|
||||
@@ -204,10 +229,14 @@ export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): R
|
||||
fs.renameSync(staged, live);
|
||||
committed.push({ name: file.name, existed: existed.get(file.name) === true });
|
||||
}
|
||||
|
||||
activeFile = undefined;
|
||||
} catch (error) {
|
||||
if (phase !== 'commit') {
|
||||
const cleanupError = transactionCreated ? removeTransaction(options, transactionDir) : null;
|
||||
const cleanupError = transactionCreated
|
||||
? removeTransaction(options, transactionDir)
|
||||
: null;
|
||||
|
||||
if (cleanupError) {
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=%s file=%s original-error=%s cleanup-error=%s',
|
||||
@@ -221,11 +250,15 @@ export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): R
|
||||
phase: 'cleanup',
|
||||
transactionId,
|
||||
message: `restore ${phase} failed and transaction cleanup also failed`,
|
||||
cause: new AggregateError([error, cleanupError], `restore ${phase} and cleanup both failed`),
|
||||
cause: new AggregateError(
|
||||
[error, cleanupError],
|
||||
`restore ${phase} and cleanup both failed`,
|
||||
),
|
||||
snapshotDir: transactionDir,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
|
||||
log.warn(
|
||||
'restore transaction=%s phase=%s file=%s failed error=%s',
|
||||
transactionId,
|
||||
@@ -242,7 +275,14 @@ export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): R
|
||||
});
|
||||
}
|
||||
|
||||
const rollbackErrors = rollbackCommitted(options, configDir, snapshotRoot, rollbackRoot, committed);
|
||||
const rollbackErrors = rollbackCommitted(
|
||||
options,
|
||||
configDir,
|
||||
snapshotRoot,
|
||||
rollbackRoot,
|
||||
committed,
|
||||
);
|
||||
|
||||
if (rollbackErrors.length > 0) {
|
||||
const failedFiles = rollbackErrors.map((entry) => entry.name);
|
||||
const rollbackDetails = rollbackErrors
|
||||
@@ -272,6 +312,7 @@ export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): R
|
||||
}
|
||||
|
||||
const cleanupError = removeTransaction(options, transactionDir);
|
||||
|
||||
if (cleanupError) {
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=rollback commit-file=%s commit-error=%s cleanup-error=%s snapshot=%s',
|
||||
@@ -284,13 +325,18 @@ export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): R
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'cleanup',
|
||||
transactionId,
|
||||
message: 'restore commit failed, rollback succeeded, but transaction cleanup failed',
|
||||
cause: new AggregateError([error, cleanupError], 'restore commit and post-rollback cleanup both failed'),
|
||||
message:
|
||||
'restore commit failed, rollback succeeded, but transaction cleanup failed',
|
||||
cause: new AggregateError(
|
||||
[error, cleanupError],
|
||||
'restore commit and post-rollback cleanup both failed',
|
||||
),
|
||||
rollbackSucceeded: true,
|
||||
snapshotDir: transactionDir,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
|
||||
log.warn(
|
||||
'restore transaction=%s phase=commit file=%s failed rollback=complete error=%s',
|
||||
transactionId,
|
||||
@@ -308,6 +354,7 @@ export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): R
|
||||
}
|
||||
|
||||
const cleanupError = removeTransaction(options, transactionDir);
|
||||
|
||||
if (cleanupError) {
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=commit cleanup-error=%s snapshot=%s',
|
||||
@@ -343,14 +390,21 @@ function rollbackCommitted(
|
||||
committed: readonly CommittedFile[],
|
||||
): Array<{ name: string; error: unknown }> {
|
||||
const errors: Array<{ name: string; error: unknown }> = [];
|
||||
|
||||
for (const file of [...committed].reverse()) {
|
||||
const live = path.join(configDir, file.name);
|
||||
|
||||
try {
|
||||
if (!file.existed) {
|
||||
invoke(options, { phase: 'rollback', operation: 'remove-created', file: file.name });
|
||||
invoke(options, {
|
||||
phase: 'rollback',
|
||||
operation: 'remove-created',
|
||||
file: file.name,
|
||||
});
|
||||
fs.rmSync(live, { force: true });
|
||||
continue;
|
||||
}
|
||||
|
||||
const snapshot = path.join(snapshotRoot, file.name);
|
||||
const rollback = path.join(rollbackRoot, file.name);
|
||||
fs.mkdirSync(path.dirname(rollback), { recursive: true });
|
||||
@@ -362,6 +416,7 @@ function rollbackCommitted(
|
||||
errors.push({ name: file.name, error });
|
||||
}
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
@@ -384,8 +439,7 @@ function errorMessage(error: unknown): string {
|
||||
}
|
||||
|
||||
function isMissingPathError(error: unknown): boolean {
|
||||
return typeof error === 'object'
|
||||
&& error !== null
|
||||
&& 'code' in error
|
||||
&& error.code === 'ENOENT';
|
||||
return (
|
||||
typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'
|
||||
);
|
||||
}
|
||||
+674
-129
File diff suppressed because it is too large.
Load diff
Loaded 100 of 871 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user