Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3870052fb4 | ||
|
|
b019b00e82 | ||
|
|
50aa9b3595 | ||
|
|
af8d5ab06b | ||
|
|
adf0744f75 | ||
|
|
652bafd75a | ||
|
|
5440cbc37e | ||
|
|
a434da9e85 | ||
|
|
2c565fbd8d | ||
|
|
0d30ee628e | ||
|
|
0f7aa5a600 | ||
|
|
1b07005d91 | ||
|
|
aaed36aa19 | ||
|
|
c3a8a9b6b6 | ||
|
|
868f4a5798 | ||
|
|
93850ec11c | ||
|
|
40c51bcd02 | ||
|
|
bed48bbe46 | ||
|
|
34cc6be8df | ||
|
|
c55042aff4 | ||
|
|
3726913c1f |
@@ -2,7 +2,7 @@ root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
end_of_line = crlf
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
@@ -11,11 +11,5 @@ trim_trailing_whitespace = true
|
||||
[*.{json,yml,yaml,md}]
|
||||
indent_size = 2
|
||||
|
||||
[*.py]
|
||||
indent_size = 4
|
||||
|
||||
[*.bat]
|
||||
end_of_line = crlf
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
trim_trailing_whitespace = false
|
||||
14
.gitattributes
vendored
14
.gitattributes
vendored
@@ -1,14 +0,0 @@
|
||||
* text=auto eol=lf
|
||||
|
||||
*.bat text eol=crlf
|
||||
|
||||
*.node binary
|
||||
*.dll binary
|
||||
*.so binary
|
||||
*.dylib binary
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.woff2 binary
|
||||
33
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
33
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -18,15 +18,13 @@ body:
|
||||
required: true
|
||||
- label: 我使用的是 [最新 Release](https://github.com/SnowLuma/SnowLuma/releases) 或当前 `dev` 分支构建
|
||||
required: true
|
||||
- label: 我已将日志级别调到 TRACE,并在下方「TRACE 日志」一栏附上了复现期间的完整日志
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: snowluma-version
|
||||
attributes:
|
||||
label: SnowLuma 版本
|
||||
description: 启动日志首行或 `package.json` 里的版本号
|
||||
placeholder: "例如 1.10.2"
|
||||
placeholder: "例如 1.8.5"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
@@ -55,19 +53,6 @@ body:
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: deploy
|
||||
attributes:
|
||||
label: 部署方式
|
||||
description: 如何运行 SnowLuma
|
||||
options:
|
||||
- 源码运行(pnpm dev / start)
|
||||
- 预构建包
|
||||
- Docker
|
||||
- 其他 / 不确定
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: node-version
|
||||
attributes:
|
||||
@@ -121,21 +106,11 @@ body:
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: TRACE 日志 / 错误堆栈
|
||||
label: 相关日志 / 错误堆栈
|
||||
description: |
|
||||
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现。
|
||||
|
||||
开启 TRACE 的两种方式(任选其一):
|
||||
- **WebUI(推荐)**:进入「日志」页 →「服务端日志级别」切到 `TRACE` → 显示过滤切到「开发」预设(确保 TRACE 行可见,否则导出不含 trace)→ 复现问题 → 点「导出当前视图」得到 `snowluma-logs-*.log`,拖到本输入框上传。
|
||||
- **环境变量**:启动前设置 `SNOWLUMA_LOG_LEVEL=trace` 再运行,复现后复制控制台输出。
|
||||
|
||||
贴出的日志里应当能看到 `TRACE` 字样。请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
|
||||
placeholder: |
|
||||
[2026-06-26 12:00:00.000] TRACE [core] ...
|
||||
[2026-06-26 12:00:00.001] DEBUG [bridge] ...
|
||||
粘贴控制台日志、SSE 实时日志或错误堆栈。
|
||||
请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
|
||||
render: shell
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: extra
|
||||
|
||||
10
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
10
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@@ -66,13 +66,11 @@ body:
|
||||
- OneBot v11 规范: https://github.com/botuniverse/onebot-11/...
|
||||
- 相关讨论: #xxx
|
||||
|
||||
- type: dropdown
|
||||
- type: checkboxes
|
||||
id: willingness
|
||||
attributes:
|
||||
label: 您是否愿意提交 PR 来实现这个功能?
|
||||
options:
|
||||
- 愿意,但需要维护者讨论方案后再动手
|
||||
- 愿意,已有大致实现思路
|
||||
- 暂时只提建议
|
||||
validations:
|
||||
required: true
|
||||
- label: 愿意,且需要维护者讨论方案后再动手
|
||||
- label: 愿意,已有大致实现思路
|
||||
- label: 暂时只提建议
|
||||
|
||||
40
.github/logo.svg
vendored
40
.github/logo.svg
vendored
@@ -1,40 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 120" width="100%" height="100%" style="background-color: transparent;">
|
||||
<defs>
|
||||
<style>
|
||||
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@800&display=swap');
|
||||
|
||||
.title-font {
|
||||
font-family: 'Plus Jakarta Sans', sans-serif;
|
||||
font-size: 48px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
text-anchor: middle;
|
||||
}
|
||||
|
||||
.star-fx {
|
||||
animation: floatAnimation 4s ease-in-out infinite;
|
||||
}
|
||||
.star-top { transform-origin: 265px 25px; fill: #cec1e6; }
|
||||
.star-bottom { transform-origin: 45px 95px; animation-delay: 0.5s; fill: #fad6e6; }
|
||||
|
||||
@keyframes floatAnimation {
|
||||
0% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
|
||||
50% { transform: translateY(-8px) rotate(10deg); opacity: 1; }
|
||||
100% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
|
||||
}
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<g transform="translate(160, 75)">
|
||||
<text class="title-font" dx="2" dy="2">
|
||||
<tspan fill="#f9d5e7">Snow</tspan><tspan fill="#a5c9ff">Luma</tspan>
|
||||
</text>
|
||||
|
||||
<text class="title-font" dx="0" dy="0">
|
||||
<tspan fill="#a5c9ff">Snow</tspan><tspan fill="#cec1e6">Luma</tspan>
|
||||
</text>
|
||||
</g>
|
||||
|
||||
<path class="star-fx star-top" d="M265,13 L267.8,21.1 L276,24 L267.8,26.9 L265,35 L262.2,26.9 L254,24 L262.2,21.1 Z"/>
|
||||
<path class="star-fx star-bottom" d="M45,84 L47.1,90.2 L53.5,92.2 L47.1,94.2 L45,100 L42.9,94.2 L36.5,92.2 L42.9,90.2 Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
17
.github/pull_request_template.md
vendored
17
.github/pull_request_template.md
vendored
@@ -1,17 +0,0 @@
|
||||
<!-- 感谢贡献。请填写以下内容,方便评审。 -->
|
||||
|
||||
## 关联 Issue
|
||||
|
||||
<!-- 例如 Closes #123。若无关联 issue,请说明这个 PR 解决什么问题、为何现在做。 -->
|
||||
|
||||
## 变更说明
|
||||
|
||||
<!-- 简述本 PR 做了什么、为什么这样做。 -->
|
||||
|
||||
## 提交前检查
|
||||
|
||||
- [ ] 本 PR 聚焦单一目标,未夹带无关改动
|
||||
- [ ] 已通过 `pnpm lint` 与 `pnpm typecheck`
|
||||
- [ ] 已补充/更新相关测试,且 `pnpm test` 通过
|
||||
- [ ] 文件行尾为 LF(未引入 CRLF)
|
||||
- [ ] PR 描述与实际实现一致
|
||||
111
.github/workflows/ci.yml
vendored
111
.github/workflows/ci.yml
vendored
@@ -1,111 +0,0 @@
|
||||
# Run the root validation commands on every pull request.
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Cancel an in-flight run when the PR gets new commits.
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run all package tests
|
||||
run: pnpm test
|
||||
|
||||
# The MCP test suite regenerates the action catalog (catalog.ts + the
|
||||
# catalog.json the docs site consumes). Fail if the committed snapshot
|
||||
# drifted from the live specs — keeps the API docs from going stale.
|
||||
- name: Verify generated action catalog is up to date
|
||||
run: |
|
||||
catalog_status="$(git status --porcelain=v1 --untracked-files=all -- packages/mcp/src/generated)"
|
||||
if [ -n "$catalog_status" ]; then
|
||||
git diff -- packages/mcp/src/generated
|
||||
printf '%s\n' "$catalog_status"
|
||||
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Type check all packages
|
||||
run: pnpm typecheck
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build release inputs
|
||||
run: pnpm run build:all
|
||||
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Lint managed source files
|
||||
run: pnpm lint
|
||||
162
.github/workflows/dev-build.yml
vendored
162
.github/workflows/dev-build.yml
vendored
@@ -7,15 +7,6 @@ on:
|
||||
tags-ignore:
|
||||
- 'v*'
|
||||
|
||||
# Only `dev` gets a shared, self-cancelling group so a newer dev commit
|
||||
# supersedes the in-flight one (and its Docker dispatch) before it publishes.
|
||||
# Every other branch falls back to a unique per-run group (github.run_id), so
|
||||
# their concurrency behavior is unchanged — no shared-group pending-run
|
||||
# replacement, no accidental serialization.
|
||||
concurrency:
|
||||
group: ${{ github.ref == 'refs/heads/dev' && format('{0}-{1}', github.workflow, github.ref) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.ref == 'refs/heads/dev' }}
|
||||
|
||||
jobs:
|
||||
cleanup:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -23,20 +14,10 @@ jobs:
|
||||
actions: write
|
||||
contents: read
|
||||
steps:
|
||||
# Delete only artifacts older than 24h. The dev Docker hand-off relies on
|
||||
# this run's fresh `snowluma-dev-docker-*` artifact still existing when the
|
||||
# downstream (cross-repo) Docker build downloads it; a blanket "delete all"
|
||||
# here — which also runs on every other branch's push — could race-delete
|
||||
# an in-flight hand-off artifact. Age-gating keeps recent ones safe while
|
||||
# still reaping the backlog.
|
||||
- name: Delete old artifacts
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const cutoff = Date.now() - 24 * 60 * 60 * 1000;
|
||||
// Collect every artifact first, THEN delete — deleting mid-pagination
|
||||
// shifts the list and would skip ~a page of old artifacts per delete.
|
||||
const all = [];
|
||||
let page = 1;
|
||||
while (true) {
|
||||
const { data: { artifacts } } = await github.rest.actions.listArtifactsForRepo({
|
||||
@@ -46,19 +27,15 @@ jobs:
|
||||
page,
|
||||
});
|
||||
if (artifacts.length === 0) break;
|
||||
all.push(...artifacts);
|
||||
page++;
|
||||
}
|
||||
for (const artifact of all) {
|
||||
if (new Date(artifact.created_at).getTime() >= cutoff) {
|
||||
continue; // keep recent artifacts (may be in-flight dev hand-offs)
|
||||
for (const artifact of artifacts) {
|
||||
await github.rest.actions.deleteArtifact({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
artifact_id: artifact.id,
|
||||
});
|
||||
console.log(`Deleted artifact: ${artifact.name}`);
|
||||
}
|
||||
await github.rest.actions.deleteArtifact({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
artifact_id: artifact.id,
|
||||
});
|
||||
console.log(`Deleted artifact: ${artifact.name}`);
|
||||
page++;
|
||||
}
|
||||
|
||||
typecheck:
|
||||
@@ -78,7 +55,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
@@ -121,31 +98,21 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run native smoke tests
|
||||
run: pnpm test:native
|
||||
|
||||
# Always builds the WebUI flavor — no separate "core-only" artifact.
|
||||
- name: Build project
|
||||
env:
|
||||
SNOWLUMA_TARGET: ${{ matrix.target }}
|
||||
run: pnpm run build:all
|
||||
|
||||
# Bundle production node_modules into dist/ before packaging — mirrors
|
||||
# release.yml. Without this the `-lite` tarball has no runtime deps and the
|
||||
# Docker image (which bakes the lite tarball) can't start.
|
||||
- name: Bundle runtime dependencies
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
- name: Package (windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: pwsh
|
||||
@@ -173,110 +140,3 @@ jobs:
|
||||
retention-days: 3
|
||||
overwrite: true
|
||||
if-no-files-found: error
|
||||
|
||||
# Deterministic-name hand-off artifact consumed by the cross-repo dev
|
||||
# Docker build (SnowLuma.Docker.Framework/docker-image.yml downloads it by
|
||||
# this exact name). linux-x64 only — dev images are amd64-only. Just the
|
||||
# lite tarball; the container already ships its own Node runtime.
|
||||
- name: Upload dev Docker hand-off artifact
|
||||
if: matrix.name == 'linux-x64' && github.ref == 'refs/heads/dev'
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: snowluma-dev-docker-linux-x64
|
||||
path: SnowLuma-dev-linux-x64-lite.tar.gz
|
||||
retention-days: 3
|
||||
overwrite: true
|
||||
if-no-files-found: error
|
||||
|
||||
# Fire the "latest dev" Docker build on SnowLuma.Docker.Framework — but only
|
||||
# for `dev`. Mirrors release.yml's dispatch-docker, parameterized for dev:
|
||||
# tag=dev (rolling) + sha_tag=dev-<12sha> (immutable), also_latest=false so it
|
||||
# never touches the stable :latest, platforms=amd64, and artifact_run_id so the
|
||||
# downstream build pulls THIS run's hand-off artifact instead of a Release.
|
||||
dispatch-dev-docker:
|
||||
needs: [build]
|
||||
if: github.ref == 'refs/heads/dev'
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Compute short SHA
|
||||
id: sha
|
||||
run: echo "short=${GITHUB_SHA:0:12}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Dispatch dev Docker build
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
RELEASE_REPOSITORY: ${{ vars.DOCKER_RELEASE_REPOSITORY }}
|
||||
DOCKER_IMAGE: ${{ vars.DOCKER_IMAGE }}
|
||||
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
|
||||
DOCKER_REF: ${{ vars.DOCKER_REF }}
|
||||
SHA_TAG: dev-${{ steps.sha.outputs.short }}
|
||||
ARTIFACT_RUN_ID: ${{ github.run_id }}
|
||||
with:
|
||||
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
|
||||
script: |
|
||||
const target = process.env.RELEASE_REPOSITORY;
|
||||
if (!target || !target.includes('/')) {
|
||||
throw new Error('Set SnowLuma environment variable DOCKER_RELEASE_REPOSITORY to owner/repo.');
|
||||
}
|
||||
const [owner, repo] = target.split('/');
|
||||
const sourceRepo = context.repo.owner + '/' + context.repo.repo;
|
||||
const image = process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
|
||||
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
|
||||
const ref = process.env.DOCKER_REF || 'main';
|
||||
const runId = String(process.env.ARTIFACT_RUN_ID);
|
||||
const shaTag = process.env.SHA_TAG;
|
||||
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: workflowId,
|
||||
ref,
|
||||
inputs: {
|
||||
image,
|
||||
tag: 'dev',
|
||||
push: 'true',
|
||||
platforms: 'linux/amd64',
|
||||
also_latest: 'false',
|
||||
snowluma_repository: sourceRepo,
|
||||
artifact_run_id: runId,
|
||||
sha_tag: shaTag,
|
||||
},
|
||||
});
|
||||
core.info(`Dispatched ${workflowId}@${ref} on ${target} for dev (image=${image}:dev + :${shaTag}, src run ${runId}).`);
|
||||
|
||||
// Best-effort: resolve the dispatched run by its unique run-name
|
||||
// marker so the summary links straight to it (every dev dispatch is
|
||||
// tag=dev, so we key on the source run id, not the tag).
|
||||
const marker = `(src-run ${runId})`;
|
||||
let runUrl = '';
|
||||
for (let i = 0; i < 6 && !runUrl; i++) {
|
||||
await new Promise((r) => setTimeout(r, 5000));
|
||||
try {
|
||||
const { data } = await github.rest.actions.listWorkflowRuns({
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: workflowId,
|
||||
event: 'workflow_dispatch',
|
||||
per_page: 30,
|
||||
});
|
||||
const hit = data.workflow_runs.find(
|
||||
(r) => (r.display_title || r.name || '').includes(marker),
|
||||
);
|
||||
if (hit) runUrl = hit.html_url;
|
||||
} catch (e) {
|
||||
core.warning(`Downstream run lookup failed: ${e.message}`);
|
||||
}
|
||||
}
|
||||
const workflowUrl = `https://github.com/${owner}/${repo}/actions/workflows/${workflowId}`;
|
||||
await core.summary
|
||||
.addHeading('dev Docker dispatch', 3)
|
||||
.addList([
|
||||
`source SHA: ${context.sha}`,
|
||||
`source run id: ${runId}`,
|
||||
`image: ${image}:dev + ${image}:${shaTag}`,
|
||||
`downstream run: ${runUrl || `(not resolved yet — see ${workflowUrl}, look for ${marker})`}`,
|
||||
])
|
||||
.write();
|
||||
|
||||
94
.github/workflows/issue-require-logs.yml
vendored
94
.github/workflows/issue-require-logs.yml
vendored
@@ -1,94 +0,0 @@
|
||||
name: 校验 Bug 反馈日志
|
||||
|
||||
# 表单只能强制「非空」,强制不了「内容真的是 TRACE 级别」。
|
||||
# 这个 workflow 在 bug issue 打开/编辑时解析正文里的 TRACE 日志小节,
|
||||
# 缺日志就打 needs-logs 标签 + 评论,补齐后自动移除标签。
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, edited]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
require-trace-logs:
|
||||
runs-on: ubuntu-latest
|
||||
# 只校验 Bug 反馈(表单会自动打 bug 标签)
|
||||
if: contains(join(github.event.issue.labels.*.name, ','), 'bug')
|
||||
steps:
|
||||
- uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const NEEDS = 'needs-logs';
|
||||
const MARKER = '<!-- needs-logs-bot -->';
|
||||
const { owner, repo } = context.repo;
|
||||
const issue = context.payload.issue;
|
||||
const number = issue.number;
|
||||
const body = issue.body || '';
|
||||
|
||||
// 抽取「TRACE 日志 / 错误堆栈」小节(issue form 渲染成 ### 标题)
|
||||
const m = body.match(/###\s*TRACE 日志[^\n]*\n([\s\S]*?)(?:\n###\s|$)/);
|
||||
const section = (m ? m[1] : '').trim();
|
||||
|
||||
// 粘贴的终端日志常带 ANSI 颜色码(如 \x1b[90mTRACE\x1b[0m),
|
||||
// 颜色码结尾的 'm' 紧贴 TRACE 会吃掉 \b 单词边界,先剥掉再判定。
|
||||
const clean = section.replace(/\x1b\[[0-9;]*m/g, '');
|
||||
|
||||
const empty = section === '' || /^_no response_$/i.test(section);
|
||||
const hasTrace = /\bTRACE\b/i.test(clean);
|
||||
// 去掉代码围栏后过短,基本等于没给
|
||||
const stripped = clean.replace(/```[a-z]*|```|`/gi, '').trim();
|
||||
const tooShort = stripped.length < 40;
|
||||
const ok = !empty && hasTrace && !tooShort;
|
||||
|
||||
const hasLabel = (issue.labels || []).some((l) => (l.name || l) === NEEDS);
|
||||
|
||||
if (ok) {
|
||||
if (hasLabel) {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({ owner, repo, issue_number: number, name: NEEDS });
|
||||
} catch (e) { /* 已被手动移除则忽略 */ }
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 确保标签存在再添加(addLabels 不会自动建标签)
|
||||
try {
|
||||
await github.rest.issues.getLabel({ owner, repo, name: NEEDS });
|
||||
} catch (e) {
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner, repo, name: NEEDS, color: 'd93f0b',
|
||||
description: '缺少有效的 TRACE 日志',
|
||||
});
|
||||
} catch (e2) { /* 并发下可能已被建出 */ }
|
||||
}
|
||||
await github.rest.issues.addLabels({ owner, repo, issue_number: number, labels: [NEEDS] });
|
||||
|
||||
// 已经提示过就不再刷屏
|
||||
const comments = await github.paginate(github.rest.issues.listComments, {
|
||||
owner, repo, issue_number: number,
|
||||
});
|
||||
if (comments.some((c) => (c.body || '').includes(MARKER))) return;
|
||||
|
||||
const reasons = [];
|
||||
if (empty) reasons.push('- 日志字段为空');
|
||||
else if (!hasTrace) reasons.push('- 日志里没有 `TRACE` 字样(默认级别 `info` 不输出 TRACE,需先开启)');
|
||||
else if (tooShort) reasons.push('- 日志内容过短,疑似未提供完整日志');
|
||||
|
||||
const comment = [
|
||||
MARKER,
|
||||
`@${issue.user.login} 这条反馈缺少有效的 **TRACE 级别日志**,已标记为 \`${NEEDS}\`:`,
|
||||
'',
|
||||
reasons.join('\n'),
|
||||
'',
|
||||
'请按以下任一方式开启 TRACE 后复现,再 **编辑本 issue** 把完整日志补到「TRACE 日志 / 错误堆栈」一栏:',
|
||||
'',
|
||||
'- **WebUI**:「日志」页 → 服务端日志级别切到 `TRACE` → 显示过滤用「开发」预设 → 复现 → 导出当前视图。',
|
||||
'- **环境变量**:`SNOWLUMA_LOG_LEVEL=trace` 启动后复现。',
|
||||
'',
|
||||
'补齐后机器人会自动移除该标记。若你以附件形式上传了 `.log` 文件,请在正文里也贴一段关键日志(机器人只能识别正文)。',
|
||||
].join('\n');
|
||||
|
||||
await github.rest.issues.createComment({ owner, repo, issue_number: number, body: comment });
|
||||
65
.github/workflows/issue-template-guard.yml
vendored
65
.github/workflows/issue-template-guard.yml
vendored
@@ -1,65 +0,0 @@
|
||||
name: Issue template guard
|
||||
|
||||
# Blank / free-form issues bypass `blank_issues_enabled: false` (it only hides
|
||||
# the chooser link — the CLI, API and direct URLs still create template-less
|
||||
# issues). This guard enforces the policy after the fact: an issue opened by
|
||||
# someone WITHOUT write access that did not go through a template (no template
|
||||
# label) is commented on and closed. Properly-filed bug reports / feature
|
||||
# requests (which carry `bug` / `enhancement`) and anyone with write access are
|
||||
# left alone.
|
||||
#
|
||||
# Note: workflows for `issues` events run from the file on the DEFAULT branch,
|
||||
# so this only takes effect once it lands on `main`.
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
guard:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const issue = context.payload.issue;
|
||||
|
||||
// Write-access roles are exempt.
|
||||
const privileged = ['OWNER', 'MEMBER', 'COLLABORATOR'];
|
||||
if (privileged.includes(issue.author_association)) {
|
||||
core.info(`author_association=${issue.author_association} — allowed`);
|
||||
return;
|
||||
}
|
||||
|
||||
// A template was used iff it stamped its label.
|
||||
const TEMPLATE_LABELS = ['bug', 'enhancement'];
|
||||
const labels = (issue.labels || []).map((l) => (typeof l === 'string' ? l : l.name));
|
||||
if (labels.some((l) => TEMPLATE_LABELS.includes(l))) {
|
||||
core.info('template label present — allowed');
|
||||
return;
|
||||
}
|
||||
|
||||
// Non-privileged + no template → guide and close.
|
||||
const { owner, repo } = context.repo;
|
||||
const chooser = `https://github.com/${owner}/${repo}/issues/new/choose`;
|
||||
const body = [
|
||||
'感谢你的反馈。',
|
||||
'',
|
||||
'本仓库的 issue 需要通过模板提交:请使用 **Bug 反馈** 或 **功能请求** 模板重新创建,',
|
||||
'以便我们准确、高效地处理。直接创建的空白 / 自定义 issue 会被自动关闭。',
|
||||
'',
|
||||
`- 重新创建:${chooser}`,
|
||||
'- 日常使用、快速交流类问题,可先到 README 中的 QQ 群',
|
||||
'',
|
||||
'本 issue 将自动关闭,感谢理解。',
|
||||
].join('\n');
|
||||
|
||||
await github.rest.issues.createComment({ owner, repo, issue_number: issue.number, body });
|
||||
await github.rest.issues.update({
|
||||
owner, repo, issue_number: issue.number,
|
||||
state: 'closed', state_reason: 'not_planned',
|
||||
});
|
||||
core.info(`closed #${issue.number} (author_association=${issue.author_association}, no template label)`);
|
||||
109
.github/workflows/mcp-npm-publish.yml
vendored
109
.github/workflows/mcp-npm-publish.yml
vendored
@@ -1,109 +0,0 @@
|
||||
name: Publish MCP to npm
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'packages/mcp/**'
|
||||
# The action catalog is generated from @snowluma/onebot's specs, so an
|
||||
# action change must republish the MCP snapshot.
|
||||
- 'packages/onebot/**'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'pnpm-workspace.yaml'
|
||||
- 'tsconfig.base.json'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: mcp-npm-publish-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Build, test, and publish MCP
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Type check MCP
|
||||
run: pnpm --filter @snowluma/mcp typecheck
|
||||
|
||||
- name: Test MCP (regenerates + validates the action catalog)
|
||||
run: pnpm --filter @snowluma/mcp test
|
||||
|
||||
- name: Build MCP
|
||||
run: pnpm --filter @snowluma/mcp build
|
||||
|
||||
- name: Check npm package version
|
||||
id: npm
|
||||
working-directory: packages/mcp
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
|
||||
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
|
||||
|
||||
{
|
||||
echo "package_name=${package_name}"
|
||||
echo "package_version=${package_version}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
|
||||
echo "already_published=true" >> "${GITHUB_OUTPUT}"
|
||||
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
|
||||
else
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Publish MCP to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/mcp
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
shell: bash
|
||||
run: |
|
||||
{
|
||||
echo "## MCP npm publish"
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
91
.github/workflows/release.yml
vendored
91
.github/workflows/release.yml
vendored
@@ -9,45 +9,7 @@ permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
preflight:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run all package tests
|
||||
run: pnpm test
|
||||
|
||||
- name: Type check all packages
|
||||
run: pnpm typecheck
|
||||
|
||||
- name: Verify generated action catalog is up to date
|
||||
run: |
|
||||
catalog_status="$(git status --porcelain=v1 --untracked-files=all -- packages/mcp/src/generated)"
|
||||
if [ -n "$catalog_status" ]; then
|
||||
git diff -- packages/mcp/src/generated
|
||||
printf '%s\n' "$catalog_status"
|
||||
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
build:
|
||||
needs: preflight
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -77,15 +39,12 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run native smoke tests
|
||||
run: pnpm test:native
|
||||
|
||||
# Always builds the WebUI flavor — no separate "core-only" artifact.
|
||||
- name: Build project
|
||||
env:
|
||||
@@ -98,7 +57,7 @@ jobs:
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
|
||||
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
- name: Package (windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: pwsh
|
||||
@@ -150,42 +109,42 @@ jobs:
|
||||
tag="${GITHUB_REF_NAME}"
|
||||
previousTag="$(git describe --tags --abbrev=0 "${tag}^" 2>/dev/null || true)"
|
||||
if [[ -n "$previousTag" ]]; then
|
||||
range="$previousTag..$tag"
|
||||
comparison="[查看 ${previousTag} → ${tag} 的完整差异](https://github.com/${GITHUB_REPOSITORY}/compare/${previousTag}...${tag})"
|
||||
changes="$(git log --pretty=format:'- %s (%h)' "$previousTag..$tag")"
|
||||
else
|
||||
range="$tag"
|
||||
comparison=""
|
||||
changes="$(git log --pretty=format:'- %s (%h)' "$tag")"
|
||||
fi
|
||||
changes="$(git log --no-merges --invert-grep --grep='^chore(release):' --pretty=format:"- %s ([%h](https://github.com/${GITHUB_REPOSITORY}/commit/%H))" "$range")"
|
||||
[[ -z "$changes" ]] && changes="- No commit changes detected."
|
||||
cat > release-notes.md <<EOF
|
||||
# SnowLuma ${tag}
|
||||
|
||||
> **跨平台正式支持:** Windows x64、Linux x64 与 Linux arm64 均可完整运行 SnowLuma,包含 QQ 接入、OneBot v11 与 WebUI 管理能力。
|
||||
## 发布概览
|
||||
本次发布提供 SnowLuma 的 Windows x64 / Linux x64 / Linux arm64 构建产物,默认包含 WebUI。
|
||||
|
||||
## 选择下载
|
||||
## 下载说明
|
||||
命名约定:
|
||||
- 无后缀 \`.zip/.tar.gz\`:完整版本,内置 \`node\`/\`node.exe\` 与运行时依赖,解压即可使用。
|
||||
- \`-lite\` 后缀:精简版本,不含 Node.js 运行时,需自行安装 Node.js 22+。
|
||||
|
||||
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 22.13+;23 系需 23.4+) |
|
||||
| --- | --- | --- |
|
||||
| Windows x64 | \`SnowLuma-${tag}-win-x64.zip\` | \`SnowLuma-${tag}-win-x64-lite.zip\` |
|
||||
| Linux x64 | \`SnowLuma-${tag}-linux-x64.tar.gz\` | \`SnowLuma-${tag}-linux-x64-lite.tar.gz\` |
|
||||
| Linux arm64 | \`SnowLuma-${tag}-linux-arm64.tar.gz\` | \`SnowLuma-${tag}-linux-arm64-lite.tar.gz\` |
|
||||
Windows:
|
||||
- \`SnowLuma-${tag}-win-x64.zip\`
|
||||
- \`SnowLuma-${tag}-win-x64-lite.zip\`
|
||||
|
||||
完整版适合直接解压运行;Lite 版不包含 Node.js,但其余运行时依赖和 WebUI 静态资源保持一致。
|
||||
Linux x64:
|
||||
- \`SnowLuma-${tag}-linux-x64.tar.gz\`
|
||||
- \`SnowLuma-${tag}-linux-x64-lite.tar.gz\`
|
||||
|
||||
## 快速开始
|
||||
|
||||
1. 解压与你的系统架构匹配的压缩包。
|
||||
2. Windows 运行 \`launcher.bat\`;Linux 运行 \`./launcher.sh\`。
|
||||
3. 浏览器访问 http://localhost:5099,初始账号为 \`admin\`,密码见启动日志。
|
||||
|
||||
无人值守部署可同时设置 \`SNOWLUMA_ACCEPT_EULA=1\` 与 \`SNOWLUMA_ACCEPT_PRIVACY=1\` 完成协议确认。设置这些变量即表示运营者已阅读并同意发行包内的 EULA 与隐私政策;缺少任意一项时仍会显示同意页面。
|
||||
|
||||
## 本次更新
|
||||
Linux arm64:
|
||||
- \`SnowLuma-${tag}-linux-arm64.tar.gz\`
|
||||
- \`SnowLuma-${tag}-linux-arm64-lite.tar.gz\`
|
||||
|
||||
## 更新内容
|
||||
${changes}
|
||||
|
||||
${comparison}
|
||||
## 使用说明
|
||||
- Windows x64:\`launcher.bat\` 或 \`node index.mjs\`。
|
||||
- Linux:\`./launcher.sh\` 或 \`node index.mjs\`。
|
||||
- 所有压缩包均已内置 WebUI 静态资源;启动后访问 http://localhost:5099。
|
||||
- Linux 版本仅提供 OneBot 桥接能力,NTQQ 进程注入仅在 Windows 下生效。
|
||||
EOF
|
||||
|
||||
- name: Create GitHub Release
|
||||
|
||||
2
.github/workflows/sdk-npm-publish.yml
vendored
2
.github/workflows/sdk-npm-publish.yml
vendored
@@ -37,7 +37,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
|
||||
34
.github/workflows/stale-needs-logs.yml
vendored
34
.github/workflows/stale-needs-logs.yml
vendored
@@ -1,34 +0,0 @@
|
||||
name: 关闭长期缺日志的反馈
|
||||
|
||||
# needs-logs 的 issue 若长期不补 TRACE 日志,先标 stale,再自动关闭。
|
||||
# 补齐日志后 issue-require-logs 会移除 needs-logs,这里 only-labels 过滤即跳过。
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 2 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
only-labels: 'needs-logs'
|
||||
days-before-stale: 7
|
||||
days-before-close: 7
|
||||
stale-issue-label: 'stale'
|
||||
close-issue-reason: 'not_planned'
|
||||
ascending: true
|
||||
# 不处理 PR
|
||||
days-before-pr-stale: -1
|
||||
days-before-pr-close: -1
|
||||
stale-issue-message: >
|
||||
这条反馈因长期缺少有效的 TRACE 日志被标记为 `stale`。
|
||||
若 7 天内仍未补充日志,将自动关闭。补充后请编辑 issue 贴上日志或留言。
|
||||
close-issue-message: >
|
||||
因长期缺少定位所需的 TRACE 日志,已自动关闭。
|
||||
如果问题仍然存在,欢迎补齐 TRACE 日志后重新打开本 issue 或新开一个。
|
||||
114
.github/workflows/sync-docs-catalog.yml
vendored
114
.github/workflows/sync-docs-catalog.yml
vendored
@@ -1,114 +0,0 @@
|
||||
name: Sync action catalog to docs
|
||||
|
||||
# Regenerates the OneBot action catalog from @snowluma/onebot's specs and commits
|
||||
# the plain-JSON twin (catalog.json) into the SnowLumaDocs repo, where the docs
|
||||
# build turns it into the API Reference pages. Runs on main (the release/promote
|
||||
# target) so the published docs always describe shipped behavior. Uses the same
|
||||
# SnowLuma bot GitHub App as the promote-dev-to-main flow.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'packages/onebot/src/actions/**'
|
||||
- 'packages/onebot/src/action-kit.ts'
|
||||
- 'packages/onebot/src/action-docs.ts'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sync-docs-catalog
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout SnowLuma
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Generate catalog.json
|
||||
run: pnpm --filter @snowluma/mcp gen
|
||||
|
||||
- name: Validate GitHub App credentials
|
||||
env:
|
||||
APP_ID: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
|
||||
PRIVATE_KEY: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
|
||||
run: |
|
||||
if [ -z "${APP_ID}" ] || [ -z "${PRIVATE_KEY}" ]; then
|
||||
echo 'Missing SNOWLUMA_BOT_APP_ID and/or SNOWLUMA_BOT_PRIVATE_KEY secrets.' >&2
|
||||
echo 'Configure the same GitHub App used by the promote-dev-to-main flow.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Mint GitHub App installation token (scoped to SnowLumaDocs)
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
|
||||
private-key: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
repositories: SnowLumaDocs
|
||||
|
||||
- name: Resolve bot identity
|
||||
id: bot
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bot_login="${APP_SLUG}[bot]"
|
||||
bot_id="$(gh api "/users/${bot_login}" --jq .id)"
|
||||
bot_email="${bot_id}+${bot_login}@users.noreply.github.com"
|
||||
{
|
||||
echo "login=${bot_login}"
|
||||
echo "email=${bot_email}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
- name: Commit catalog.json to docs repo
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
BOT_LOGIN: ${{ steps.bot.outputs.login }}
|
||||
BOT_EMAIL: ${{ steps.bot.outputs.email }}
|
||||
OWNER: ${{ github.repository_owner }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
src="$(pwd)/packages/mcp/src/generated/catalog.json"
|
||||
tmp="$(mktemp -d)"
|
||||
git clone --depth 1 \
|
||||
"https://x-access-token:${GH_TOKEN}@github.com/${OWNER}/SnowLumaDocs.git" "$tmp"
|
||||
mkdir -p "$tmp/docs/public/api"
|
||||
cp "$src" "$tmp/docs/public/api/catalog.json"
|
||||
cd "$tmp"
|
||||
git config user.name "${BOT_LOGIN}"
|
||||
git config user.email "${BOT_EMAIL}"
|
||||
# Stage first: `git diff --quiet` ignores UNTRACKED files, so on the
|
||||
# initial sync (catalog.json not yet in the docs repo) the index diff
|
||||
# is the only reliable change check.
|
||||
git add docs/public/api/catalog.json
|
||||
if git diff --cached --quiet; then
|
||||
echo "::notice::catalog.json unchanged; nothing to sync."
|
||||
exit 0
|
||||
fi
|
||||
git commit -m "chore(api): sync action catalog from SnowLuma@${GITHUB_SHA::7}"
|
||||
# Single writer, but guard against a concurrent docs commit racing the
|
||||
# shallow clone: rebase onto the latest main before pushing.
|
||||
git pull --rebase --depth 1 origin main
|
||||
git push origin HEAD:main
|
||||
2
.github/workflows/ui-npm-publish.yml
vendored
2
.github/workflows/ui-npm-publish.yml
vendored
@@ -37,7 +37,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -11,13 +11,7 @@ dist/
|
||||
|
||||
/config/
|
||||
/data/
|
||||
# per-package runtime data dirs (e.g. packages/core/data/<uin>/*.db written by
|
||||
# IdentityService during tests) — not just the root /data/
|
||||
**/data/
|
||||
logs/
|
||||
|
||||
# macOS metadata
|
||||
.DS_Store
|
||||
|
||||
# test coverage output
|
||||
coverage/
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
22.13.0
|
||||
11
.npmrc
11
.npmrc
@@ -1,4 +1,13 @@
|
||||
registry=https://registry.npmmirror.com/
|
||||
@moonrepo:registry=https://registry.npmmirror.com/
|
||||
|
||||
# Mirrors for binary downloads (sharp, esbuild, swc, electron etc.)
|
||||
disturl=https://npmmirror.com/dist
|
||||
electron_mirror=https://npmmirror.com/mirrors/electron/
|
||||
sass_binary_site=https://npmmirror.com/mirrors/node-sass/
|
||||
sharp_binary_host=https://npmmirror.com/mirrors/sharp
|
||||
sharp_libvips_binary_host=https://npmmirror.com/mirrors/sharp-libvips
|
||||
puppeteer_download_host=https://npmmirror.com/mirrors
|
||||
|
||||
auto-install-peers=true
|
||||
strict-peer-dependencies=false
|
||||
engine-strict=true
|
||||
|
||||
@@ -43,14 +43,10 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
|
||||
|
||||
### 系统要求
|
||||
|
||||
- **Node.js 22.13+(23 系需 23.4+)**(项目使用默认启用的 `node:sqlite`)
|
||||
- **pnpm 10.28.0**(项目通过 `packageManager` 与 CI 统一版本)
|
||||
- **Node.js ≥ 22**(`engines` 字段强制,低版本会报错)
|
||||
- **pnpm 10.28.0+**(项目通过 `packageManager` 字段锁定,建议用 `corepack enable` 安装匹配版本)
|
||||
- macOS / Linux / Windows 均可。如果要构建原生产物,需要对应平台的工具链。
|
||||
|
||||
如果系统提供 Corepack,可执行 `corepack enable pnpm`;没有 Corepack 时可执行
|
||||
`npm install -g pnpm@10.28.0`。进入仓库后,`node --version` 与
|
||||
`pnpm --version` 应满足上述版本要求,否则安装会直接失败。
|
||||
|
||||
### 拉代码、装依赖、跑起来
|
||||
|
||||
```bash
|
||||
@@ -61,13 +57,13 @@ cd SnowLuma
|
||||
# 2. 切到 dev 分支(所有开发都基于 dev,不是 main)
|
||||
git checkout dev
|
||||
|
||||
# 3. 按锁文件安装依赖
|
||||
pnpm install --frozen-lockfile
|
||||
# 3. 安装依赖
|
||||
pnpm install
|
||||
|
||||
# 4. 跑类型检查,确认环境 OK
|
||||
pnpm typecheck
|
||||
|
||||
# 5. 跑全工作区测试
|
||||
# 5. 跑测试
|
||||
pnpm test
|
||||
|
||||
# 6. 启动开发模式
|
||||
@@ -100,17 +96,14 @@ git checkout -b fix/onebot-mention-encoding
|
||||
- **写测试**:修 bug 时优先写一个能复现该 bug 的测试,确认它会 fail,再让它 pass。新增功能至少补上 happy path 的测试。
|
||||
- **不要添加无意义的注释**:标识符已经说清楚的事情不需要再写一遍。注释应当解释"为什么",而不是"做了什么"。
|
||||
|
||||
提交之前请运行与 PR CI 相同的验证入口:
|
||||
提交之前请本地跑一遍:
|
||||
|
||||
```bash
|
||||
pnpm typecheck
|
||||
pnpm lint
|
||||
pnpm test
|
||||
pnpm run build:all
|
||||
```
|
||||
|
||||
`pnpm test` 会运行所有声明了测试脚本的工作区包;只验证 Core 时可使用
|
||||
`pnpm test:core`。CI 会重新执行上述完整检查。
|
||||
CI 上跑的是同一套检查,本地通过几乎能保证 CI 通过。
|
||||
|
||||
### 3. 提交信息
|
||||
|
||||
@@ -292,13 +285,3 @@ git push origin v1.7.0 # → 仅触发 release.yml
|
||||
- 如果只是想确认"我这么改 OK 吗",欢迎开 draft PR,先把代码亮出来再讨论。
|
||||
|
||||
感谢你愿意花时间贡献 SnowLuma —— 这个项目能走多远,取决于你们每一个人。❄️
|
||||
|
||||
## 贡献的许可 / Licensing of contributions
|
||||
|
||||
当你提交 PR,即表示你的贡献按本项目的 [`LICENSE`](LICENSE)(SnowLuma 源码可见非商业许可)授权,且你声明你有权这么做、贡献为你的原创(若含第三方材料,请在 PR 中显著标注其来源与许可证)。
|
||||
|
||||
**你保留对自己贡献的版权**,同时**授予 SnowLumaDevs 一项永久、全球、免费、不可撤销、可再许可(sublicensable)的许可**,可使用、复制、修改、分发你的贡献并基于其制作衍生作品,**包括以本项目非商业许可之外的其他条款(含商业条款)再许可与分发**——以便项目方无需逐一回头征求同意,即可在获授权的商业场景中使用社区贡献。
|
||||
|
||||
By opening a PR, you agree your contribution is licensed under the project's [`LICENSE`](LICENSE); you represent that you have the right to submit it and that it is your own work (clearly identify any third-party material in the PR).
|
||||
|
||||
**You retain copyright in your contribution** and additionally grant SnowLumaDevs a **perpetual, worldwide, royalty-free, irrevocable, sublicensable license** to use, reproduce, modify, distribute, and create derivative works of your contribution, **including the right to relicense and distribute it under terms other than this project's non-commercial license (including commercial terms)** — so the project can use community contributions in authorized commercial scenarios without seeking each contributor's consent again.
|
||||
|
||||
92
EULA.md
92
EULA.md
@@ -1,92 +0,0 @@
|
||||
# SnowLuma 最终用户许可协议(EULA)/ End-User License Agreement
|
||||
|
||||
- **生效日期 / Effective date:** 2026-07-21
|
||||
- **版本 / Version:** 1.1
|
||||
- **许可方 / Licensor:** SnowLumaDevs(联系方式 / Contact: motricseven@foxmail.com)
|
||||
|
||||
> 本协议以中文与英文两种语言提供。如两版本有冲突,**以中文版本为准**。
|
||||
> This Agreement is provided in Chinese and English. **In case of any conflict, the Chinese version prevails.**
|
||||
|
||||
---
|
||||
|
||||
## 中文版
|
||||
|
||||
### 1. 定义与接受
|
||||
1.1 "**本软件**"指 SnowLuma 软件及其官方发行包,包括可执行文件、原生模块(`snowluma-*.node`)、文档及相关组件。
|
||||
1.2 "**您**"指下载、安装、运行或以其他方式使用本软件的个人或实体。
|
||||
1.3 下载、安装、运行或使用本软件,即表示您已阅读、理解并同意受本协议约束。**若您不同意本协议,请勿使用本软件并删除其全部副本。**
|
||||
|
||||
### 2. 授权范围
|
||||
2.1 本软件的**源代码与资源**(不含第 5 条所述专有组件及第三方组件)依据随附的 [`LICENSE`](LICENSE)——**SnowLuma 源码可见非商业许可(SnowLuma Source-Available Non-Commercial License)**——授权。
|
||||
2.2 `LICENSE` 仅授予其中明确列明的权利,包括查看、学习、个人或其他非商业使用、非商业自托管,以及在规定条件下进行修改或再分发。**任何商业使用,以及公开发布修改版或衍生版,均须事先取得著作权人的书面授权。**
|
||||
2.3 本协议是针对**官方发行包(二进制)**的补充条款,就接受方式、可接受使用、免责、专有组件、终止及争议解决等事项作出约定;本协议不扩大、替代或暗示授予 `LICENSE` 未明确授予的权利。
|
||||
2.4 专有组件(见第 5 条)不属于源码许可范围,仅按 `LICENSE` 第 5 条及本协议允许的方式使用。
|
||||
2.5 就源代码与资源的许可范围而言,以 `LICENSE` 为准;就官方发行包中的专有组件及二进制特有事项而言,以本协议为准。另行签署或出具的书面商业授权,仅在其明确约定的主体、用途、范围、数量及期限内优先适用。
|
||||
|
||||
### 3. 免责声明
|
||||
3.1 **非官方、无隶属**:本软件是独立的第三方互操作性项目,与腾讯公司(Tencent)及 QQ **无任何隶属、合作、授权或背书关系**。"QQ""腾讯"等名称及标识为其各自所有者的商标。
|
||||
3.2 **用途**:除非事先取得书面商业授权,本软件仅供 `LICENSE` 允许的**个人或其他非商业用途**使用,包括学习、研究、技术互操作与非商业自托管。
|
||||
3.3 **合规义务**:您须自行确保对本软件的使用符合一切适用法律法规,以及您所接入平台的规定(包括但不限于《QQ 用户协议》与相关服务条款)。
|
||||
3.4 **按"现状"提供**:本软件按"**现状(AS-IS)**"及"**现有(AS-AVAILABLE)**"提供,不附带任何明示或默示的担保,包括但不限于对适销性、特定用途适用性、不侵权、可用性、准确性或不中断的担保。
|
||||
3.5 **责任限制**:在适用法律允许的最大范围内,对于因使用或无法使用本软件而导致的任何直接、间接、偶然、特殊、惩罚性或后果性损害(包括但不限于账号封禁或限制、数据丢失、利润或业务损失、服务中断),SnowLumaDevs **概不承担责任**。
|
||||
3.6 **风险自负**:您理解,使用非官方协议工具接入第三方平台**可能违反该平台条款并导致账号风险**,您**自愿承担**该等风险。
|
||||
|
||||
### 4. 可接受使用
|
||||
您**不得**将本软件用于:(a) 任何违法犯罪活动;(b) 未经授权访问、干扰或破坏任何系统或网络;(c) 发送垃圾信息、实施骚扰、欺诈或传播恶意内容;(d) 侵犯他人隐私、知识产权或其他合法权益;(e) 任何违反所接入平台服务条款的行为。
|
||||
|
||||
### 5. 专有组件
|
||||
5.1 本软件可能包含或依赖**专有组件**,包括但不限于 SnowLuma 原生附加组件(如 `snowluma-*.node`、`snowluma-*.dll`、`snowluma-*.so`),以及其中可能包含的授权、激活或技术保护措施。
|
||||
5.2 此类专有组件不属于 `LICENSE` 所授权的源代码与资源,仅以随本软件提供的预编译形式按本条款授权使用;本协议不授予其源代码权利。
|
||||
5.3 除适用法律强制性规定明确允许外,您不得对专有组件进行逆向工程、反编译或反汇编,亦不得规避、破解或绕过其授权或激活机制。
|
||||
5.4 除事先取得著作权人的书面授权外,您仅可为 `LICENSE` 允许的非商业用途,以专有组件随本软件提供的形式运行该组件;不得复制、修改、单独再分发或再许可该组件。将其并入第三方安装包或 Docker 镜像、通过自动化脚本部署,或者将其用于任何商业用途,均须事先取得书面授权。
|
||||
|
||||
### 6. 终止
|
||||
若您违反本协议或适用的 `LICENSE` 条款,相关授权将依各自的终止条款自动终止。终止后,您应停止使用官方发行包并删除其中的专有组件;源代码与资源的后续处理依 `LICENSE` 执行。任何单独书面商业授权的终止及终止后处理,以该授权文件的明确约定为准。
|
||||
|
||||
### 7. 适用法律与争议解决
|
||||
本协议的订立、效力、解释、履行及争议解决,均适用**中华人民共和国大陆地区法律**(不含其冲突法规则)。因本协议引起或与之相关的任何争议,双方应首先友好协商解决;协商不成的,任何一方可向**有管辖权的人民法院**提起诉讼。
|
||||
|
||||
### 8. 协议的变更
|
||||
SnowLumaDevs 可不时更新本协议。更新后的版本将随发行包发布并注明生效日期。在更新生效后继续使用本软件,即视为您接受更新后的条款。
|
||||
|
||||
---
|
||||
|
||||
## English Version
|
||||
|
||||
### 1. Definitions and Acceptance
|
||||
1.1 "**Software**" means the SnowLuma software and its official distribution packages, including executables, native modules (`snowluma-*.node`), documentation, and related components.
|
||||
1.2 "**You**" means the individual or entity that downloads, installs, runs, or otherwise uses the Software.
|
||||
1.3 By downloading, installing, running, or using the Software, you acknowledge that you have read, understood, and agree to be bound by this Agreement. **If you do not agree, do not use the Software and delete all copies.**
|
||||
|
||||
### 2. Scope of License
|
||||
2.1 The **source code and assets** of the Software (excluding the Proprietary Components described in Section 5 and third-party components) are licensed under the accompanying [`LICENSE`](LICENSE), the **SnowLuma Source-Available Non-Commercial License**.
|
||||
2.2 The `LICENSE` grants only the rights expressly stated in it, including viewing, studying, personal or other Non-Commercial use, Non-Commercial self-hosting, and modification or redistribution subject to its conditions. **Any Commercial Use, and any public release of a modified or derivative version, requires the copyright holder's prior written authorization.**
|
||||
2.3 This Agreement provides **supplemental terms for official binary distribution packages**, addressing acceptance, acceptable use, disclaimers, Proprietary Components, termination, and dispute resolution. It does not expand, replace, or imply any right not expressly granted by the `LICENSE`.
|
||||
2.4 Proprietary Components (Section 5) are outside the scope of the source license and may be used only as permitted by Section 5 of the `LICENSE` and this Agreement.
|
||||
2.5 The `LICENSE` controls the scope of rights in the source code and assets; this Agreement controls Proprietary Components in official distribution packages and matters specific to those binaries. A separate written commercial authorization controls only within the licensee, purpose, scope, quantity, and term that it expressly identifies.
|
||||
|
||||
### 3. Disclaimers
|
||||
3.1 **Not official; no affiliation.** The Software is an independent, third-party interoperability project and has **no affiliation, partnership, authorization, or endorsement relationship** with Tencent or QQ. "QQ", "Tencent", and related marks belong to their respective owners.
|
||||
3.2 **Purpose.** Unless prior written commercial authorization has been obtained, the Software may be used only for **personal or other Non-Commercial purposes** permitted by the `LICENSE`, including study, research, technical interoperability, and Non-Commercial self-hosting.
|
||||
3.3 **Compliance.** You are responsible for ensuring that your use complies with all applicable laws and with the terms of any platform you connect to (including the QQ User Agreement and related terms of service).
|
||||
3.4 **AS-IS.** The Software is provided "**AS IS**" and "**AS AVAILABLE**", without warranties of any kind, express or implied, including merchantability, fitness for a particular purpose, non-infringement, availability, accuracy, or uninterrupted operation.
|
||||
3.5 **Limitation of liability.** To the maximum extent permitted by law, SnowLumaDevs shall **not be liable** for any direct, indirect, incidental, special, punitive, or consequential damages (including account suspension or restriction, data loss, lost profits or business, or service interruption) arising from use of or inability to use the Software.
|
||||
3.6 **Assumption of risk.** You understand that using an unofficial protocol tool to connect to a third-party platform **may violate that platform's terms and carry account risk**, which you **voluntarily assume**.
|
||||
|
||||
### 4. Acceptable Use
|
||||
You shall **not** use the Software for: (a) any unlawful activity; (b) unauthorized access to, interference with, or disruption of any system or network; (c) spam, harassment, fraud, or malicious content; (d) infringement of others' privacy, intellectual-property, or other lawful rights; or (e) any conduct that violates the terms of service of a connected platform.
|
||||
|
||||
### 5. Proprietary Components
|
||||
5.1 The Software may include or depend on **Proprietary Components**, including but not limited to SnowLuma native addons such as `snowluma-*.node`, `snowluma-*.dll`, and `snowluma-*.so`, and any licensing, activation, or technical-protection measures they may contain.
|
||||
5.2 Such Proprietary Components are outside the source code and assets licensed by the `LICENSE` and are provided only in precompiled form with the Software for use under this Section. This Agreement grants no right to their source code.
|
||||
5.3 Except to the extent expressly permitted by mandatory applicable law, you may not reverse engineer, decompile, or disassemble the Proprietary Components, nor circumvent, crack, or bypass their licensing or activation mechanisms.
|
||||
5.4 Unless the copyright holder has given prior written authorization, you may run a Proprietary Component only as supplied with the Software and only for Non-Commercial use permitted by the `LICENSE`; you may not reproduce, modify, redistribute it separately, or relicense it. Incorporating it into a third-party installer or Docker image, deploying it through an automated script, or using it for any Commercial Use requires prior written authorization.
|
||||
|
||||
### 6. Termination
|
||||
If you breach this Agreement or the applicable `LICENSE`, the relevant rights terminate automatically under their respective termination provisions. Upon termination, you must cease using the official distribution package and delete its Proprietary Components; further handling of the source code and assets is governed by the `LICENSE`. Termination of any separate written commercial authorization, and the parties' post-termination rights and obligations, are governed by that authorization's express terms.
|
||||
|
||||
### 7. Governing Law and Disputes
|
||||
This Agreement is governed by the laws of the **mainland of the People's Republic of China** (excluding its conflict-of-laws rules). Any dispute arising out of or relating to this Agreement shall first be resolved through good-faith negotiation; failing that, either party may bring an action before a **court of competent jurisdiction**.
|
||||
|
||||
### 8. Changes
|
||||
SnowLumaDevs may update this Agreement from time to time. Updated versions will be published with the distribution package and bear an effective date. Continued use after an update takes effect constitutes acceptance of the updated terms.
|
||||
131
LICENSE
131
LICENSE
@@ -1,131 +0,0 @@
|
||||
SnowLuma Source-Available Non-Commercial License
|
||||
SnowLuma 源码可见非商业许可
|
||||
|
||||
Version 1.0 · 2026-06-19
|
||||
Copyright (C) 2026 SnowLumaDevs
|
||||
Contact: motricseven@foxmail.com
|
||||
|
||||
中英文如有冲突,以中文为准。
|
||||
In case of any conflict between the Chinese and English text, the Chinese
|
||||
version prevails.
|
||||
|
||||
This is NOT an open-source license as defined by the Open Source Initiative:
|
||||
it restricts commercial use and the public release of modifications. The
|
||||
source is published for transparency, study, and non-commercial self-hosting.
|
||||
本许可不是 OSI 定义的开源许可:它限制商业用途与修改版的公开发布。源码公开
|
||||
仅用于透明、学习与非商业的自托管。
|
||||
|
||||
===============================================================================
|
||||
1. Definitions / 定义
|
||||
===============================================================================
|
||||
- "Software" / "本软件": the SnowLuma source code and assets in this
|
||||
repository, excluding the Native Addon (defined below) and any third-party
|
||||
components.
|
||||
- "You" / "你": any individual or entity exercising rights under this License.
|
||||
- "Commercial Use" / "商业用途": any use primarily intended for or directed
|
||||
toward commercial advantage or monetary compensation. This includes, without
|
||||
limitation, selling or reselling the Software; offering paid hosting,
|
||||
deployment, setup, or operation services based on the Software; bundling it
|
||||
into a paid product or service; or running it to provide a service for a fee.
|
||||
包括但不限于:出售或转售本软件;提供基于本软件的付费托管、部署、代搭、代运营
|
||||
服务;将其并入付费产品或服务;或以收费方式运行本软件对外提供服务。
|
||||
- "Native Addon" / "原生附加组件": the SnowLuma native binary components shipped
|
||||
with the Software (e.g. `snowluma-*.node`, `snowluma-*.dll`, `snowluma-*.so`).
|
||||
These are a separate, proprietary component and are NOT licensed under this
|
||||
License — see Section 5.
|
||||
|
||||
===============================================================================
|
||||
2. Grant / 授权
|
||||
===============================================================================
|
||||
Subject to the conditions and restrictions below, the copyright holder grants
|
||||
You a worldwide, royalty-free, non-exclusive, non-transferable, revocable
|
||||
license to:
|
||||
在下列条件与限制下,著作权人授予你一项全球、免费、非独占、不可转让、可撤销的
|
||||
许可,允许你:
|
||||
(a) view and study the Software; 查看与学习本软件;
|
||||
(b) use and run the Software for personal or other Non-Commercial purposes;
|
||||
为个人或其他非商业目的使用与运行本软件;
|
||||
(c) modify the Software for Your own Non-Commercial use; 为自己的非商业使用
|
||||
修改本软件;
|
||||
(d) redistribute the Software under the conditions in Section 3.
|
||||
在第 3 条的条件下再分发本软件。
|
||||
|
||||
===============================================================================
|
||||
3. Redistribution Conditions / 再分发条件
|
||||
===============================================================================
|
||||
You may redistribute the Software (modified or unmodified) ONLY if ALL of the
|
||||
following are met. 仅当同时满足以下全部条件时,你方可再分发本软件(无论是否修改):
|
||||
(a) it is Non-Commercial; 属非商业性质;
|
||||
(b) the complete text of this License is included; 附带本许可的完整文本;
|
||||
(c) all copyright, attribution, and notices are retained unaltered;
|
||||
保留全部著作权、署名与声明,且不得改动;
|
||||
(d) PUBLIC release of a modified or derivative version requires the prior
|
||||
written permission of the copyright holder. Private, non-public
|
||||
modifications for Your own Non-Commercial use are permitted.
|
||||
公开发布修改版或衍生版,须事先获得著作权人书面许可;为你自己非商业使用
|
||||
而作的、不公开的修改则被允许。
|
||||
|
||||
===============================================================================
|
||||
4. Restrictions / 限制
|
||||
===============================================================================
|
||||
(a) Commercial Use of the Software in any form is PROHIBITED without the
|
||||
prior written authorization of the copyright holder.
|
||||
未经著作权人事先书面授权,禁止以任何形式对本软件进行商业使用。
|
||||
(b) You may not develop, publish, or distribute another project based on the
|
||||
Software without the prior written authorization of the copyright holder.
|
||||
未经著作权人事先书面授权,不得基于本软件开发、发布或分发另一个项目。
|
||||
(c) You may not remove, obscure, or alter any copyright, attribution, license,
|
||||
or notice. 不得移除、遮蔽或更改任何著作权、署名、许可或声明。
|
||||
|
||||
===============================================================================
|
||||
5. Native Addon / 原生附加组件
|
||||
===============================================================================
|
||||
The Native Addon is proprietary and is NOT covered by this License. It is
|
||||
distributed only as a precompiled binary bundled with the Software. No rights
|
||||
are granted to it other than to run it as bundled for the Non-Commercial use
|
||||
permitted above; in particular, no right to reverse engineer, reproduce,
|
||||
modify, redistribute separately, or relicense it is granted.
|
||||
原生附加组件为专有组件,不在本许可范围内,仅以随本软件分发的预编译二进制形式提供。
|
||||
除按上文允许的非商业用途以其随附形式运行外,不授予任何权利;尤其不授予对其进行逆向、
|
||||
复制、修改、单独再分发或再许可的权利。
|
||||
|
||||
===============================================================================
|
||||
6. Additional Permissions / 额外授权
|
||||
===============================================================================
|
||||
Any use not granted by this License — including Commercial Use and the public
|
||||
release of derivative works — requires prior written permission, which must be
|
||||
requested from and granted by the copyright holder (Contact above).
|
||||
本许可未授予的任何用途——包括商业使用及公开发布衍生作品——均须事先取得著作权人的
|
||||
书面许可(见上方联系方式)。
|
||||
|
||||
===============================================================================
|
||||
7. Third-Party Components / 第三方组件
|
||||
===============================================================================
|
||||
Third-party code and components retain their own original licenses, which
|
||||
govern those parts. 第三方代码与组件遵循其各自的原始许可,并以其许可为准。
|
||||
|
||||
===============================================================================
|
||||
8. Termination / 终止
|
||||
===============================================================================
|
||||
Any breach of this License automatically terminates the rights granted to You
|
||||
under it. 任何违反本许可的行为将自动终止你依本许可获得的权利。
|
||||
|
||||
===============================================================================
|
||||
9. Disclaimer / 免责声明
|
||||
===============================================================================
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
|
||||
LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
||||
OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
本软件按“现状”提供,不附带任何明示或默示的担保,包括但不限于适销性、特定用途
|
||||
适用性及不侵权的担保。在任何情况下,作者或著作权人均不对因本软件或其使用所引起
|
||||
的任何索赔、损害或其他责任负责。
|
||||
|
||||
===============================================================================
|
||||
10. Governing Law / 适用法律
|
||||
===============================================================================
|
||||
This License is governed by the laws of the mainland of the People's Republic
|
||||
of China, excluding its conflict-of-laws rules.
|
||||
本许可适用中华人民共和国大陆地区法律(不含其冲突法规则)。
|
||||
149
PRIVACY.md
149
PRIVACY.md
@@ -1,149 +0,0 @@
|
||||
# SnowLuma 隐私与数据处理说明 / Privacy & Data Handling Notice
|
||||
|
||||
- **生效日期 / Effective date:** 2026-06-19
|
||||
- **版本 / Version:** 1.0
|
||||
- **责任主体 / Provider:** SnowLumaDevs(联系方式 / Contact: motricseven@foxmail.com)
|
||||
|
||||
> 本说明以中文与英文两种语言提供。如有冲突,**以中文版本为准**。
|
||||
> Provided in Chinese and English. **In case of conflict, the Chinese version prevails.**
|
||||
|
||||
---
|
||||
|
||||
## 中文版
|
||||
|
||||
### 1. 概述
|
||||
SnowLuma 是一款**自托管**软件:它运行在**您自己的设备或服务器**上。**SnowLumaDevs(作者方)默认不收集、不接收、不存储您的任何个人数据**。本软件**不包含**任何需要联网激活、或向作者方回传信息的授权机制。
|
||||
本说明唯一例外的数据外发情形,是第 4、5 条所述的两种,且其中遥测受严格限制(第 5 条)。
|
||||
|
||||
### 2. 本软件在您设备上存储的数据
|
||||
为实现功能,本软件会在您的设备本地(如 SQLite 数据库、配置与日志文件)存储以下类别的数据。**这些数据保存在您本地、由您掌控,作者方无法访问:**
|
||||
- **账号与登录凭据**:所登录的 QQ 账号信息、会话/令牌、WebUI 登录口令(以**加盐 scrypt 哈希**形式存储,不保存明文)。
|
||||
- **关系数据**:好友、群组及成员的列表与资料。
|
||||
- **消息数据**:为实现协议转换而处理或缓存的消息(视您的配置而定)。
|
||||
- **运行配置与日志**:适配器配置、运行日志等。
|
||||
|
||||
> 说明:因 SnowLuma 是 QQ 协议工具,上述本地数据**必然**包含 QQ 账号及联系人信息。这与第 5 条"遥测绝不采集 QQ 账号/联系人"并不矛盾——本地存储 ≠ 对外传输。
|
||||
|
||||
### 3. 您作为数据控制者的责任
|
||||
当您运行本软件处理您 QQ 联系人、群成员等他人的个人信息时,**您是该等个人信息的"数据控制者/处理者"**,须自行就该等处理承担合规责任(包括取得必要同意、保障安全、响应数据主体请求等)。作者方仅提供软件工具,不参与您的数据处理活动。
|
||||
|
||||
### 4. 数据离开您设备的唯一途径
|
||||
除以下两种情形外,本软件不会将您的数据传输至任何外部目的地:
|
||||
1. **您自行配置的通知 / Webhook**:当您主动配置通知渠道(如 Webhook)时,相应内容会按**您填写的地址与设置**外发。目的地与内容由您完全掌控,作者方不经手。
|
||||
2. **匿名遥测**:见第 5 条。
|
||||
|
||||
### 5. 遥测(Telemetry)
|
||||
**模式:默认开启(opt-out)。** 您可随时关闭(见 5.3)。
|
||||
|
||||
#### 5.1 采集内容(仅匿名、聚合,无法定位到个人)
|
||||
- 应用版本、操作系统与 CPU 架构、Node.js 版本;
|
||||
- 启动次数、功能使用计数(例如启用了哪些适配器/命令,**不含其参数或内容**);
|
||||
- 匿名化的崩溃栈与错误类型。
|
||||
|
||||
#### 5.2 绝不采集(显式负面清单)
|
||||
本遥测**在任何情况下都不会**采集或传输:
|
||||
- **QQ 账号 / UIN,及好友、群、成员的身份信息**;
|
||||
- **消息内容或其元数据**、昵称、头像;
|
||||
- 手机号、邮箱或任何联系方式;
|
||||
- 凭据、令牌、密码;
|
||||
- 用于身份画像的精确 IP 地址(若服务端在传输层偶然可见 IP,将即时丢弃、不入库、不进行关联);
|
||||
- 任何可直接或间接定位到自然人的标识。
|
||||
|
||||
#### 5.3 如何关闭与告知
|
||||
- **首次运行提示**:软件首次运行时会在控制台与 WebUI 一次性告知遥测已默认开启及关闭方式。
|
||||
- **一键关闭**:可通过环境变量 `SNOWLUMA_TELEMETRY=0`、配置项或 WebUI 开关随时关闭,关闭后即刻停止采集。
|
||||
|
||||
#### 5.4 用途、共享与保留
|
||||
遥测数据**仅用于改进本软件**,**不向任何第三方出售或共享**,仅以匿名聚合形式保留必要期限。
|
||||
|
||||
#### 5.5 生效状态(重要)
|
||||
本条款完整描述了 SnowLuma 的遥测机制,但**仅对实际包含遥测代码的发行版生效**。
|
||||
> **当前生效状态(截至 2026-06-17)**:公开发行版**尚未包含**遥测代码,故本条款目前**处于未生效状态**。一旦某一发行版引入遥测,将在该版本的发布说明中明确告知,并使本条款对该版本生效。
|
||||
|
||||
### 6. 数据安全与保留
|
||||
本地数据的安全与保留由您(运营者)控制。建议您妥善保护设备访问权限、定期更新 WebUI 口令。
|
||||
|
||||
### 7. 第三方组件
|
||||
本软件可能捆绑第三方组件(如用于音视频处理的 FFmpeg)。此类组件**在您本地运行**、用于处理本地数据,**不向作者方或第三方外发**数据。
|
||||
|
||||
### 8. 未成年人
|
||||
本软件面向开发者与技术用户,**不面向未成年人**,作者方不会有意收集未成年人信息。
|
||||
|
||||
### 9. 您的权利
|
||||
由于作者方默认不持有您的任何个人数据,与您个人信息相关的访问、更正、删除等权利,应在**您本地的数据范围内**由您自行行使。如遥测启用且您有疑问,可通过第 10 条联系我们。
|
||||
|
||||
### 10. 联系方式
|
||||
隐私相关问询:**motricseven@foxmail.com**。
|
||||
|
||||
### 11. 变更
|
||||
本说明可不时更新,更新版本将注明生效日期。涉及遥测的重大变更将在发布说明中显著告知。
|
||||
|
||||
---
|
||||
|
||||
## English Version
|
||||
|
||||
### 1. Overview
|
||||
SnowLuma is **self-hosted**: it runs on **your own device or server**. **By default, SnowLumaDevs (the authors) collect, receive, and store none of your data.** The Software contains **no** activation that requires network access or transmits information back to the authors. The only data that ever leaves your device is described in Sections 4 and 5, and telemetry is strictly limited (Section 5).
|
||||
|
||||
### 2. Data the Software Stores on Your Device
|
||||
To function, the Software stores the following categories of data locally (e.g., in a SQLite database, configuration, and log files). **This data stays on your device under your control; the authors cannot access it:**
|
||||
- **Account & credentials:** the signed-in QQ account, session/tokens, and the WebUI login password (stored as a **salted scrypt hash**, never in plaintext).
|
||||
- **Relationship data:** lists and profiles of friends, groups, and members.
|
||||
- **Message data:** messages processed or cached for protocol conversion (depending on your configuration).
|
||||
- **Runtime configuration & logs.**
|
||||
|
||||
> Note: Because SnowLuma is a QQ protocol tool, this local data **necessarily** includes QQ account and contact information. This does not conflict with Section 5 ("telemetry never collects QQ account/contacts") — local storage ≠ outbound transmission.
|
||||
|
||||
### 3. You Are the Data Controller
|
||||
When you run the Software to process the personal information of your QQ contacts, group members, or other individuals, **you are the data controller/processor** for that information and are responsible for compliance (obtaining any necessary consent, securing the data, responding to data-subject requests). The authors merely provide a software tool and take no part in your processing.
|
||||
|
||||
### 4. The Only Ways Data Leaves Your Device
|
||||
The Software transmits your data to an external destination only in these two cases:
|
||||
1. **Notifications / webhooks you configure:** when you set up a notification channel (e.g., a webhook), the relevant content is sent to **the address and settings you provide**. You fully control the destination and content; the authors are not involved.
|
||||
2. **Anonymous telemetry:** see Section 5.
|
||||
|
||||
### 5. Telemetry
|
||||
**Mode: ON by default (opt-out).** You can disable it at any time (see 5.3).
|
||||
|
||||
#### 5.1 What is collected (anonymous, aggregate, non-identifying only)
|
||||
- Application version, OS and CPU architecture, Node.js version;
|
||||
- Launch counts and feature-usage counts (e.g., which adapters/commands are enabled — **never their arguments or content**);
|
||||
- Anonymized crash stacks and error types.
|
||||
|
||||
#### 5.2 Never collected (explicit negative list)
|
||||
Telemetry will **never, under any circumstances**, collect or transmit:
|
||||
- **QQ account / UIN, or the identity of any friend, group, or member**;
|
||||
- **Message content or metadata**, nicknames, avatars;
|
||||
- Phone numbers, emails, or any contact details;
|
||||
- Credentials, tokens, passwords;
|
||||
- Precise IP addresses used for profiling (any IP incidentally visible at the transport layer is discarded immediately, not stored, not correlated);
|
||||
- Any identifier that could directly or indirectly identify a natural person.
|
||||
|
||||
#### 5.3 How to disable; notice
|
||||
- **First-run notice:** on first run the Software gives a one-time notice in the console and WebUI that telemetry is on by default and how to disable it.
|
||||
- **One switch off:** disable any time via the `SNOWLUMA_TELEMETRY=0` environment variable, a config option, or the WebUI toggle; collection stops immediately.
|
||||
|
||||
#### 5.4 Use, sharing, retention
|
||||
Telemetry is used **only to improve the Software**, is **never sold or shared with any third party**, and is retained only in anonymous aggregate form for as long as necessary.
|
||||
|
||||
#### 5.5 Effective status (important)
|
||||
This Section fully describes SnowLuma's telemetry mechanism but is **effective only for builds that actually contain telemetry code.**
|
||||
> **Current status (as of 2026-06-17):** public releases **do not yet contain** telemetry code, so this Section is currently **not in effect**. If a release introduces telemetry, its release notes will say so and this Section will take effect for that release.
|
||||
|
||||
### 6. Security & Retention
|
||||
Security and retention of local data are under your (the operator's) control. Protect device access and rotate the WebUI password regularly.
|
||||
|
||||
### 7. Third-Party Components
|
||||
The Software may bundle third-party components (such as FFmpeg for media processing). These run **locally** on your device to process local data and **send nothing** to the authors or third parties.
|
||||
|
||||
### 8. Minors
|
||||
The Software targets developers and technical users, is **not directed to minors**, and the authors do not knowingly collect minors' information.
|
||||
|
||||
### 9. Your Rights
|
||||
Because the authors hold none of your personal data by default, rights of access, correction, and deletion are exercised by you **over the data on your own device**. If telemetry is enabled and you have questions, contact us (Section 10).
|
||||
|
||||
### 10. Contact
|
||||
Privacy inquiries: **motricseven@foxmail.com**.
|
||||
|
||||
### 11. Changes
|
||||
This Notice may be updated from time to time; updated versions bear an effective date. Material changes affecting telemetry will be prominently noted in release notes.
|
||||
226
README.md
226
README.md
@@ -1,179 +1,131 @@
|
||||
<h1 align="center">❄️ SnowLuma</h1>
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/readme/hero.svg" width="100%" alt="SnowLuma 将 QQ 原生会话桥接到 OneBot、WebUI 与自动化工具" />
|
||||
<i>Next Remote Protocol Framework.</i>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="最新版本" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/actions/workflows/dev-build.yml"><img alt="构建状态" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/dev-build.yml?branch=dev&style=flat-square&label=build"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="SnowLuma SDK 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=sdk&color=287fb8"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/mcp"><img alt="SnowLuma MCP 版本" src="https://img.shields.io/npm/v/%40snowluma%2Fmcp?style=flat-square&label=mcp&color=7658c7"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="GitHub Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="Release" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/actions"><img alt="Build" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/release.yml?branch=main&style=flat-square&label=build"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="@snowluma/sdk" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=%40snowluma%2Fsdk&color=cb3837"></a>
|
||||
<a href="https://www.npmjs.com/package/@snowluma/ui"><img alt="@snowluma/ui" src="https://img.shields.io/npm/v/%40snowluma%2Fui?style=flat-square&label=%40snowluma%2Fui&color=cb3837"></a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="#快速开始">快速开始</a> ·
|
||||
<a href="#运行链路">运行链路</a> ·
|
||||
<a href="./docs/onebot-actions.md">动作参考</a> ·
|
||||
<a href="./packages/sdk/README.md">SDK</a> ·
|
||||
<a href="./packages/mcp/README.md">MCP</a> ·
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/issues">问题反馈</a>
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/releases">Releases</a> ·
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/issues">Issues</a> ·
|
||||
<a href="https://qm.qq.com/q/g3UMLpWALe">QQ 群</a> ·
|
||||
<a href="https://t.me/napcatqq">Telegram</a>
|
||||
</p>
|
||||
|
||||
SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时。它把 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,并通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口;每个账号拥有独立会话,适合机器人开发、自动化与协议研究。
|
||||
---
|
||||
|
||||
> [!CAUTION]
|
||||
> **使用边界**:SnowLuma 是独立的第三方互操作项目,**与腾讯 / QQ 无任何隶属或授权关系**。本项目仅供学习与技术研究,请遵守《QQ 用户协议》及适用法律;软件按“现状”提供、不附带任何担保,使用风险自负。详见 [`EULA.md`](EULA.md)。
|
||||
>
|
||||
> **Disclaimer**: SnowLuma is an independent third-party interoperability project with no affiliation with or endorsement by Tencent / QQ. It is provided for study and research only, “as is” and without warranty. See [`EULA.md`](EULA.md).
|
||||
## 简介
|
||||
|
||||
## 运行链路
|
||||
SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/readme/runtime-map.svg" width="100%" alt="QQ 会话经过协议桥接与 OneBot 标准化后连接到 WebSocket、HTTP、WebUI、SDK 和 MCP" />
|
||||
</p>
|
||||
项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。
|
||||
|
||||
SnowLuma 将会话接入、协议解析、身份映射、OneBot 转换和网络适配拆成清晰边界。多个 QQ 账号可以并行运行,同时保持独立状态、日志与连接配置。
|
||||
## 特性
|
||||
|
||||
## 核心能力
|
||||
|
||||
| 场景 | SnowLuma 提供 |
|
||||
| --- | --- |
|
||||
| OneBot 接入 | OneBot v11 动作与事件,支持 WebSocket 服务端 / 客户端、HTTP 服务端 / 上报及同端口复用 |
|
||||
| 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及 JSON / XML 卡片等常见消息元素 |
|
||||
| 多账号运行 | 每个 QQ 账号独立维护会话、身份映射、消息存储与网络适配器 |
|
||||
| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试、存储管理、密码管理与可定制总览 |
|
||||
| 开发者工具 | 提供 [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) |
|
||||
| 可观察错误 | 关键解析与执行失败会留下明确上下文,不以静默丢弃掩盖问题 |
|
||||
- **OneBot v11 兼容** —— 涵盖文本、图片、视频、语音、合并转发、戳一戳、Markdown、JSON、XML 等常用消息段。
|
||||
- **多账号并行** —— 同一进程可同时托管多个 QQ 账号,会话彼此独立。
|
||||
- **多种适配器** —— WebSocket Server / WebSocket Client / HTTP Server / HTTP Post,HTTP 服务端同时支持 `application/json` 与 `application/x-www-form-urlencoded`。
|
||||
- **WebUI 管理面板** —— 浏览器登录、密码强度校验、登录限流、SSE 实时日志、配置热更新。
|
||||
- **TypeScript 全链路** —— Bridge / OneBot / SDK / UI 均使用 TypeScript,发布到 npm 的 `@snowluma/sdk` 与 `@snowluma/ui` 可直接供下游应用消费。
|
||||
- **数据持久化** —— 好友、群、群成员等关系数据落 SQLite,跨重启可用。
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 选择发行包
|
||||
|
||||
前往 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载与你的平台匹配的版本:
|
||||
|
||||
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 22.13+;23 系需 23.4+) |
|
||||
| --- | --- | --- |
|
||||
| Windows x64 | `SnowLuma-vX.Y.Z-win-x64.zip` | `SnowLuma-vX.Y.Z-win-x64-lite.zip` |
|
||||
| Linux x64 | `SnowLuma-vX.Y.Z-linux-x64.tar.gz` | `SnowLuma-vX.Y.Z-linux-x64-lite.tar.gz` |
|
||||
| Linux arm64 | `SnowLuma-vX.Y.Z-linux-arm64.tar.gz` | `SnowLuma-vX.Y.Z-linux-arm64-lite.tar.gz` |
|
||||
|
||||
完整版适合直接解压运行;Lite 版只移除了内置 Node.js,其余运行时依赖与 WebUI 静态资源保持一致。
|
||||
|
||||
### 2. 启动 SnowLuma
|
||||
|
||||
Windows 运行 `launcher.bat`。Linux 在解压目录执行:
|
||||
下载预构建发布包:
|
||||
|
||||
```bash
|
||||
chmod +x launcher.sh
|
||||
./launcher.sh
|
||||
# 从 Releases 下载 zip,解压到任意目录
|
||||
./launcher.bat # Windows
|
||||
```
|
||||
|
||||
### 3. 打开 WebUI
|
||||
|
||||
浏览器访问 [`http://localhost:5099`](http://localhost:5099)。初始账号为 `admin`,随机密码会显示在启动日志中;首次登录后,WebUI 会在同一个引导流程中完成协议确认与访问密码设置,随后即可接入已启动的 QQ 进程并配置 OneBot 连接。
|
||||
|
||||
<details>
|
||||
<summary><strong>无人值守部署:通过环境变量确认协议</strong></summary>
|
||||
|
||||
同时设置以下两个变量可跳过 WebUI 首次使用引导中的协议确认步骤:
|
||||
|
||||
```bash
|
||||
SNOWLUMA_ACCEPT_EULA=1
|
||||
SNOWLUMA_ACCEPT_PRIVACY=1
|
||||
```
|
||||
|
||||
两项必须同时设置,且环境变量确认不会写入持久化同意记录。设置变量即表示运营者已阅读并同意 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md)。
|
||||
|
||||
全新无人值守部署还可以使用 `SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD` 预设 WebUI 密码(至少 8 位);由该变量初始化的密码不再要求进入强制修改步骤。已有 `config/webui.json` 时仍以现有凭据为准。
|
||||
|
||||
</details>
|
||||
|
||||
## 可选:登录时补齐云端历史
|
||||
|
||||
WebUI 的账号“通用设置”可开启登录历史补齐,默认关闭,并在下次登录或重启后生效。该功能只把缺失的 QQ 云端漫游消息静默写入 SnowLuma 本地历史库,不重放 OneBot 事件,也不改变 QQ 已读状态。
|
||||
|
||||
花名册预热完成后会等待 30 秒,且进程内一次只为一个账号执行自动补齐。每次登录最多扫描 100 个群和 100 位好友,优先续补本地已知缺口,每类最多处理 3 个会话;每个会话最多读取 20 条消息,自动请求之间至少间隔 2 秒,失败后本次登录不重试。
|
||||
|
||||
## 日志与存储管理
|
||||
|
||||
WebUI 的“系统设置 → 存储管理”可查看受管数据占用、调整日志策略,并清理日志、非活动传输临时文件或离线账号的消息、媒体和表情回应数据库。清理范围固定,不包含配置、凭据或其他文件。
|
||||
|
||||
| 设置 | 默认值 | 环境变量 |
|
||||
| --- | --- | --- |
|
||||
| 日志树总量上限 | 1024 MB | `SNOWLUMA_LOG_MAX_TOTAL_MB` |
|
||||
| 日志保留天数 | 7 天;`0` 表示关闭按日期清理 | `SNOWLUMA_LOG_RETAIN_DAYS` |
|
||||
| 按账号额外写日志 | 关闭 | `SNOWLUMA_LOG_PER_UIN` |
|
||||
|
||||
以上环境变量优先于 `config/runtime.json`,对应字段会在 WebUI 中显示为锁定。`SNOWLUMA_LOG_MAX_MB` 仅控制单个日志分卷大小,不是日志树总量上限。
|
||||
|
||||
文件日志等级可通过 `SNOWLUMA_LOG_FILE_LEVEL` 单独设置为 `debug`、`info`、`success`、`warn` 或 `error`,默认为 `debug`。该启动参数不写入 `config/runtime.json`,也不受 WebUI 实时日志等级影响;TRACE 始终不落盘。
|
||||
|
||||
## 选择接入方式
|
||||
|
||||
| 入口 | 适合场景 | 参考 |
|
||||
| --- | --- | --- |
|
||||
| WebSocket / HTTP | 对接现有 OneBot 机器人框架 | [OneBot 动作参考](docs/onebot-actions.md) |
|
||||
| TypeScript SDK | 编写类型安全的客户端与消息逻辑 | [`packages/sdk`](packages/sdk/README.md) |
|
||||
| MCP | 让支持 MCP 的工具查询或调用 SnowLuma 动作 | [`packages/mcp`](packages/mcp/README.md) |
|
||||
| WebUI | 管理运行状态、日志、账号与连接 | 启动后访问 `http://localhost:5099` |
|
||||
|
||||
## 开发与贡献
|
||||
|
||||
本地开发需要 Node.js 22.13+(23 系需 23.4+)与项目锁定的 pnpm 10.28.0。所有日常开发基于 `dev` 分支:
|
||||
或从源码开发:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/SnowLuma/SnowLuma.git
|
||||
cd SnowLuma
|
||||
git checkout dev
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm typecheck
|
||||
pnpm lint
|
||||
pnpm test
|
||||
pnpm run build:all
|
||||
pnpm install
|
||||
pnpm build
|
||||
pnpm start
|
||||
```
|
||||
|
||||
`pnpm test` 会运行所有声明了常规测试的 workspace;`pnpm test:all` 是兼容别名,`pnpm test:core` 只运行 Core 测试。原生模块测试需单独运行 `pnpm test:native`。`pnpm coverage` 会生成各常规测试 workspace 的覆盖率报告,但不设置覆盖率阻断阈值。
|
||||
WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial credentials: user=admin password=<...>`,登录后请立即修改。
|
||||
若未完成首次改密就关闭进程,下次启动会自动重新生成一个新的随机密码。
|
||||
|
||||
- 先读 [`CONTEXT.md`](CONTEXT.md) 了解模块边界与项目词汇。
|
||||
- 提交代码前阅读 [`CONTRIBUTING.md`](CONTRIBUTING.md) 与 [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md)。
|
||||
- 开发方向与已完成事项见 [`RoadMap.md`](RoadMap.md)。
|
||||
## 工作区
|
||||
|
||||
<details>
|
||||
<summary><strong>主要目录</strong></summary>
|
||||
本仓库使用 pnpm monorepo 管理,各包职责如下:
|
||||
|
||||
| 路径 | 作用 |
|
||||
| 包 | 说明 |
|
||||
| --- | --- |
|
||||
| `packages/protocol` | QQ 协议定义、数据包解析、消息推送与 OIDB 服务 |
|
||||
| `packages/onebot` | OneBot 动作执行、事件转换与网络适配 |
|
||||
| `packages/core` | 运行时编排、QQ 会话桥接与 WebUI 服务端 |
|
||||
| `packages/webui` | React 管理界面 |
|
||||
| `packages/sdk` | 对外发布的 TypeScript SDK |
|
||||
| `packages/mcp` | 面向 MCP 客户端的动作目录与执行入口 |
|
||||
| [`@snowluma/core`](packages/core) | 核心:协议层 / Bridge / OneBot / WebUI 全部在此。 |
|
||||
| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 |
|
||||
| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 |
|
||||
| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 |
|
||||
| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb<N, T>`,Vite 插件在构建时把 `protobuf_encode<T>` / `protobuf_decode<T>` 替换为内联 codec,零运行时反射。 |
|
||||
| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 |
|
||||
| [`webui`](packages/webui) | Web 管理面板前端。 |
|
||||
|
||||
</details>
|
||||
## 架构
|
||||
|
||||
## 使用边界与许可
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A([QQ 客户端])
|
||||
B["协议层<br/><sub>packet pipeline · cmd 分派</sub>"]
|
||||
C["Bridge 层<br/><sub>会话调度 · 花名册缓存 · 消息发送</sub>"]
|
||||
D["OneBot 层<br/><sub>Event Converter · Action Handler</sub>"]
|
||||
E([WS / HTTP / WebUI])
|
||||
|
||||
> [!IMPORTANT]
|
||||
> SnowLuma 使用 **源码可见非商业许可**,**不是 OSI 开源许可**。源码可用于查看、学习、非商业自托管及私下修改;任何商业使用,以及公开发布修改版或衍生版,均需事先取得书面授权。
|
||||
A --> B --> C --> D --> E
|
||||
```
|
||||
|
||||
- 完整条款见 [`LICENSE`](LICENSE)。
|
||||
- 随附的原生附加组件为专有组件,不在源码许可范围内。
|
||||
- 二进制发行包另受 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md) 约束。
|
||||
- 商业授权请联系 `motricseven@foxmail.com`。
|
||||
## 文档
|
||||
|
||||
SnowLuma is source-available for study and non-commercial self-hosting, but it is **not OSI open source**. Commercial use and public distribution of modified or derivative versions require prior written permission. Bundled native components are proprietary and excluded from the source license.
|
||||
- [路线图](RoadMap.md)
|
||||
- [贡献指南](CONTRIBUTING.md)
|
||||
- [行为准则](CODE_OF_CONDUCT.md)
|
||||
|
||||
## 社区与支持
|
||||
## 开发命令
|
||||
|
||||
- [提交问题](https://github.com/SnowLuma/SnowLuma/issues)
|
||||
- [QQ 群](https://qm.qq.com/q/g3UMLpWALe)
|
||||
- [Telegram](https://t.me/napcatqq)
|
||||
```bash
|
||||
pnpm dev # 启动 core dev server
|
||||
pnpm dev:web # 启动 webui dev server
|
||||
pnpm test # 运行 core 测试
|
||||
pnpm typecheck # 全仓库 type check
|
||||
pnpm build:all # 构建 core + sdk + webui
|
||||
```
|
||||
|
||||
## 鸣谢
|
||||
|
||||
项目参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
|
||||
- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。
|
||||
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors"><img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="SnowLuma 贡献者" /></a>
|
||||
</p>
|
||||
## 贡献者
|
||||
|
||||
感谢每一位为 SnowLuma 提交过代码的伙伴。
|
||||
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="Contributors" />
|
||||
</a>
|
||||
|
||||
## Star 趋势
|
||||
|
||||
<a href="https://star-history.com/#SnowLuma/SnowLuma&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## 社区
|
||||
|
||||
- QQ 群:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
|
||||
- 问题反馈:[GitHub Issues](https://github.com/SnowLuma/SnowLuma/issues)
|
||||
|
||||
500
RoadMap.md
500
RoadMap.md
@@ -1,9 +1,491 @@
|
||||
# V2.0.0 前计划
|
||||
- [x] 统一Uid/Uin提供一个Service,并实现Sqlite持久化,群/好友/入群和好友申请 获取新Uid。
|
||||
- [x] 优化Debug体验,实现免打包Debug,同时数据目录正确。(Proton兜底思路改成ts+map提取类型,用于tsx和nodejs,vite正常打包的时候剥离)
|
||||
- [x] 拆分core,架构为Common(公共能力) OneBot(外层封装 协议转换),Core(Api raw能力,基础能力等功能),Bridge(封装和关键解析能力和Event message/sent group/member_add ...)
|
||||
- [x] 剥离ProtocolBuffer定义到单独package。
|
||||
- [x] 整理发送和解析消息链路,提高性能。`packages/{bridge,onebot}/bench/*.bench.ts` 拿到了基线数字。最大瓶颈不在 protobuf 解析(已经 sub-μs),而在两处 SQLite 反复 `db.prepare(sql)` 重 parse —— 把 `node:sqlite`(实验性)换成 `better-sqlite3`(稳定)+ 缓存 prepared statements 后:`group_member_join` 全链路 17.5μs → 4.7μs(**3.7x**),`storeMeta` 17μs → 11μs,`storeEvent` 23μs → 18μs,`findMeta` 5.4μs → 1.3μs(**4x**)。送侧组合 hot path(storeMeta + storeEvent)单条消息 40μs → 29μs。另外干掉 `Buffer.from(pkt.body)` 的冗余 alloc(pkt.body 本来就是 Uint8Array)。`elementsToJson` 同步快路径 / WAL checkpoint 调参 / JSON 序列化替换 等次要优化点保留,待真有 throughput 压力再做。
|
||||
- [x] 对齐NapCat设计采用Api层,挂到ctx,Core与Onebot都这么设计。
|
||||
- [x] Core 侧:13 个 Api 类(message/contacts/groupAdmin/groupFile/groupAlbum/interaction/friend/profile/forward/misc/extras/web)已挂到 `bridge.apis.<area>.method()`,`BridgeInterface` + `actions/*` 全部删除。
|
||||
- [x] OneBot 侧:`ApiActionContext` 砍掉 ~40 个纯转发字段(groupAdmin / groupFile / groupAlbum / friend / interaction / message / profile / web 八区),actions 直接 `ctx.bridge.apis.<area>.method(...)` 调用 Core 的 Api 层。保留的 ~30 个字段全是真组合 helper(module-level send/forward、message store reads、meta-lookup composers)。完全 NapCat 化(class-per-action / TypeBox schema / actionName 枚举 / auto-register decorator)暂未做——profile 文档/工具链需求出现后再做。
|
||||
# SnowLuma v3 — 目标架构
|
||||
|
||||
> v2 已完成:UID/UIN Service(SQLite 持久化)、tsx+map Debug、包拆分、proto-defs 剥离、消息 hot-path 优化(17.5μs → 4.7μs)、NapCat 风格 Api 层、Bridge/Account 分层(v2 发布在 `@snowluma/bridge`,v3 重命名为 `@snowluma/channel`)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 数据流总览(一图概览所有权)
|
||||
|
||||
```
|
||||
┌─ @snowluma/channel-hook ─────────┐ ┌─ @snowluma/channel-socket ──────┐
|
||||
│ HookManager + HookChannel │ │ SocketChannel (future) │
|
||||
│ — 仅 send/recv + pid/hook state — │ │ — 仅 send/recv + socket state — │
|
||||
└────────────┬─────────────────────┘ └─────────────┬───────────────────┘
|
||||
│ Channel 实例 │
|
||||
└───────────┬──────────────────────────┘
|
||||
│ 通过 ChannelAdapter 注册
|
||||
▼
|
||||
┌─ @snowluma/core ──── Hub(主入口 / 持有一切)──────────────┐
|
||||
│ │
|
||||
│ 内部:Map<uin, Core> │
|
||||
│ │
|
||||
│ channel available ──► ctx = capability(channel) │
|
||||
│ ──► core = new Core(ctx) │
|
||||
│ ──► emit 'core-online' { uin, apis, events, ... } │
|
||||
│ │
|
||||
│ channel gone ──► core.dispose() + emit 'core-offline' { uin } │
|
||||
└─────────────────────────────────────┬─────────────────────────────────┘
|
||||
│ 顶层 lifecycle 事件(仅 2 个)
|
||||
▼
|
||||
┌─ @snowluma/onebot ──────────────────────────────────────────────────────┐
|
||||
│ hub.events.on('core-online', ctx => { │
|
||||
│ this.byUin.set(ctx.uin, ctx); │
|
||||
│ ctx.events.on('group_message', e => …); // 每账号 bus │
|
||||
│ }); │
|
||||
│ // 处理 OneBot action: │
|
||||
│ this.byUin.get(uin)?.apis.message.sendGroup(...) │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**核心约定**:
|
||||
- `Channel` / adapter 包 **只**做 send/recv + 自己的内部状态(pid set / hook session / socket fd)。完全无业务。
|
||||
- `Hub` 是**主入口**,独占持有 Channels + Cores。`Core` 实例由它构造,外部拿不到 Core 类本身。
|
||||
- `Core` 通过 **ctx**(capability,一个 POJO)拿到 send/recv,从不直接持有 Channel。
|
||||
- 外部消费者(OneBot / WebUI)只拿 `CoreCtx`(Core 的对外投影:`{ uin, apis, events, identity }`),不知道 Core 类的存在。
|
||||
- 每个账号一个 `events`(在 Core 上),不做全局 bus;Hub 只 emit 两个顶层生命周期事件。
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标包结构
|
||||
|
||||
```
|
||||
SnowLuma/
|
||||
├── packages/
|
||||
│ │
|
||||
│ │ ── Infrastructure(无业务) ──
|
||||
│ ├── common/ logger / packet-sender / protocol-types / async-context
|
||||
│ ├── proto-defs/ protobuf TS 接口定义
|
||||
│ ├── proton/ protobuf codec 编译时生成器
|
||||
│ ├── runtime/ native .node 产物清单
|
||||
│ ├── ui/ Tailwind v4 + shadcn 组件(前端)
|
||||
│ │
|
||||
│ │ ── Protocol(解析层,纯函数) ──
|
||||
│ ├── protocol/ events / identity-service / msg-push / oidb / highway /
|
||||
│ │ element-builder / packet-pipeline / event-bus
|
||||
│ │
|
||||
│ │ ── Channel & adapters(transport 端口与实现) ──
|
||||
│ ├── channel/ ⭐ Channel 接口 + 抽象类 + ChannelAdapter 端口
|
||||
│ │ —— 只定义接口和最小抽象,**不**含 Hub
|
||||
│ ├── channel-hook/ ⭐ HookManager + HookChannel + HookAdapter
|
||||
│ │ —— 现 @snowluma/channel 大部分内容搬来
|
||||
│ ├── channel-socket/ ⭐ 未来:SocketChannel + SocketAdapter
|
||||
│ │
|
||||
│ │ ── Core(主入口 + 业务封装) ──
|
||||
│ ├── core/ ⭐ Core + Hub + CoreCtx + ApiHub + 协议封装
|
||||
│ │ —— Hub 在这里(避免 channel↔core 循环)
|
||||
│ │
|
||||
│ │ ── Inbound(外部协议消费 CoreCtx) ──
|
||||
│ ├── onebot/ OneBot v11 (HTTP + WS)
|
||||
│ ├── websocket/ 底层 WS server(被 onebot / webui-backend 共用)
|
||||
│ ├── webui-backend/ ⭐ Hono server + REST/WS(拆自 webui)
|
||||
│ ├── webui-frontend/ ⭐ Vite SPA(拆自 webui)
|
||||
│ └── sdk/ TS SDK
|
||||
│
|
||||
├── package.json
|
||||
└── pnpm-workspace.yaml
|
||||
```
|
||||
|
||||
⭐ 标记的是 v3 改动。
|
||||
|
||||
### 1.1 关键变动
|
||||
|
||||
| 当前 | 目标 | 备注 |
|
||||
|---|---|---|
|
||||
| `@snowluma/bridge`(hook + transport + adapter + manager) | `@snowluma/channel`(仅接口 + abstract Channel)+ `@snowluma/channel-hook`(hook 实现) | 包名 v2 叫 bridge,v3 重命名;hook 全套迁出独立包 |
|
||||
| `@snowluma/core`(含 Account + AccountManager) | `core`:Core + Hub | Account → Core;AccountManager 折进 Hub |
|
||||
| —— | `channel-socket` | 新建 stub |
|
||||
| `@snowluma/webui` | `webui-backend` + `webui-frontend` | 前后端拆分 |
|
||||
|
||||
### 1.2 依赖 DAG(无环)
|
||||
|
||||
```
|
||||
common ◄── proton, proto-defs, protocol, runtime, ui, channel
|
||||
proto-defs ◄── protocol
|
||||
proton ◄── protocol
|
||||
protocol ◄── core
|
||||
channel ◄── channel-hook, channel-socket, core
|
||||
channel-hook ◄── core
|
||||
channel-socket ◄── core
|
||||
core ◄── onebot, webui-backend
|
||||
websocket ◄── onebot, webui-backend
|
||||
ui ◄── webui-frontend
|
||||
```
|
||||
|
||||
**核心要点**:`core` 是唯一一处同时知道 `channel` 端口 + 业务实现的地方。Channel 包不反向依赖 core,因此 Hub **住在 core**,而不是 channel —— 名字保留 `Hub` 是因为它语义上仍是「channel 集群的指挥官」。
|
||||
|
||||
---
|
||||
|
||||
## 2. 三个关键类型 / 接口(设计核心)
|
||||
|
||||
整个系统由 **3 个类型** 串起来。每个职责单一、边界清晰。
|
||||
|
||||
### 2.1 `Channel`(在 `@snowluma/channel`)—— 纯 transport
|
||||
|
||||
```ts
|
||||
// packages/channel/src/channel.ts
|
||||
export type ChannelKind = 'inject' | 'socket';
|
||||
|
||||
export interface Channel {
|
||||
readonly kind: ChannelKind;
|
||||
readonly uin: string;
|
||||
readonly id: string; // adapter:uin 形式
|
||||
|
||||
sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult>;
|
||||
setPacketHandler(h: ((pkt: PacketInfo) => void) | null): void;
|
||||
deliverPacket(pkt: PacketInfo): void; // adapter 内部用
|
||||
dispose(): void;
|
||||
}
|
||||
```
|
||||
|
||||
Adapter 包(`channel-hook` / `channel-socket`)的具体类(`HookChannel` / `SocketChannel`)实现 `Channel`。它们的内部状态(PID set、hook session、socket fd)对外不可见。
|
||||
|
||||
### 2.2 `ChannelCtx`(在 `@snowluma/channel`)—— channel → core 的能力 POJO
|
||||
|
||||
```ts
|
||||
// packages/channel/src/channel-ctx.ts
|
||||
export interface ChannelCtx {
|
||||
readonly uin: string;
|
||||
readonly kind: ChannelKind;
|
||||
readonly sendRawPacket: (cmd: string, body: Uint8Array) => Promise<SendPacketResult>;
|
||||
readonly onPacket: (h: (pkt: PacketInfo) => void) => void;
|
||||
readonly dispose: () => void;
|
||||
}
|
||||
|
||||
// Hub 用 makeCtx(channel) 把 Channel 投影成 ChannelCtx:
|
||||
export function makeChannelCtx(b: Channel): ChannelCtx {
|
||||
return {
|
||||
uin: b.uin, kind: b.kind,
|
||||
sendRawPacket: (c, x) => b.sendRawPacket(c, x),
|
||||
onPacket: (h) => b.setPacketHandler(h),
|
||||
dispose: () => b.dispose(),
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**关键设计**:`Core` 只接收 `ChannelCtx`(capability POJO),**不**持有 `Channel` 类引用。这样 `core` 包不依赖任何 adapter 实现细节,连 Channel 抽象类都不用 import。
|
||||
|
||||
### 2.3 `CoreCtx`(在 `@snowluma/core`)—— core → onebot 的能力 POJO
|
||||
|
||||
```ts
|
||||
// packages/core/src/core-ctx.ts
|
||||
export interface CoreCtx {
|
||||
readonly uin: string;
|
||||
readonly kind: ChannelKind;
|
||||
readonly apis: ApiHub; // 所有 typed api(message/contacts/...)
|
||||
readonly events: EventBus; // 该账号的事件(per-uin)
|
||||
readonly identity: IdentityService; // UID/UIN/group roster
|
||||
}
|
||||
```
|
||||
|
||||
**关键设计**:OneBot 拿到的就是这个 POJO 投影,**不**持有 `Core` 类引用。Hub 在 `core-online` 事件里把 `CoreCtx` 透出去;OneBot 按 uin 存起来用。
|
||||
|
||||
---
|
||||
|
||||
## 3. `Hub` —— 主入口完整实现
|
||||
|
||||
所有所有权、生命周期、装配都在这里。**外部 main.ts 只跟它打交道。**
|
||||
|
||||
```ts
|
||||
// packages/core/src/hub.ts
|
||||
import { Channel, ChannelAdapter, ChannelAdapterHost, makeChannelCtx } from '@snowluma/channel';
|
||||
import { Core } from './core';
|
||||
import type { CoreCtx } from './core-ctx';
|
||||
import { TypedEmitter } from '@snowluma/common/typed-emitter';
|
||||
|
||||
type Lifecycle = {
|
||||
'core-online': CoreCtx;
|
||||
'core-offline': { uin: string };
|
||||
};
|
||||
|
||||
export class Hub {
|
||||
private readonly cores = new Map<string, Core>();
|
||||
private readonly adapters: ChannelAdapter[] = [];
|
||||
readonly events = new TypedEmitter<Lifecycle>();
|
||||
|
||||
registerAdapter(a: ChannelAdapter): void {
|
||||
this.adapters.push(a);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
const host: ChannelAdapterHost = {
|
||||
onChannelReady: (b) => this.onChannelReady(b),
|
||||
onChannelGone: (uin) => this.onChannelGone(uin),
|
||||
};
|
||||
await Promise.all(this.adapters.map((a) => a.start(host)));
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await Promise.all(this.adapters.map((a) => a.stop()));
|
||||
for (const c of this.cores.values()) c.dispose();
|
||||
this.cores.clear();
|
||||
}
|
||||
|
||||
// ─── private ───────────────────────────────
|
||||
|
||||
private onChannelReady(channel: Channel): void {
|
||||
const stale = this.cores.get(channel.uin);
|
||||
if (stale) {
|
||||
stale.dispose();
|
||||
this.events.emit('core-offline', { uin: channel.uin });
|
||||
}
|
||||
const core = new Core(makeChannelCtx(channel));
|
||||
this.cores.set(channel.uin, core);
|
||||
this.events.emit('core-online', core.publicCtx);
|
||||
}
|
||||
|
||||
private onChannelGone(uin: string): void {
|
||||
const core = this.cores.get(uin);
|
||||
if (!core) return;
|
||||
core.dispose();
|
||||
this.cores.delete(uin);
|
||||
this.events.emit('core-offline', { uin });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 4. `Core` 实现要点
|
||||
|
||||
```ts
|
||||
// packages/core/src/core.ts
|
||||
import type { ChannelCtx } from '@snowluma/channel';
|
||||
import { EventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
|
||||
import { buildApiHub, type ApiHub } from './apis';
|
||||
import type { CoreCtx } from './core-ctx';
|
||||
|
||||
export class Core {
|
||||
readonly events = new EventBus(); // ← 每账号一个 bus
|
||||
readonly identity: IdentityService;
|
||||
readonly apis: ApiHub;
|
||||
private readonly pipeline: IncomingPacketPipeline;
|
||||
|
||||
constructor(private readonly channelCtx: ChannelCtx) {
|
||||
this.identity = IdentityService.openForUin(channelCtx.uin);
|
||||
this.pipeline = new IncomingPacketPipeline(this.events, this.identity);
|
||||
this.apis = buildApiHub(this); // apis 内部持 Core 引用,调 sendRawPacket
|
||||
channelCtx.onPacket((pkt) => this.pipeline.process(pkt));
|
||||
}
|
||||
|
||||
// 给外部消费者的投影(只读 POJO,不暴露 Core 实例)
|
||||
get publicCtx(): CoreCtx {
|
||||
return {
|
||||
uin: this.channelCtx.uin,
|
||||
kind: this.channelCtx.kind,
|
||||
apis: this.apis,
|
||||
events: this.events,
|
||||
identity: this.identity,
|
||||
};
|
||||
}
|
||||
|
||||
// apis 内部通过 core 调发包
|
||||
sendRawPacket(cmd: string, body: Uint8Array) {
|
||||
return this.channelCtx.sendRawPacket(cmd, body);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.channelCtx.dispose();
|
||||
this.identity.close();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 5. OneBot 消费 `CoreCtx`
|
||||
|
||||
```ts
|
||||
// packages/onebot/src/manager.ts
|
||||
import type { Hub, CoreCtx } from '@snowluma/core';
|
||||
|
||||
export class OneBotManager {
|
||||
private readonly byUin = new Map<string, CoreCtx>();
|
||||
|
||||
bind(hub: Hub): void {
|
||||
hub.events.on('core-online', (ctx) => this.attach(ctx));
|
||||
hub.events.on('core-offline', ({ uin }) => this.detach(uin));
|
||||
}
|
||||
|
||||
private attach(ctx: CoreCtx): void {
|
||||
this.byUin.set(ctx.uin, ctx);
|
||||
ctx.events.on('group_message', (e) => this.dispatchGroupMessage(ctx, e));
|
||||
ctx.events.on('private_message',(e) => this.dispatchPrivateMessage(ctx, e));
|
||||
// ... 其它 kind
|
||||
}
|
||||
|
||||
private detach(uin: string): void {
|
||||
this.byUin.delete(uin);
|
||||
// ctx.events 随 Core dispose 一起释放
|
||||
}
|
||||
|
||||
// 处理 OneBot HTTP/WS action:用 uin 查到 ctx,直接调 apis
|
||||
async handleSendGroupMsg(uin: string, groupId: number, msg: OneBotMsg) {
|
||||
const ctx = this.byUin.get(uin);
|
||||
if (!ctx) throw new Error(`unknown uin: ${uin}`);
|
||||
return ctx.apis.message.sendGroup(groupId, msg); // ← 直接调封装好的 api
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 6. 主入口(`packages/core/src/index.ts`)
|
||||
|
||||
```ts
|
||||
import { HookAdapter } from '@snowluma/channel-hook';
|
||||
import { OneBotManager } from '@snowluma/onebot';
|
||||
import { Hub } from './hub';
|
||||
|
||||
const hub = new Hub();
|
||||
hub.registerAdapter(new HookAdapter({ autoLoadOnDiscovery: true }));
|
||||
// hub.registerAdapter(new SocketAdapter()); // 未来
|
||||
|
||||
const onebot = new OneBotManager();
|
||||
onebot.bind(hub);
|
||||
|
||||
await hub.start();
|
||||
await initWebUI(port, onebot, /* hookManager from adapter */);
|
||||
```
|
||||
|
||||
9 行装配,每行都是有意义的所有权声明。
|
||||
|
||||
---
|
||||
|
||||
## 7. 为什么这样设计优雅
|
||||
|
||||
### 7.1 单向数据流
|
||||
|
||||
```
|
||||
adapter → Channel → ChannelCtx → Core → CoreCtx → OneBot
|
||||
transport capability capability
|
||||
```
|
||||
|
||||
**没有反向引用**:Core 不知道 Channel 类,OneBot 不知道 Core 类。每层只看到「下一层的能力 POJO」。
|
||||
|
||||
### 7.2 单一所有者
|
||||
|
||||
`Hub.cores: Map<uin, Core>` 是 **唯一** 持有 Core 的地方。OneBot 只持 `CoreCtx`(投影,不算所有权)。Core 销毁 = 从这个 Map 里删 = 所有 ctx 同时失效。无需引用计数、无需 GC 协调。
|
||||
|
||||
### 7.3 每账号独立 EventBus
|
||||
|
||||
Core 自带 `events: EventBus`,互不干扰。OneBot 通过 `core-online` 拿到 ctx 后立即 subscribe,`core-offline` 时 Core 已 dispose,bus 自然失效,不会泄漏。**没有全局 bus**,没有「哪个账号的事件」问题。
|
||||
|
||||
### 7.4 完全可测
|
||||
|
||||
- 测 Channel:mock `setPacketHandler` 回调(已在 `account-private-routing.test.ts` 用 `FakeChannel` 验证)
|
||||
- 测 Core:传 `ChannelCtx` POJO 即可,无需真 Channel
|
||||
- 测 OneBot:emit 一个 `core-online` + 假 `CoreCtx`
|
||||
- 测 Hub:用 fake `ChannelAdapter`
|
||||
|
||||
每层都能独立测试。
|
||||
|
||||
### 7.5 内部还要避免 ctx 漫天的两个小招
|
||||
|
||||
**(a) Api 类捕获 deps(已做)**
|
||||
|
||||
```ts
|
||||
class MessageApi {
|
||||
constructor(private readonly core: Core) {}
|
||||
// 方法签名只有业务参数:
|
||||
async sendGroup(groupId: number, msg: Msg) { this.core.sendRawPacket(...) }
|
||||
}
|
||||
```
|
||||
|
||||
**(b) AsyncLocalStorage 处理日志 / trace(建议引入)**
|
||||
|
||||
```ts
|
||||
// packages/common/src/async-context.ts
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
const als = new AsyncLocalStorage<{ uin?: string; trace?: string }>();
|
||||
|
||||
export const runInContext = <T>(c: { uin?: string; trace?: string }, fn: () => T) =>
|
||||
als.run(c, fn);
|
||||
export const ctx = () => als.getStore() ?? {};
|
||||
|
||||
// logger 自动 prefix [uin],业务代码不用接 log 参数
|
||||
```
|
||||
|
||||
在 `Core.constructor` 给 `onPacket` 包一层:
|
||||
```ts
|
||||
channelCtx.onPacket((pkt) => {
|
||||
runInContext({ uin: channelCtx.uin, trace: `pkt:${pkt.seqId}` }, () => {
|
||||
this.pipeline.process(pkt);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
所有下游 `log.info()` 自动带 `[10001]` 前缀,不污染业务签名。开销 ~50ns/call。
|
||||
|
||||
---
|
||||
|
||||
## 8. 不要的设计(保持简单)
|
||||
|
||||
| 方案 | 不做的原因 |
|
||||
|---|---|
|
||||
| **`CoreFactory` 抽象** | Core 只一种,多此一举。直接 `new Core(ctx)` |
|
||||
| **全局 EventBus** | 每账号自己的 bus 更清晰,OneBot 按 uin 订阅,不混杂 |
|
||||
| **`AccountManager` 独立层** | 多余的中间层,折进 `Hub` |
|
||||
| **`InboundAdapter` 抽象** | OneBot / WebUI 数量有限且固定,直接 `bm.events.on(...)` 即可,不抽插件层 |
|
||||
| **DI 容器(tsyringe 等)** | 9 行手动装配已经清晰,DI 引入反射/装饰器元数据反而难调 |
|
||||
| **Effect monad / Reader monad** | TS 缺 do-notation,类型噪音 > 收益 |
|
||||
| **CQRS / Event-sourced state** | 当前状态量级(10 账号 × 100 群)远未到 |
|
||||
|
||||
---
|
||||
|
||||
## 9. 迁移路线(每步独立可 ship)
|
||||
|
||||
> typecheck + 全测试通过才进下一步。
|
||||
|
||||
**Step 1** —— ⭐ 重命名 + 拆现有的 `@snowluma/bridge`
|
||||
- `packages/bridge/` 重命名为 `packages/channel/`;package.json name 改为 `@snowluma/channel`
|
||||
- 新建 `packages/channel-hook/`,从 `@snowluma/channel` 搬:`hook-manager.ts` / `hook-session.ts` / `hook-packet-client.ts` / `injector.ts` / `pipe-watcher.ts` / `qq-hook-client.ts` / `qq-port-probe.ts` / `hook-channel.ts`(原 inject-bridge.ts)/ `hook-adapter.ts`(原 inject-adapter.ts)
|
||||
- `@snowluma/channel` 留:`channel.ts`(abstract,原 bridge.ts)/ `channel-interface.ts` / `channel-ctx.ts`(新)/ `adapter.ts`(端口)+ `makeChannelCtx` 工具
|
||||
- 删除:`manager.ts`(原 BridgeManager)(搬到 core/hub.ts)/ `socket-channel.ts` + `socket-adapter.ts`(搬到 `channel-socket` stub)
|
||||
|
||||
**Step 2** —— ⭐ 重塑 `@snowluma/core`
|
||||
- 删除:`account/account.ts` / `account-interface.ts` / `account-context.ts` / `account-manager.ts`
|
||||
- 新建:`core.ts`(吸收 Account 业务,构造接 `ChannelCtx`)/ `core-ctx.ts` / `hub.ts`
|
||||
- `apis/` 内部 `AccountContext` → `Core`(直接拿 Core 类型)
|
||||
- `index.ts` 9 行装配(见 §6)
|
||||
|
||||
**Step 3** —— OneBot 适配 CoreCtx
|
||||
- 全局 `AccountInterface` → `CoreCtx`
|
||||
- `OneBotManager.bind(hub)` 订阅 `'core-online'` / `'core-offline'`
|
||||
- 内部 `byUin.get(uin).apis.<area>.method()` 调 api
|
||||
|
||||
**Step 4** —— 引入 `AsyncLocalStorage`
|
||||
- `packages/common/src/async-context.ts`
|
||||
- `logger.ts` 自动读 ALS,加 `[uin]` 前缀
|
||||
- `Core.constructor` 在 `onPacket` 回调外包 `runInContext`
|
||||
|
||||
**Step 5** —— `channel-socket` stub 包(占位)
|
||||
- 把 `socket-channel.ts` / `socket-adapter.ts` 搬过来
|
||||
- 实现 placeholder,让 `ChannelAdapter` 端口齐
|
||||
|
||||
**Step 6** —— ⭐ 拆 `webui` 为 `webui-backend` + `webui-frontend`
|
||||
- Hono server + REST/WS → `webui-backend`,依赖 `@snowluma/core`(消费 `CoreCtx`)
|
||||
- Vite SPA + UI → `webui-frontend`,依赖 `@snowluma/ui`
|
||||
|
||||
---
|
||||
|
||||
## 10. 设计原则速查
|
||||
|
||||
- **单向数据流**:`adapter → Channel → ChannelCtx → Core → CoreCtx → OneBot`,无反向引用
|
||||
- **能力 POJO 跨层传递**:层间用 `{ uin, sendRawPacket, ... }` / `{ uin, apis, events, ... }` 这种纯数据,不传类实例
|
||||
- **单一所有者**:`Hub.cores` 是 Core 唯一容器,消费者只持投影
|
||||
- **每账号自带 EventBus**:避免全局 bus 混杂,订阅生命周期与 Core 绑定
|
||||
- **Class 封装 deps**:构造时捕获,方法签名只剩业务参数
|
||||
- **AsyncLocalStorage 跨切面**:日志 / trace 不进显式参数
|
||||
- **不引入过度抽象**:no factory / no DI / no Effect monad / no global bus
|
||||
- **可测**:每层接 POJO,fake 一下就能测
|
||||
|
||||
---
|
||||
|
||||
## 11. v2.0.0 已完成
|
||||
|
||||
- ✅ UID/UIN Service + SQLite 持久化
|
||||
- ✅ tsx 免打包 Debug
|
||||
- ✅ Common / OneBot / Core / Bridge / Protocol / proto-defs 拆包
|
||||
- ✅ 消息 hot-path 优化(17.5μs → 4.7μs,better-sqlite3 + prepared-statement cache)
|
||||
- ✅ NapCat 风格 Api 层(13 Api 类)
|
||||
- ✅ Bridge / Account 严格分层(v2 中间形态;v3 重命名为 Channel + Core,并用 ctx 替代直接引用)
|
||||
- ✅ `@snowluma/bridge` 完整 transport 包(v3 重命名为 `@snowluma/channel`)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="400" viewBox="0 0 1200 400" role="img" aria-labelledby="hero-title hero-desc">
|
||||
<title id="hero-title">SnowLuma — QQ 到 OneBot 的现代协议桥</title>
|
||||
<desc id="hero-desc">SnowLuma 将多个 QQ 原生会话经过协议、桥接与 OneBot 三层处理,连接到 WebSocket、HTTP、WebUI、SDK 与 MCP。</desc>
|
||||
|
||||
<defs>
|
||||
<linearGradient id="hero-bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#08111f"/>
|
||||
<stop offset="0.58" stop-color="#101b31"/>
|
||||
<stop offset="1" stop-color="#17223d"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="brand-line" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0" stop-color="#75d2ff"/>
|
||||
<stop offset="0.55" stop-color="#bba7ff"/>
|
||||
<stop offset="1" stop-color="#f4bfd9"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="bridge-fill" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#192c4e"/>
|
||||
<stop offset="1" stop-color="#2a2550"/>
|
||||
</linearGradient>
|
||||
<filter id="soft-glow" x="-40%" y="-40%" width="180%" height="180%">
|
||||
<feGaussianBlur stdDeviation="16"/>
|
||||
</filter>
|
||||
<style>
|
||||
.sans { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; }
|
||||
.mono { font-family: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace; }
|
||||
.hero-star { animation: hero-star-float 4s ease-in-out infinite; }
|
||||
.hero-star-main { transform-origin: 16px 14px; }
|
||||
.hero-star-secondary { transform-origin: 38px 38px; animation-delay: 0.5s; }
|
||||
@keyframes hero-star-float {
|
||||
0% { transform: translateY(0) rotate(0deg); opacity: 0.9; }
|
||||
50% { transform: translateY(-8px) rotate(10deg); opacity: 1; }
|
||||
100% { transform: translateY(0) rotate(0deg); opacity: 0.9; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .hero-star { animation: none; } }
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<rect width="1200" height="400" rx="28" fill="url(#hero-bg)"/>
|
||||
<circle cx="1112" cy="28" r="138" fill="#63c9f6" opacity="0.08" filter="url(#soft-glow)"/>
|
||||
<circle cx="705" cy="392" r="120" fill="#b59cff" opacity="0.06" filter="url(#soft-glow)"/>
|
||||
|
||||
<g aria-hidden="true" fill="none" stroke-linecap="round">
|
||||
<path d="M694 28H1154" stroke="#5f7192" stroke-opacity="0.28"/>
|
||||
<path d="M694 372H1154" stroke="#5f7192" stroke-opacity="0.2"/>
|
||||
<path d="M708 14V386" stroke="#5f7192" stroke-opacity="0.16"/>
|
||||
<path d="M1140 14V386" stroke="#5f7192" stroke-opacity="0.16"/>
|
||||
</g>
|
||||
|
||||
<g id="title-block" transform="translate(64 54)">
|
||||
<text class="mono" x="0" y="0" fill="#8da1c0" font-size="14" letter-spacing="2.2">QQ INTEROPERABILITY · ONEBOT V11 · MULTI-ACCOUNT</text>
|
||||
|
||||
<text class="sans" x="0" y="92" font-size="74" font-weight="760" letter-spacing="-3">
|
||||
<tspan fill="#f7fbff">Snow</tspan><tspan fill="#82d7ff">Luma</tspan>
|
||||
</text>
|
||||
<rect x="2" y="110" width="148" height="5" rx="2.5" fill="url(#brand-line)"/>
|
||||
|
||||
<text class="sans" x="0" y="162" fill="#dce7f7" font-size="27" font-weight="590">把 QQ 原生会话,稳定地桥接到</text>
|
||||
<text class="sans" x="0" y="199" fill="#dce7f7" font-size="27" font-weight="590">OneBot、WebUI 与自动化工具。</text>
|
||||
|
||||
<text class="sans" x="0" y="244" fill="#92a6c5" font-size="16">一个运行时,管理多账号、动作调用、事件分发与实时状态。</text>
|
||||
|
||||
<g transform="translate(0 274)">
|
||||
<rect width="128" height="34" rx="17" fill="#172942" stroke="#315173"/>
|
||||
<circle cx="18" cy="17" r="4" fill="#75d2ff"/>
|
||||
<text class="mono" x="31" y="22" fill="#b9dfff" font-size="13">Windows x64</text>
|
||||
|
||||
<g transform="translate(140 0)">
|
||||
<rect width="174" height="34" rx="17" fill="#211f41" stroke="#4d4777"/>
|
||||
<circle cx="18" cy="17" r="4" fill="#bba7ff"/>
|
||||
<text class="mono" x="31" y="22" fill="#d8cdfd" font-size="13">Linux x64 / arm64</text>
|
||||
</g>
|
||||
|
||||
<g transform="translate(326 0)">
|
||||
<rect width="120" height="34" rx="17" fill="#302037" stroke="#68435c"/>
|
||||
<circle cx="18" cy="17" r="4" fill="#f4bfd9"/>
|
||||
<text class="mono" x="31" y="22" fill="#f7d7e6" font-size="13">TypeScript</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g id="project-proof" transform="translate(734 58)">
|
||||
<text class="mono" x="0" y="0" fill="#8398b8" font-size="13" letter-spacing="1.8">LIVE SESSION ROUTING</text>
|
||||
|
||||
<g transform="translate(0 24)">
|
||||
<g>
|
||||
<rect width="116" height="45" rx="12" fill="#12253d" stroke="#2d5274"/>
|
||||
<circle cx="19" cy="17" r="5" fill="#74d2ff"/>
|
||||
<text class="mono" x="31" y="21" fill="#c7e9fb" font-size="12">QQ · 01</text>
|
||||
<text class="mono" x="16" y="36" fill="#7189a9" font-size="10">ONLINE</text>
|
||||
</g>
|
||||
<g transform="translate(132 0)">
|
||||
<rect width="116" height="45" rx="12" fill="#1b2342" stroke="#4a4c78"/>
|
||||
<circle cx="19" cy="17" r="5" fill="#bba7ff"/>
|
||||
<text class="mono" x="31" y="21" fill="#ddd4ff" font-size="12">QQ · 02</text>
|
||||
<text class="mono" x="16" y="36" fill="#8186ad" font-size="10">ONLINE</text>
|
||||
</g>
|
||||
<g transform="translate(264 0)">
|
||||
<rect width="116" height="45" rx="12" fill="#292039" stroke="#67445d"/>
|
||||
<circle cx="19" cy="17" r="5" fill="#f4bfd9"/>
|
||||
<text class="mono" x="31" y="21" fill="#f8dbea" font-size="12">QQ · N</text>
|
||||
<text class="mono" x="16" y="36" fill="#a17f95" font-size="10">READY</text>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g aria-hidden="true" fill="none" stroke="url(#brand-line)" stroke-width="2" stroke-linecap="round" opacity="0.85">
|
||||
<path d="M58 69V90C58 102 78 104 94 104H190"/>
|
||||
<path d="M190 69V104"/>
|
||||
<path d="M322 69V90C322 102 302 104 286 104H190"/>
|
||||
</g>
|
||||
|
||||
<g transform="translate(0 104)">
|
||||
<rect x="12" y="16" width="356" height="88" rx="18" fill="#0d1729" stroke="#263853" opacity="0.72"/>
|
||||
<rect x="6" y="8" width="368" height="88" rx="18" fill="#111f35" stroke="#364865" opacity="0.88"/>
|
||||
<rect width="380" height="88" rx="18" fill="url(#bridge-fill)" stroke="#6684ae" stroke-opacity="0.74"/>
|
||||
|
||||
<text class="mono" x="22" y="25" fill="#90a6c6" font-size="11" letter-spacing="1.4">SNOWLUMA RUNTIME</text>
|
||||
<text class="sans" x="22" y="53" fill="#f4f8ff" font-size="20" font-weight="680">Protocol → Bridge → OneBot</text>
|
||||
<text class="sans" x="22" y="74" fill="#93a8c7" font-size="13">独立会话 · 类型化动作 · 可追踪事件</text>
|
||||
|
||||
<g transform="translate(326 13)" aria-hidden="true">
|
||||
<path class="hero-star hero-star-main" d="M16 0L19.5 10.5L30 14L19.5 17.5L16 28L12.5 17.5L2 14L12.5 10.5Z" fill="#c8b7ff"/>
|
||||
<path class="hero-star hero-star-secondary" d="M38 30L40 36L46 38L40 40L38 46L36 40L30 38L36 36Z" fill="#f2c2da" opacity="0.9"/>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g aria-hidden="true" fill="none" stroke="#6881a4" stroke-width="1.5" stroke-linecap="round">
|
||||
<path d="M58 208V224"/>
|
||||
<path d="M190 208V224"/>
|
||||
<path d="M322 208V224"/>
|
||||
</g>
|
||||
|
||||
<g transform="translate(0 224)">
|
||||
<g>
|
||||
<rect width="116" height="68" rx="15" fill="#10253b" stroke="#315d7c"/>
|
||||
<text class="sans" x="58" y="29" fill="#bfe8fb" text-anchor="middle" font-size="15" font-weight="650">OneBot v11</text>
|
||||
<text class="mono" x="58" y="50" fill="#6685a3" text-anchor="middle" font-size="10">ACTIONS · EVENTS</text>
|
||||
</g>
|
||||
<g transform="translate(132 0)">
|
||||
<rect width="116" height="68" rx="15" fill="#201f42" stroke="#504d7a"/>
|
||||
<text class="sans" x="58" y="29" fill="#ded5ff" text-anchor="middle" font-size="15" font-weight="650">WebUI</text>
|
||||
<text class="mono" x="58" y="50" fill="#8483ad" text-anchor="middle" font-size="10">STATUS · LOGS</text>
|
||||
</g>
|
||||
<g transform="translate(264 0)">
|
||||
<rect width="116" height="68" rx="15" fill="#2a2038" stroke="#65455e"/>
|
||||
<text class="sans" x="58" y="29" fill="#f6d6e6" text-anchor="middle" font-size="15" font-weight="650">SDK / MCP</text>
|
||||
<text class="mono" x="58" y="50" fill="#9d7e93" text-anchor="middle" font-size="10">TOOLS · STREAMS</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 8.0 KiB |
@@ -1,140 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="440" viewBox="0 0 1200 440" role="img" aria-labelledby="map-title map-desc">
|
||||
<title id="map-title">SnowLuma 运行链路</title>
|
||||
<desc id="map-desc">QQ 进程接入后,数据经过协议桥接、OneBot 标准化,再分发到 WebSocket、HTTP、WebUI、SDK 与 MCP。</desc>
|
||||
|
||||
<defs>
|
||||
<linearGradient id="map-rule" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0" stop-color="#54bde9"/>
|
||||
<stop offset="0.55" stop-color="#9e88ef"/>
|
||||
<stop offset="1" stop-color="#e4a8c6"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="consumer-border" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#54bde9"/>
|
||||
<stop offset="0.5" stop-color="#9e88ef"/>
|
||||
<stop offset="1" stop-color="#e4a8c6"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="consumer-flow" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#a5e7ff"/>
|
||||
<stop offset="0.5" stop-color="#d1c5ff"/>
|
||||
<stop offset="1" stop-color="#ffd4e8"/>
|
||||
</linearGradient>
|
||||
<style>
|
||||
.sans { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; }
|
||||
.mono { font-family: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace; }
|
||||
@media (prefers-reduced-motion: reduce) { .consumer-flow { display: none; } }
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<rect width="1200" height="440" rx="28" fill="#f6f9fd"/>
|
||||
<rect x="0.75" y="0.75" width="1198.5" height="438.5" rx="27.25" fill="none" stroke="#cbd8e8" stroke-width="1.5"/>
|
||||
|
||||
<g transform="translate(54 42)">
|
||||
<text class="mono" x="0" y="0" fill="#6e819b" font-size="13" letter-spacing="2">RUNTIME MAP · FROM SESSION TO CONSUMER</text>
|
||||
<text class="sans" x="0" y="45" fill="#14223a" font-size="34" font-weight="720">一条事件如何穿过 SnowLuma</text>
|
||||
<text class="sans" x="0" y="75" fill="#63758e" font-size="16">每层只承担一种职责,多个 QQ 账号各自拥有独立、可追踪的会话链路。</text>
|
||||
</g>
|
||||
|
||||
<g id="connection-labels" class="mono" fill="#7c8ca2" font-size="10" letter-spacing="1.5" text-anchor="middle">
|
||||
<text x="305" y="210">PIPE</text>
|
||||
<text x="577" y="210">MAP</text>
|
||||
<text x="849" y="210">OUT</text>
|
||||
</g>
|
||||
<g aria-hidden="true" fill="none" stroke="url(#map-rule)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M284 225H316L309 218M316 225L309 232"/>
|
||||
<path d="M556 225H588L581 218M588 225L581 232"/>
|
||||
<path d="M828 225H860L853 218M860 225L853 232"/>
|
||||
</g>
|
||||
|
||||
<g id="stage-session" transform="translate(54 138)">
|
||||
<rect width="230" height="218" rx="20" fill="#ffffff" stroke="#c9d8e8" stroke-width="1.5"/>
|
||||
<path d="M20 0H210" fill="none" stroke="#54bde9" stroke-width="4" stroke-linecap="round"/>
|
||||
<text class="mono" x="20" y="32" fill="#5582a0" font-size="11" letter-spacing="1.4">01 · 会话接入</text>
|
||||
|
||||
<g transform="translate(20 48)">
|
||||
<rect width="190" height="54" rx="13" fill="#edf8fd" stroke="#afd9eb"/>
|
||||
<circle cx="25" cy="19" r="5" fill="#47b7e6"/>
|
||||
<circle cx="25" cy="35" r="5" fill="#92d8f3"/>
|
||||
<text class="mono" x="42" y="23" fill="#315a77" font-size="11">QQ · ACCOUNT 01</text>
|
||||
<text class="mono" x="42" y="39" fill="#6d92a8" font-size="11">QQ · ACCOUNT 02</text>
|
||||
</g>
|
||||
|
||||
<text class="sans" x="115" y="132" fill="#15243a" font-size="20" font-weight="680" text-anchor="middle">多个 QQ 进程</text>
|
||||
<text class="sans" x="115" y="158" fill="#687c95" font-size="14" text-anchor="middle">独立接入、独立登录状态</text>
|
||||
<text class="sans" x="115" y="181" fill="#687c95" font-size="14" text-anchor="middle">每个账号单独路由</text>
|
||||
</g>
|
||||
|
||||
<g id="stage-bridge" transform="translate(326 138)">
|
||||
<rect width="230" height="218" rx="20" fill="#ffffff" stroke="#d0c9ed" stroke-width="1.5"/>
|
||||
<path d="M20 0H210" fill="none" stroke="#9e88ef" stroke-width="4" stroke-linecap="round"/>
|
||||
<text class="mono" x="20" y="32" fill="#7163aa" font-size="11" letter-spacing="1.4">02 · 协议桥接</text>
|
||||
|
||||
<g transform="translate(20 42)">
|
||||
<rect x="10" y="14" width="170" height="48" rx="12" fill="#f2effd" stroke="#cfc5f2"/>
|
||||
<rect x="5" y="7" width="180" height="48" rx="12" fill="#eeeafd" stroke="#c3b7ee"/>
|
||||
<rect width="190" height="48" rx="12" fill="#e9e3fb" stroke="#b6a7e9"/>
|
||||
<text class="mono" x="95" y="21" fill="#544584" text-anchor="middle" font-size="11">PACKET → EVENT</text>
|
||||
<text class="mono" x="95" y="37" fill="#77699c" text-anchor="middle" font-size="10">PROTOCOL · BRIDGE</text>
|
||||
</g>
|
||||
|
||||
<text class="sans" x="115" y="132" fill="#15243a" font-size="20" font-weight="680" text-anchor="middle">解析与身份映射</text>
|
||||
<text class="sans" x="115" y="158" fill="#687c95" font-size="14" text-anchor="middle">协议数据转换为内部事件</text>
|
||||
<text class="sans" x="115" y="181" fill="#687c95" font-size="14" text-anchor="middle">异常路径保留可观察信息</text>
|
||||
</g>
|
||||
|
||||
<g id="stage-onebot" transform="translate(598 138)">
|
||||
<rect width="230" height="218" rx="20" fill="#ffffff" stroke="#d9c8e1" stroke-width="1.5"/>
|
||||
<path d="M20 0H210" fill="none" stroke="#cf9bc0" stroke-width="4" stroke-linecap="round"/>
|
||||
<text class="mono" x="20" y="32" fill="#916382" font-size="11" letter-spacing="1.4">03 · 标准化</text>
|
||||
|
||||
<g transform="translate(20 49)">
|
||||
<rect width="190" height="55" rx="13" fill="#faeff6" stroke="#e6bfd5"/>
|
||||
<text class="sans" x="95" y="25" fill="#753e62" text-anchor="middle" font-size="17" font-weight="700">OneBot v11</text>
|
||||
<text class="mono" x="95" y="42" fill="#a37792" text-anchor="middle" font-size="10">ACTIONS ↔ EVENTS</text>
|
||||
</g>
|
||||
|
||||
<text class="sans" x="115" y="132" fill="#15243a" font-size="20" font-weight="680" text-anchor="middle">统一动作与事件</text>
|
||||
<text class="sans" x="115" y="158" fill="#687c95" font-size="14" text-anchor="middle">参数校验、动作执行</text>
|
||||
<text class="sans" x="115" y="181" fill="#687c95" font-size="14" text-anchor="middle">事件转换与消息存储</text>
|
||||
</g>
|
||||
|
||||
<g id="stage-consumers" transform="translate(870 138)">
|
||||
<rect x="2" y="2" width="272" height="214" rx="18" fill="#101a2d" stroke="url(#consumer-border)" stroke-width="4"/>
|
||||
<rect class="consumer-flow" x="2" y="2" width="272" height="214" rx="18" fill="none" stroke="url(#consumer-flow)" stroke-width="5" stroke-linecap="round" stroke-dasharray="108 838" aria-hidden="true">
|
||||
<animate attributeName="stroke-dashoffset" from="0" to="-946" dur="4.8s" repeatCount="indefinite"/>
|
||||
</rect>
|
||||
<text class="mono" x="20" y="32" fill="#91a5c2" font-size="11" letter-spacing="1.4">04 · 消费端</text>
|
||||
<text class="sans" x="20" y="65" fill="#f2f7ff" font-size="20" font-weight="680">按场景自由组合</text>
|
||||
|
||||
<g class="mono" font-size="11" text-anchor="middle">
|
||||
<g transform="translate(20 84)">
|
||||
<rect width="70" height="32" rx="10" fill="#17304a" stroke="#315b7a"/>
|
||||
<text x="35" y="21" fill="#bce8fb">WS</text>
|
||||
</g>
|
||||
<g transform="translate(102 84)">
|
||||
<rect width="70" height="32" rx="10" fill="#242244" stroke="#514e7c"/>
|
||||
<text x="35" y="21" fill="#ddd5ff">HTTP</text>
|
||||
</g>
|
||||
<g transform="translate(184 84)">
|
||||
<rect width="70" height="32" rx="10" fill="#34233c" stroke="#67465e"/>
|
||||
<text x="35" y="21" fill="#f6d9e7">WebUI</text>
|
||||
</g>
|
||||
<g transform="translate(20 128)">
|
||||
<rect width="111" height="32" rx="10" fill="#182a43" stroke="#334f70"/>
|
||||
<text x="55.5" y="21" fill="#c4def5">SDK</text>
|
||||
</g>
|
||||
<g transform="translate(143 128)">
|
||||
<rect width="111" height="32" rx="10" fill="#2b2447" stroke="#554d7e"/>
|
||||
<text x="55.5" y="21" fill="#dfd7ff">MCP</text>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<text class="sans" x="20" y="190" fill="#8196b5" font-size="13">多个适配器可同时启用</text>
|
||||
</g>
|
||||
|
||||
<g transform="translate(54 392)">
|
||||
<rect width="1092" height="1" fill="#d4dfeb"/>
|
||||
<circle cx="5" cy="24" r="4" fill="#54bde9"/>
|
||||
<text class="sans" x="18" y="29" fill="#60738c" font-size="14">一次接入,统一管理运行状态、日志、连接与动作调用。</text>
|
||||
<text class="mono" x="1092" y="29" fill="#8191a6" text-anchor="end" font-size="11">SNOWLUMA / RUNTIME MAP</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 8.2 KiB |
@@ -14,12 +14,9 @@ export default defineConfig([
|
||||
'**/coverage/**',
|
||||
'**/.turbo/**',
|
||||
'**/.vite/**',
|
||||
'.claude/**',
|
||||
'dev/**',
|
||||
'**/*.tsbuildinfo',
|
||||
'**/test/fixtures/**',
|
||||
'packages/runtime/native/**',
|
||||
'packages/mcp/src/generated/**',
|
||||
]),
|
||||
{
|
||||
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
|
||||
|
||||
23
package.json
23
package.json
@@ -1,7 +1,6 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.13.0",
|
||||
"version": "1.9.2",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -9,18 +8,12 @@
|
||||
"build": "pnpm --filter @snowluma/core build",
|
||||
"build:sdk": "pnpm --filter @snowluma/sdk build",
|
||||
"build:webui": "pnpm --filter webui build",
|
||||
"build:mcp": "pnpm --filter @snowluma/mcp build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter @snowluma/ui build && pnpm --filter webui build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter webui build",
|
||||
"dev": "pnpm --filter @snowluma/core dev",
|
||||
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
|
||||
"dev:web": "pnpm --filter webui dev",
|
||||
"test": "pnpm --filter=\"./packages/**\" -r --no-bail --if-present test",
|
||||
"test:core": "pnpm --filter @snowluma/core test",
|
||||
"test": "pnpm --filter @snowluma/core test",
|
||||
"test:watch": "pnpm --filter @snowluma/core test:watch",
|
||||
"test:common": "pnpm --filter @snowluma/common test",
|
||||
"test:all": "pnpm test",
|
||||
"test:native": "pnpm --filter=\"./packages/**\" -r --if-present test:native",
|
||||
"coverage": "node tools/coverage.mjs",
|
||||
"typecheck": "pnpm -r --if-present typecheck",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
@@ -47,14 +40,12 @@
|
||||
"eslint-plugin-react-hooks>eslint": "10"
|
||||
}
|
||||
},
|
||||
"overrides": {
|
||||
"esbuild@<0.28.1": "^0.28.1",
|
||||
"@babel/core@<7.29.6": "^7.29.6"
|
||||
}
|
||||
"onlyBuiltDependencies": [
|
||||
"better-sqlite3"
|
||||
]
|
||||
},
|
||||
"packageManager": "pnpm@10.28.0",
|
||||
"engines": {
|
||||
"node": "^22.13.0 || >=23.4.0",
|
||||
"pnpm": "10.28.0"
|
||||
"node": ">=22"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,536 +0,0 @@
|
||||
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';
|
||||
import fs from 'fs';
|
||||
import { HookSession, type HookSessionDeps } from './hook-session';
|
||||
import {
|
||||
injectHookProcess,
|
||||
listHookProcesses,
|
||||
resolveHookNativePath,
|
||||
unloadHookProcess,
|
||||
type HookProcessBaseInfo,
|
||||
} from './injector';
|
||||
import { PipeWatcher } from './pipe-watcher';
|
||||
import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
|
||||
import { QqHookClient } from './qq-hook-client';
|
||||
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
|
||||
import type { HookProcessInfo } from './types';
|
||||
|
||||
const AUTO_LOAD_MAX_ATTEMPTS = 3;
|
||||
|
||||
type AutoLoadAttempt = {
|
||||
attempts: number;
|
||||
inFlight: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sink that the hook layer calls back into when it observes a new login,
|
||||
* a parsed packet, or a PID disconnect. The concrete implementation lives
|
||||
* in @snowluma/core (`BridgeManager`), which is wired in by the top-level
|
||||
* app entry. Declaring it here keeps @snowluma/bridge free of any
|
||||
* dependency on @snowluma/core — the hook package is self-contained.
|
||||
*/
|
||||
export interface BridgeManagerSink {
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
|
||||
onPacket(pkt: PacketInfo): void;
|
||||
onPidDisconnected(pid: number): void;
|
||||
onPidReceiveHealthChanged(pid: number, healthy: boolean): void;
|
||||
}
|
||||
|
||||
export type HookManagerDeps = {
|
||||
bridgeManager: BridgeManagerSink;
|
||||
/** Sink for parsed packets from any live HookSession. Defaults to
|
||||
* `bridgeManager.onPacket` — every packet flows straight into the
|
||||
* per-UIN bridge dispatcher with no intermediate event emitter. */
|
||||
onPacket?: PacketSink;
|
||||
/** Native injector entrypoints. Defaults to the real native addon. */
|
||||
injector?: HookSessionDeps['injector'];
|
||||
/** Hook pipe-client factory. Defaults to `new QqHookClient(pid)`. */
|
||||
makeClient?: HookSessionDeps['makeClient'];
|
||||
/** Pre-built watcher. Defaults to a PipeWatcher wrapping the native listings. */
|
||||
pipeWatcher?: PipeWatcher;
|
||||
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
|
||||
watcherIntervalMs?: number;
|
||||
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
|
||||
listProcesses?: () => HookProcessBaseInfo[];
|
||||
/** When true, every newly-discovered QQ process is auto-injected (fires
|
||||
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
|
||||
* Failed loads are logged and leave the session in the 'error' state.
|
||||
* A narrowly-classified early-process mapping race is retried on later
|
||||
* watcher ticks with a fixed attempt limit. */
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
/** Optional hook fired whenever the set of HookProcessInfo observable to
|
||||
* `listProcesses()` changes — new process discovered, process gone, or
|
||||
* any session's status mutated. Used by the WebUI SSE wiring to push a
|
||||
* fresh processes snapshot to connected clients without REST polling.
|
||||
* Exceptions thrown by the callback are caught and logged; they do not
|
||||
* break the watcher / session event loops. */
|
||||
onSessionsChanged?: () => void;
|
||||
log?: Logger;
|
||||
};
|
||||
|
||||
/**
|
||||
* HookManager — thin orchestrator over a per-PID HookSession map and a
|
||||
* singleton PipeWatcher.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Route user commands (load/unload/refresh) to the matching session.
|
||||
* - Route watcher diff events to the matching session.
|
||||
* - Forward session events ('login' / 'disconnected' / receive health) to BridgeManager.
|
||||
* - Retry stuck-in-connecting sessions on every watcher tick (so a
|
||||
* failed connect eventually recovers without a manual refresh).
|
||||
* - Retry the bounded early-process auto-load race without retrying
|
||||
* permanent injector errors.
|
||||
*
|
||||
* The native injector, native pipe-client, and native process/pipe
|
||||
* listings are all swappable dependencies so tests can run without a
|
||||
* real QQ.exe or a native addon.
|
||||
*/
|
||||
export class HookManager {
|
||||
private readonly bridgeManager: BridgeManagerSink;
|
||||
private readonly onPacket: PacketSink;
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly pipeWatcher: PipeWatcher;
|
||||
private readonly ownsPipeWatcher: boolean;
|
||||
/** Watcher/API process enumeration — isolated + timeout-bounded by default
|
||||
* so a blocked native /proc walk can't freeze the loop (issue #158).
|
||||
* Resolves to `null` (UNKNOWN) on timeout/failure. */
|
||||
private readonly enumerate: () => Promise<HookProcessBaseInfo[] | null>;
|
||||
/** The owned enumerator (worker lifecycle), or null when a custom lister was
|
||||
* injected (tests) — nothing to tear down in that case. */
|
||||
private readonly enumerator: ProcessEnumerator | null;
|
||||
private readonly autoLoadOnDiscovery: boolean;
|
||||
private readonly onSessionsChangedRaw?: () => void;
|
||||
private readonly log: Logger;
|
||||
private readonly sessions = new Map<number, HookSession>();
|
||||
private readonly autoLoadAttempts = new Map<number, AutoLoadAttempt>();
|
||||
private readonly startPromise: Promise<void>;
|
||||
|
||||
private disposed = false;
|
||||
|
||||
constructor(deps: HookManagerDeps) {
|
||||
this.bridgeManager = deps.bridgeManager;
|
||||
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
|
||||
this.onSessionsChangedRaw = deps.onSessionsChanged;
|
||||
this.log = deps.log ?? createLogger('Hook');
|
||||
|
||||
this.injector = deps.injector ?? {
|
||||
inject: injectHookProcess,
|
||||
unload: (pid, handle) => {
|
||||
if (!handle) return;
|
||||
unloadHookProcess(pid, handle);
|
||||
},
|
||||
};
|
||||
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
|
||||
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
|
||||
|
||||
// A custom lister (tests) is used directly — no worker, no isolation, just
|
||||
// an async wrap that maps a throw to the UNKNOWN sentinel. The default path
|
||||
// wraps the native enumerator in a worker with a timeout.
|
||||
if (deps.listProcesses) {
|
||||
const lister = deps.listProcesses;
|
||||
this.enumerator = null;
|
||||
this.enumerate = async () => {
|
||||
try {
|
||||
return await lister();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
return null;
|
||||
}
|
||||
};
|
||||
} else {
|
||||
this.enumerator = createNativeProcessEnumerator({
|
||||
addonPath: resolveHookNativePath('node'),
|
||||
fallbackSync: listHookProcesses,
|
||||
processName: defaultProcessName(),
|
||||
log: this.log,
|
||||
});
|
||||
this.enumerate = () => this.enumerator!.enumerate();
|
||||
}
|
||||
|
||||
if (deps.pipeWatcher) {
|
||||
this.pipeWatcher = deps.pipeWatcher;
|
||||
this.ownsPipeWatcher = false;
|
||||
} else {
|
||||
this.pipeWatcher = new PipeWatcher({
|
||||
listProcesses: this.enumerate,
|
||||
listLivePipes: () => QqHookClient.listLivePipes(),
|
||||
intervalMs: deps.watcherIntervalMs,
|
||||
log: this.log,
|
||||
});
|
||||
this.ownsPipeWatcher = true;
|
||||
}
|
||||
|
||||
this.bindWatcher();
|
||||
this.startPromise = this.pipeWatcher.start();
|
||||
}
|
||||
|
||||
// ─────────────── public API (unchanged from prior HookManager) ───────────────
|
||||
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
await this.startPromise;
|
||||
const processes = await this.enumerate();
|
||||
if (processes === null) {
|
||||
// Enumeration timed out / failed — report the last-known sessions rather
|
||||
// than an empty list (which the WebUI would render as "no QQ").
|
||||
return [...this.sessions.values()]
|
||||
.map((s) => s.toInfo())
|
||||
.sort((a, b) => a.pid - b.pid);
|
||||
}
|
||||
const result: HookProcessInfo[] = [];
|
||||
for (const proc of processes) {
|
||||
const session = this.ensureSession(proc.pid);
|
||||
session.attachProcessInfo(proc);
|
||||
result.push(session.toInfo());
|
||||
}
|
||||
return result.sort((a, b) => a.pid - b.pid);
|
||||
}
|
||||
|
||||
async loadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
this.autoLoadAttempts.delete(pid);
|
||||
const session = this.ensureSession(pid);
|
||||
const info = await session.load();
|
||||
// Pull the next tick forward so a freshly-injected pipe gets noticed
|
||||
// within the next event-loop turn instead of after the full interval.
|
||||
this.pipeWatcher.wake();
|
||||
return info;
|
||||
}
|
||||
|
||||
async unloadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
this.autoLoadAttempts.delete(pid);
|
||||
const session = this.ensureSession(pid);
|
||||
return session.unload();
|
||||
}
|
||||
|
||||
async refreshProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
return session.refresh();
|
||||
}
|
||||
|
||||
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
this.assertValidPid(pid);
|
||||
return probeQqLoginInfo(pid);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── wiring ───────────────
|
||||
|
||||
private bindWatcher(): void {
|
||||
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
|
||||
if (this.disposed) return;
|
||||
runWithTraceRequest(() => {
|
||||
const session = this.ensureSession(info.pid);
|
||||
session.attachProcessInfo(info);
|
||||
this.log.trace(() => [
|
||||
'hook_manager_fact event=process_discovered pid=%d info=%s autoLoad=%s',
|
||||
info.pid,
|
||||
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
|
||||
// the session's status field.
|
||||
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
|
||||
this.runAutoLoad(session);
|
||||
}
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
});
|
||||
this.pipeWatcher.on('process-gone', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
runWithTraceRequest(() => {
|
||||
this.autoLoadAttempts.delete(pid);
|
||||
const session = this.sessions.get(pid);
|
||||
this.log.trace(
|
||||
'hook_manager_fact event=process_gone pid=%d tracked=%s',
|
||||
pid,
|
||||
session !== undefined,
|
||||
);
|
||||
if (session) session.notifyProcessGone();
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
});
|
||||
this.pipeWatcher.on('pipe-up', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.onPipeUp();
|
||||
});
|
||||
this.pipeWatcher.on('pipe-down', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.onPipeDown();
|
||||
});
|
||||
// After every tick, retry sessions that are stuck in 'connecting' OR
|
||||
// 'disconnected' while the pipe is up. Mirrors the original
|
||||
// tickWatcher's per-tick reconcileConnect pass; onPipeUp is idempotent
|
||||
// so calling it for an already-connected session is harmless.
|
||||
//
|
||||
// The 'disconnected' branch matters on Windows: when the QQ-NT side of
|
||||
// the named pipe stays alive but the SnowLuma-side socket dies (read
|
||||
// EPIPE / idle-timeout / similar transient I/O fault), the watcher
|
||||
// sees the pipe as still-live (the OS-level pipe is still listed by
|
||||
// `listLivePipes`) so it never fires another `pipe-up`. Without
|
||||
// retrying 'disconnected' sessions here the session is stranded
|
||||
// forever — a real-world symptom users reported as "Windows running
|
||||
// for a while then stops" with logs `pipe error: read EPIPE` →
|
||||
// `session closed: UIN=…`.
|
||||
this.pipeWatcher.on('tick', () => {
|
||||
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)) {
|
||||
this.runAutoLoad(session, autoLoad);
|
||||
continue;
|
||||
}
|
||||
if ((session.status === 'connecting' || session.status === 'disconnected')
|
||||
&& this.pipeWatcher.isPipeLive(session.pid)) {
|
||||
session.onPipeUp();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private runAutoLoad(session: HookSession, existing?: AutoLoadAttempt): void {
|
||||
if (this.disposed || session.isDisposed) return;
|
||||
const state = existing ?? { attempts: 0, inFlight: false };
|
||||
if (state.inFlight || state.attempts >= AUTO_LOAD_MAX_ATTEMPTS) return;
|
||||
|
||||
state.attempts += 1;
|
||||
state.inFlight = true;
|
||||
this.autoLoadAttempts.set(session.pid, state);
|
||||
const attempt = state.attempts;
|
||||
|
||||
void runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
this.log.trace(
|
||||
'hook_autoload_start pid=%d attempt=%d maxAttempts=%d',
|
||||
session.pid,
|
||||
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',
|
||||
session.pid,
|
||||
attempt,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return;
|
||||
}
|
||||
state.inFlight = false;
|
||||
|
||||
if (info.status !== 'error') {
|
||||
this.autoLoadAttempts.delete(session.pid);
|
||||
const reason = attempt > 1 ? 'recovered' : 'loaded';
|
||||
this.log.trace(() => [
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=completed reason=%s state=%s elapsedMs=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
reason,
|
||||
renderParamsVerbose(info),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
if (attempt > 1) {
|
||||
this.log.info(
|
||||
'auto-load recovered: PID=%d attempt=%d/%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
AUTO_LOAD_MAX_ATTEMPTS,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isTransientLibcMappingError(info.error)) {
|
||||
this.autoLoadAttempts.delete(session.pid);
|
||||
this.log.trace(
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=permanent_failure error=%j elapsedMs=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
info.error,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (attempt >= AUTO_LOAD_MAX_ATTEMPTS) {
|
||||
this.autoLoadAttempts.delete(session.pid);
|
||||
this.log.trace(
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_exhausted error=%j elapsedMs=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
info.error,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
this.log.warn(
|
||||
'auto-load retry exhausted: PID=%d attempts=%d err=%s',
|
||||
session.pid,
|
||||
attempt,
|
||||
info.error,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.log.trace(
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_pending error=%j elapsedMs=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
info.error,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
this.log.warn(
|
||||
'auto-load retry pending: PID=%d attempt=%d/%d err=%s',
|
||||
session.pid,
|
||||
attempt,
|
||||
AUTO_LOAD_MAX_ATTEMPTS,
|
||||
info.error,
|
||||
);
|
||||
} catch (err) {
|
||||
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,
|
||||
attempt,
|
||||
errMsg(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errMsg(err));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ensureSession(pid: number): HookSession {
|
||||
let session = this.sessions.get(pid);
|
||||
if (session) return session;
|
||||
|
||||
session = new HookSession(pid, {
|
||||
injector: this.injector,
|
||||
makeClient: this.makeClient,
|
||||
pipeWatcher: this.pipeWatcher,
|
||||
onPacket: this.onPacket,
|
||||
log: this.log,
|
||||
});
|
||||
session.attachProcessInfo({ name: defaultProcessName() });
|
||||
|
||||
session.on('login', (uin: string, sender) => {
|
||||
this.bridgeManager.onHookLogin(pid, uin, sender);
|
||||
});
|
||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
});
|
||||
session.on('receive-health-changed', (healthy: boolean) => {
|
||||
this.bridgeManager.onPidReceiveHealthChanged(pid, healthy);
|
||||
});
|
||||
// status-changed fires on EVERY internal status mutation, including the
|
||||
// ones reached via login / disconnected / refresh — subscribing here
|
||||
// alone covers every transition the WebUI processes view cares about.
|
||||
session.on('status-changed', () => {
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
session.on('disposed', () => {
|
||||
this.sessions.delete(pid);
|
||||
});
|
||||
|
||||
this.sessions.set(pid, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
/** Fire the optional sessions-changed hook with exceptions isolated.
|
||||
* 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;
|
||||
try {
|
||||
this.onSessionsChangedRaw();
|
||||
} catch (err) {
|
||||
this.log.warn('onSessionsChanged threw: %s', errMsg(err));
|
||||
}
|
||||
}
|
||||
|
||||
private assertValidPid(pid: number): void {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
}
|
||||
}
|
||||
|
||||
function defaultProcessName(): string {
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
|
||||
function isTransientLibcMappingError(error: string): boolean {
|
||||
return /^target process does not map \S*\/libc\.so\.6 while resolving mmap$/.test(error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter for auto-load only. Returns false for Linux Electron child
|
||||
* processes (zygote/renderer/gpu/utility), which the native enumerator
|
||||
* mis-classifies as "main QQ" because their cmdline contains "qq" and
|
||||
* they transiently inherit wrapper.node via fork copy-on-write.
|
||||
*
|
||||
* Injecting into a zygote spawns the hook's resolver thread inside it;
|
||||
* every renderer Electron later forks then inherits that thread + the
|
||||
* partially-init'd hook state, which breaks QQ's IPC and login UI.
|
||||
*
|
||||
* Manual loadProcess() bypasses this gate — the operator is responsible
|
||||
* for picking the right PID from WebUI.
|
||||
*/
|
||||
export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
|
||||
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;
|
||||
|
||||
let cmdline: string;
|
||||
try {
|
||||
cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
|
||||
} catch {
|
||||
// Can't read cmdline (process gone, permission, etc.) — let the
|
||||
// existing load() path handle it; if the process is dead the load
|
||||
// will fail with a clear error.
|
||||
return true;
|
||||
}
|
||||
if (cmdline.includes('--type=')) {
|
||||
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';
|
||||
@@ -1,811 +0,0 @@
|
||||
import {
|
||||
createLogger,
|
||||
runWithoutRequestContext,
|
||||
runWithTraceRequest,
|
||||
type Logger,
|
||||
} from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookPacketClient } from './hook-packet-client';
|
||||
import type { HookInjectResult } from './injector';
|
||||
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
|
||||
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
|
||||
import { statusFor } from './hook-status';
|
||||
import type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
|
||||
/** How often to actively re-probe QQ's login state while connected but not yet
|
||||
* logged in — the safety net for a login the native hook never pushed (Docker
|
||||
* auto-login races/bypasses the pushed loginState frame). */
|
||||
const LOGIN_RECONCILE_INTERVAL_MS = 3000;
|
||||
|
||||
/** QQ emits this response periodically while its MSF receive path is healthy.
|
||||
* Seeing it once arms the watchdog; before that, silence is UNKNOWN rather
|
||||
* than unhealthy so QQ versions that do not expose this command cannot be
|
||||
* false-flagged. Any later recv packet proves the same end-to-end path. */
|
||||
const QQ_RECV_HEARTBEAT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat';
|
||||
const RECEIVE_STALE_AFTER_MS = 90_000;
|
||||
const RECEIVE_STALE_CONFIRM_MS = 15_000;
|
||||
|
||||
export type HookSessionDeps = {
|
||||
injector: {
|
||||
inject: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
|
||||
unload: (pid: number, handle: HookInjectResult['handle']) => void;
|
||||
};
|
||||
makeClient: (pid: number) => QqHookClient;
|
||||
/** Active, pipe-independent login probe (reads QQ's ptlogin/deeplink ports).
|
||||
* Drives the login-reconcile safety net; injectable for tests. Defaults to
|
||||
* `probeQqLoginInfo`. */
|
||||
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
|
||||
/** Sync fast-path check used by load() to skip re-injection when a
|
||||
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
|
||||
* fresh poll — used after unload to dodge the up-to-1500ms cache
|
||||
* staleness that would otherwise false-flag a successful unload. */
|
||||
pipeWatcher: {
|
||||
isPipeLive: (pid: number) => boolean;
|
||||
tickNow?: () => Promise<void>;
|
||||
};
|
||||
/** Sink for parsed packets. Called with the BridgeManager-shaped
|
||||
* PacketInfo for every packet received while logged in. If omitted,
|
||||
* packets are dropped (useful in unit tests that don't care). */
|
||||
onPacket?: PacketSink;
|
||||
log?: Logger;
|
||||
};
|
||||
|
||||
/**
|
||||
* HookSession — owns the lifecycle of one QQ.exe process: injection,
|
||||
* pipe client, login state, and the public status field.
|
||||
*
|
||||
* Concurrency: every state-mutating method goes through a per-session
|
||||
* promise chain so user clicks (load/unload/refresh) and watcher-driven
|
||||
* events (onPipeUp/onPipeDown) never interleave.
|
||||
*
|
||||
* Communication: emits high-level events instead of calling BridgeManager
|
||||
* directly, so HookManager forwards them and tests can attach spies.
|
||||
*
|
||||
* Emitted events:
|
||||
* 'login' (uin, packetSender) — real-UIN login detected
|
||||
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
|
||||
* 'receive-health-changed' (healthy) — receive path confirmed stale/recovered
|
||||
* 'status-changed' (status, error) — status field mutated
|
||||
* 'disposed' () — session stopped tracking this PID
|
||||
*/
|
||||
export class HookSession extends EventEmitter {
|
||||
readonly pid: number;
|
||||
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly probeLogin: (pid: number) => Promise<QqPortLoginInfo | null>;
|
||||
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
|
||||
private readonly onPacket: PacketSink | null;
|
||||
private readonly log: Logger;
|
||||
|
||||
private _status: HookProcessStatus = 'available';
|
||||
private _error = '';
|
||||
private _uin = '0';
|
||||
private _method = '';
|
||||
private _name = '';
|
||||
private _path = '';
|
||||
|
||||
private injected = false;
|
||||
private connected = false;
|
||||
private loggedIn = false;
|
||||
private injectResult: HookInjectResult | null = null;
|
||||
private client: QqHookClient | null = null;
|
||||
private sender: HookPacketClient | null = null;
|
||||
private bound = false;
|
||||
private opChain: Promise<unknown> = Promise.resolve();
|
||||
private disposed = false;
|
||||
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private probing = false;
|
||||
private _receiveHealthy = true;
|
||||
private receiveWatchUin = '';
|
||||
private receiveWatchArmed = false;
|
||||
private receiveWatchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private lastReceiveAt = 0;
|
||||
|
||||
constructor(pid: number, deps: HookSessionDeps) {
|
||||
super();
|
||||
this.pid = pid;
|
||||
this.injector = deps.injector;
|
||||
this.makeClient = deps.makeClient;
|
||||
this.probeLogin = deps.probeLogin ?? probeQqLoginInfo;
|
||||
this.pipeWatcher = deps.pipeWatcher;
|
||||
this.onPacket = deps.onPacket ?? null;
|
||||
this.log = deps.log ?? createLogger('HookSession');
|
||||
}
|
||||
|
||||
// ─────────────── 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 receiveHealthy(): boolean { return this._receiveHealthy; }
|
||||
|
||||
attachProcessInfo(info: { name?: string; path?: string }): void {
|
||||
if (info.name) this._name = info.name;
|
||||
if (info.path) this._path = info.path;
|
||||
}
|
||||
|
||||
toInfo(): HookProcessInfo {
|
||||
return {
|
||||
pid: this.pid,
|
||||
name: this._name,
|
||||
path: this._path,
|
||||
injected: this.injected,
|
||||
connected: this.connected,
|
||||
loggedIn: this.loggedIn,
|
||||
uin: this._uin,
|
||||
status: this._status,
|
||||
error: this._error,
|
||||
method: this._method,
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────── user-facing commands ───────────────
|
||||
|
||||
load(): Promise<HookProcessInfo> {
|
||||
return this.traceCommand('load', () => this.loadInternal());
|
||||
}
|
||||
|
||||
unload(): Promise<HookProcessInfo> {
|
||||
return this.traceCommand('unload', () => this.unloadInternal());
|
||||
}
|
||||
|
||||
refresh(): Promise<HookProcessInfo> {
|
||||
return this.traceCommand('refresh', () => this.refreshInternal());
|
||||
}
|
||||
|
||||
// ─────────────── watcher-driven events (called by manager) ───────────────
|
||||
|
||||
/** Pipe came up (or stayed up across a SnowLuma restart). Drives connect
|
||||
* 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;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
await this.reconcilePipeUp();
|
||||
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
onPipeDown(): void {
|
||||
if (this.disposed) return;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
this.reconcilePipeDown();
|
||||
}).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;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.log.trace(() => [
|
||||
'hook_session_process_start pid=%d event=process_gone state=%s',
|
||||
this.pid,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
]);
|
||||
this.tearDownClient();
|
||||
this.injected = false;
|
||||
this.injectResult = null;
|
||||
this._method = '';
|
||||
this.setStatus('available', '');
|
||||
try {
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
this.disposed = true;
|
||||
this.emit('disposed');
|
||||
this.log.trace(() => [
|
||||
'hook_session_process_terminal pid=%d outcome=completed reason=process_gone wasLoggedIn=%s state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
wasLoggedIn,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
this.removeAllListeners();
|
||||
} catch (error) {
|
||||
this.log.trace(() => [
|
||||
'hook_session_process_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
errMsg(error),
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
this.tearDownClient();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
// ─────────────── per-session serialization ───────────────
|
||||
|
||||
private traceCommand(
|
||||
operation: 'load' | 'unload' | 'refresh',
|
||||
command: () => Promise<HookProcessInfo>,
|
||||
): Promise<HookProcessInfo> {
|
||||
return runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
this.log.trace(() => [
|
||||
'hook_session_start pid=%d operation=%s state=%s',
|
||||
this.pid,
|
||||
operation,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
]);
|
||||
try {
|
||||
const info = await this.serialize(command);
|
||||
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') {
|
||||
reason = `${operation}_failed`;
|
||||
} 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,
|
||||
operation,
|
||||
outcome,
|
||||
reason,
|
||||
info.error ? ` error=${JSON.stringify(info.error)}` : '',
|
||||
renderParamsVerbose(info),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
return info;
|
||||
} catch (error) {
|
||||
this.log.trace(() => [
|
||||
'hook_session_terminal pid=%d operation=%s outcome=failed reason=%s error=%j state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
operation,
|
||||
`${operation}_threw`,
|
||||
errMsg(error),
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private serialize<T>(op: () => Promise<T>): Promise<T> {
|
||||
const previous = this.opChain;
|
||||
let release!: () => void;
|
||||
const completion = new Promise<void>(resolve => { release = resolve; });
|
||||
this.opChain = previous.then(() => completion);
|
||||
return (async () => {
|
||||
try {
|
||||
await previous.catch(() => undefined);
|
||||
return await op();
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
// ─────────────── internal transitions ───────────────
|
||||
|
||||
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
|
||||
// resident in QQ.exe. If the watcher already sees a live pipe,
|
||||
// skip re-injection and let onPipeUp drive the reconnect.
|
||||
if (this.pipeWatcher.isPipeLive(this.pid)) {
|
||||
this.injected = true;
|
||||
this._method = this._method || 'reconnect';
|
||||
this.log.trace(
|
||||
'hook_session_branch pid=%d operation=load branch=existing_pipe method=%j',
|
||||
this.pid,
|
||||
this._method,
|
||||
);
|
||||
this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid);
|
||||
} else {
|
||||
this.log.trace(
|
||||
'hook_session_branch pid=%d operation=load branch=inject_begin',
|
||||
this.pid,
|
||||
);
|
||||
this.injectResult = await this.injector.inject(this.pid);
|
||||
this.injected = true;
|
||||
this._method = this.injectResult.method;
|
||||
this.log.trace(
|
||||
'hook_session_branch pid=%d operation=load branch=inject_completed method=%j',
|
||||
this.pid,
|
||||
this._method,
|
||||
);
|
||||
}
|
||||
}
|
||||
this.applyStatus();
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this.setStatus('error', this._error);
|
||||
this.log.error('load failed: PID=%d err=%s', this.pid, this._error);
|
||||
}
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
private async unloadInternal(): Promise<HookProcessInfo> {
|
||||
this._error = '';
|
||||
try {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
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);
|
||||
}
|
||||
|
||||
this.injected = false;
|
||||
this.injectResult = null;
|
||||
this._method = '';
|
||||
this._uin = '0';
|
||||
|
||||
// Verify the unload took: if the pipe is still up the DLL is still
|
||||
// resident. The cached snapshot is up to 1500ms stale and we just
|
||||
// changed the world, so force a fresh poll first — otherwise even
|
||||
// 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);
|
||||
this.log.warn('unload verification failed: PID=%d pipe still up', this.pid);
|
||||
} else {
|
||||
this.setStatus('available', '');
|
||||
}
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
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
|
||||
// onPipeUp/onPipeDown bodies — and fixes the drift where the down
|
||||
// branch reported 'disconnected' even for a never-logged-in session.
|
||||
if (this.pipeWatcher.isPipeLive(this.pid)) {
|
||||
await this.reconcilePipeUp();
|
||||
} else {
|
||||
this.reconcilePipeDown();
|
||||
}
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
|
||||
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
|
||||
}
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
// ─────────────── settled-status reconcilers ───────────────
|
||||
|
||||
/** Push the settled status derived from the live flags. `wasLoggedIn`
|
||||
* 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({
|
||||
injected: this.injected,
|
||||
connected: this.connected,
|
||||
loggedIn: this.loggedIn,
|
||||
wasLoggedIn,
|
||||
}), error);
|
||||
}
|
||||
|
||||
/** Pipe is up: adopt a DLL that survived a SnowLuma restart, drop a
|
||||
* stale client, then (re)connect if needed or just settle the status.
|
||||
* Shared by onPipeUp and refresh's pipe-up branch. */
|
||||
private async reconcilePipeUp(): Promise<void> {
|
||||
if (!this.injected) {
|
||||
this.injected = true;
|
||||
if (!this._method) this._method = 'reconnect';
|
||||
}
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.connected) {
|
||||
await this.attemptConnect();
|
||||
} else {
|
||||
this.applyStatus();
|
||||
}
|
||||
}
|
||||
|
||||
/** Pipe is down (or the client closed): tear down, settle the status,
|
||||
* and emit the disconnect notification iff we owed BridgeManager one
|
||||
* (i.e. we had reached login). Shared by onPipeDown, refresh's pipe-down
|
||||
* branch, and the client 'close' handler. */
|
||||
private reconcilePipeDown(): void {
|
||||
if (!this.connected) {
|
||||
// Nothing live to tear down. A session that never connected can't owe
|
||||
// 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);
|
||||
return;
|
||||
}
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.log.trace(() => [
|
||||
'hook_session_disconnect_start pid=%d reason=pipe_down state=%s',
|
||||
this.pid,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
]);
|
||||
this.tearDownClient();
|
||||
this.applyStatus(wasLoggedIn);
|
||||
try {
|
||||
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,
|
||||
wasLoggedIn,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
} catch (error) {
|
||||
this.log.trace(() => [
|
||||
'hook_session_disconnect_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
errMsg(error),
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─────────────── client plumbing ───────────────
|
||||
|
||||
private async attemptConnect(): Promise<void> {
|
||||
if (this.connected) return;
|
||||
return runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
this.log.trace(() => [
|
||||
'hook_session_connect_start pid=%d state=%s',
|
||||
this.pid,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
]);
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.client) {
|
||||
this.client = this.makeClient(this.pid);
|
||||
this.sender = new HookPacketClient(this.client);
|
||||
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'.
|
||||
if (loginState.loggedIn) {
|
||||
this.handleLoginState(loginState);
|
||||
} else {
|
||||
this.applyStatus();
|
||||
// The native hook only PUSHES a loginState frame on the login edge;
|
||||
// if QQ logged in before/around connect (Docker auto-login) that edge
|
||||
// is missed and we'd wait forever. Actively re-probe until logged in.
|
||||
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',
|
||||
this.pid,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
// Drop the client so the next attempt builds a fresh socket pair.
|
||||
// A failed connect was never logged in → 'connecting' (or 'available').
|
||||
this.tearDownClient();
|
||||
this.applyStatus(false, this._error);
|
||||
this.log.trace(() => [
|
||||
'hook_session_connect_terminal pid=%d outcome=failed reason=connect_failed error=%j state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
this._error,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private bindClient(client: QqHookClient): void {
|
||||
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;
|
||||
// Only the currently-registered client should drive a reconcile;
|
||||
// listeners may fire for an already-replaced client.
|
||||
if (this.client !== client) return;
|
||||
void this.serialize(async () => {
|
||||
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)));
|
||||
});
|
||||
}
|
||||
|
||||
private tearDownClient(): void {
|
||||
this.stopLoginReconcile();
|
||||
this.resetReceiveWatch();
|
||||
const client = this.client;
|
||||
if (client) {
|
||||
client.removeAllListeners();
|
||||
try { client.close(); } catch { /* ignore */ }
|
||||
}
|
||||
this.client = null;
|
||||
this.sender = null;
|
||||
this.bound = false;
|
||||
this.connected = false;
|
||||
this.loggedIn = false;
|
||||
}
|
||||
|
||||
private handleLoginState(state: QqHookLoginState): void {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
const previousUin = this._uin;
|
||||
this._uin = state.uin || state.uinNumber.toString();
|
||||
this.loggedIn = state.loggedIn && isRealUin(this._uin);
|
||||
// However login was observed (pushed frame or the active probe), the
|
||||
// safety net's job is done.
|
||||
if (this.loggedIn) {
|
||||
this.stopLoginReconcile();
|
||||
// A PID can switch accounts without an intermediate logout edge. Never
|
||||
// carry the previous account's heartbeat deadline into the new epoch.
|
||||
if (this.receiveWatchUin !== this._uin) this.resetReceiveWatch(this._uin);
|
||||
} else {
|
||||
this.resetReceiveWatch();
|
||||
}
|
||||
|
||||
// Only the connected/logged-in states are ours to set here; when fully
|
||||
// down we leave the status the teardown path already settled.
|
||||
// Load-bearing invariant: `loggedIn ⇒ connected` (login can only be
|
||||
// observed on a live client, and teardown clears `loggedIn` before
|
||||
// `connected`), so statusFor lands 'online' here rather than the
|
||||
// disconnected/connecting branch.
|
||||
if (this.connected || this.loggedIn) {
|
||||
this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error);
|
||||
}
|
||||
|
||||
if (!this.loggedIn || !this.sender) return;
|
||||
if (wasLoggedIn && previousUin === this._uin) return;
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
this.log.trace(
|
||||
'hook_session_login_start pid=%d previousUin=%j uin=%j',
|
||||
this.pid,
|
||||
previousUin,
|
||||
this._uin,
|
||||
);
|
||||
try {
|
||||
this.emit('login', this._uin, this.sender!);
|
||||
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
|
||||
this.log.trace(() => [
|
||||
'hook_session_login_terminal pid=%d outcome=completed reason=login_detected previousUin=%j uin=%j state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
previousUin,
|
||||
this._uin,
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
} catch (error) {
|
||||
this.log.trace(() => [
|
||||
'hook_session_login_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
errMsg(error),
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─────────────── login reconcile (Docker auto-login safety net) ───────────
|
||||
// The hook's loginState frame is edge-triggered (pushed only when the native
|
||||
// observes the login transition). When that edge is missed — QQ auto-logged
|
||||
// in before connect, or a silent session-restore path the hook doesn't
|
||||
// intercept — we'd sit at 'loaded'/'connecting' forever. So while connected
|
||||
// but not logged in, actively re-probe QQ's own ports and synthesize the
|
||||
// login once it reports a real uin. Idempotent with the pushed-frame path
|
||||
// (handleLoginState's wasLoggedIn guard dedups the 'login' emit).
|
||||
|
||||
private startLoginReconcile(): void {
|
||||
if (this.loginProbeTimer || this.disposed) return;
|
||||
void this.probeLoginOnce(); // immediate — catch already-logged-in fast
|
||||
this.loginProbeTimer = setInterval(() => void this.probeLoginOnce(), LOGIN_RECONCILE_INTERVAL_MS);
|
||||
this.loginProbeTimer.unref?.();
|
||||
}
|
||||
|
||||
private stopLoginReconcile(): void {
|
||||
if (this.loginProbeTimer) {
|
||||
clearInterval(this.loginProbeTimer);
|
||||
this.loginProbeTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private async probeLoginOnce(): Promise<void> {
|
||||
// A port-scan probe can outlast the interval; skip overlapping ticks so a
|
||||
// slow probe never stacks concurrent subprocess-spawning scans.
|
||||
if (this.probing) return;
|
||||
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
|
||||
this.probing = true;
|
||||
try {
|
||||
let info: QqPortLoginInfo | null;
|
||||
try {
|
||||
info = await this.probeLogin(this.pid);
|
||||
} catch {
|
||||
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?.loggedIn && isRealUin(info.uin)) {
|
||||
this.log.info('login reconciled via active probe: PID=%d UIN=%s', this.pid, info.uin);
|
||||
// isRealUin guarantees a pure non-empty digit string, so BigInt() here
|
||||
// cannot throw (keep that contract if isRealUin's regex is ever changed).
|
||||
// Reconcile through QqHookClient instead of mutating HookSession alone:
|
||||
// packet sending and login waiters must observe the same state before
|
||||
// the login event starts Bridge / OneBot initialization.
|
||||
this.client!.reconcileLoginState({
|
||||
loggedIn: true,
|
||||
uin: info.uin,
|
||||
uinNumber: BigInt(info.uin),
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
this.probing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private handlePacket(packet: QqHookPacket): void {
|
||||
if (!this.loggedIn) return;
|
||||
const uin = packet.uin || this._uin;
|
||||
// Routing requires a real UIN, but even a frame carrying UIN=0 proves the
|
||||
// receive hook is alive. Attribute that evidence to the current epoch
|
||||
// without forwarding the malformed packet into BridgeManager.
|
||||
const receiveUin = isRealUin(uin) ? uin : (this.receiveWatchUin || this._uin);
|
||||
if (isRealUin(receiveUin)) this.noteReceiveActivity(packet.cmd, receiveUin);
|
||||
if (!isRealUin(uin)) return;
|
||||
if (!this.onPacket) return;
|
||||
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
|
||||
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
|
||||
// renaming was that module's entire purpose, so it lives at the source
|
||||
// now (no need for a single-listener event-emitter in between).
|
||||
this.onPacket({
|
||||
pid: this.pid,
|
||||
uin,
|
||||
serviceCmd: packet.cmd,
|
||||
seqId: packet.seq,
|
||||
retCode: packet.error,
|
||||
fromClient: false,
|
||||
body: Buffer.from(packet.body),
|
||||
});
|
||||
}
|
||||
|
||||
private setStatus(status: HookProcessStatus, error: string): void {
|
||||
if (this._status === status && this._error === error) return;
|
||||
this._status = status;
|
||||
this._error = error;
|
||||
this.emit('status-changed', status, error);
|
||||
}
|
||||
|
||||
private noteReceiveActivity(cmd: string, uin: string): void {
|
||||
// BridgeManager treats packet.uin as authoritative and may move this PID
|
||||
// before the next loginState edge. Keep the watchdog on that same epoch.
|
||||
if (this.receiveWatchUin !== uin) this.resetReceiveWatch(uin);
|
||||
|
||||
if (!this.receiveWatchArmed) {
|
||||
if (cmd !== QQ_RECV_HEARTBEAT_CMD) return;
|
||||
this.receiveWatchArmed = true;
|
||||
this.log.debug('receive health armed by QQ heartbeat: PID=%d UIN=%s', this.pid, this.receiveWatchUin);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const silentForMs = this.lastReceiveAt > 0 ? now - this.lastReceiveAt : 0;
|
||||
this.lastReceiveAt = now;
|
||||
this.scheduleReceiveStaleCheck();
|
||||
|
||||
if (!this._receiveHealthy) {
|
||||
this.setReceiveHealthy(true);
|
||||
this.log.info(
|
||||
'receive path recovered: PID=%d UIN=%s silentFor=%dms',
|
||||
this.pid,
|
||||
this.receiveWatchUin,
|
||||
silentForMs,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleReceiveStaleCheck(): void {
|
||||
if (this.receiveWatchTimer) clearTimeout(this.receiveWatchTimer);
|
||||
this.receiveWatchTimer = setTimeout(() => {
|
||||
this.receiveWatchTimer = null;
|
||||
if (!this.shouldWatchReceive()) return;
|
||||
|
||||
// A delayed event loop (notably system sleep/resume) lands here long
|
||||
// after the nominal 90s deadline. Do not flip health immediately: give
|
||||
// the real QQ heartbeat one short confirmation window to arrive.
|
||||
this.receiveWatchTimer = setTimeout(() => {
|
||||
this.receiveWatchTimer = null;
|
||||
if (!this.shouldWatchReceive()) return;
|
||||
const silentForMs = Date.now() - this.lastReceiveAt;
|
||||
if (silentForMs < RECEIVE_STALE_AFTER_MS + RECEIVE_STALE_CONFIRM_MS) {
|
||||
this.scheduleReceiveStaleCheck();
|
||||
return;
|
||||
}
|
||||
this.setReceiveHealthy(false);
|
||||
this.log.warn(
|
||||
'receive path stale: PID=%d UIN=%s lastRecvAt=%s silentFor=%dms; reporting good=false',
|
||||
this.pid,
|
||||
this.receiveWatchUin,
|
||||
new Date(this.lastReceiveAt).toISOString(),
|
||||
silentForMs,
|
||||
);
|
||||
}, RECEIVE_STALE_CONFIRM_MS);
|
||||
this.receiveWatchTimer.unref?.();
|
||||
}, RECEIVE_STALE_AFTER_MS);
|
||||
this.receiveWatchTimer.unref?.();
|
||||
}
|
||||
|
||||
private shouldWatchReceive(): boolean {
|
||||
return !this.disposed && this.connected && this.loggedIn && this.receiveWatchArmed;
|
||||
}
|
||||
|
||||
private setReceiveHealthy(healthy: boolean): void {
|
||||
if (this._receiveHealthy === healthy) return;
|
||||
this._receiveHealthy = healthy;
|
||||
this.emit('receive-health-changed', healthy);
|
||||
}
|
||||
|
||||
private resetReceiveWatch(uin = ''): void {
|
||||
if (this.receiveWatchTimer) {
|
||||
clearTimeout(this.receiveWatchTimer);
|
||||
this.receiveWatchTimer = null;
|
||||
}
|
||||
this.receiveWatchUin = uin;
|
||||
this.receiveWatchArmed = false;
|
||||
this.lastReceiveAt = 0;
|
||||
this._receiveHealthy = true;
|
||||
}
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import type { HookProcessStatus } from './types';
|
||||
|
||||
/**
|
||||
* The flags that fully determine a HookSession's *settled* status.
|
||||
* `wasLoggedIn` carries the one bit of history the derivation needs:
|
||||
* on ANY injected-but-not-connected path (connect failure, pipe close,
|
||||
* refresh-while-down), the session reads `disconnected` only if it had
|
||||
* reached login, otherwise it's still `connecting`. Capture it from
|
||||
* `loggedIn` *before* tearing the client down, since teardown clears it.
|
||||
*/
|
||||
export interface HookFlags {
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
wasLoggedIn: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single source of truth for the five *settled* HookProcessStatus values
|
||||
* — `available` / `connecting` / `loaded` / `online` / `disconnected`.
|
||||
*
|
||||
* Pure: status is a function of the flags alone. The two *out-of-band*
|
||||
* states `loading` (injection in flight) and `error` (carries a message)
|
||||
* are set explicitly by HookSession and are deliberately NOT derivable
|
||||
* here.
|
||||
*/
|
||||
export function statusFor(flags: HookFlags): HookProcessStatus {
|
||||
if (!flags.injected) return 'available';
|
||||
if (flags.connected) return flags.loggedIn ? 'online' : 'loaded';
|
||||
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
export {
|
||||
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
|
||||
type HookProcessStatus, type QqPortLoginInfo
|
||||
} from './hook-manager';
|
||||
|
||||
@@ -1,238 +0,0 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { Worker } from 'worker_threads';
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
/**
|
||||
* Isolated, timeout-bounded wrapper around the native `getAllMainProcess()`
|
||||
* enumeration.
|
||||
*
|
||||
* Why this exists (issue #158): the watcher polls QQ processes every ~1.5s by
|
||||
* calling the synchronous native enumerator, which walks `/proc` and reads each
|
||||
* candidate's `cmdline`/`maps`. Those reads go through the target's mm and
|
||||
* BLOCK while a process is mid-`exec()` — exactly what happens when QQ runs a
|
||||
* silent hot-update and the process table churns. A blocked synchronous native
|
||||
* call freezes the whole Node event loop: OneBot stops responding, the watcher
|
||||
* stops ticking, reconnect logic never runs. The process stays "alive" so the
|
||||
* supervisor never restarts it — the bot just goes silent.
|
||||
*
|
||||
* The only way to put a real timeout on a synchronous native call is to run it
|
||||
* off the main thread. We run it in a worker; the main thread races the result
|
||||
* against a deadline. On timeout the main loop keeps going (it returns the
|
||||
* UNKNOWN sentinel `null`, which the watcher treats as "no fresh data, keep
|
||||
* prior state" — crucially NOT "all processes gone"). The blocked worker is
|
||||
* abandoned (a fresh one is spawned next time); it exits on its own once the
|
||||
* native call finally returns.
|
||||
*
|
||||
* Graceful degradation: if the native addon can't be loaded in a worker (e.g.
|
||||
* it isn't context-aware) or there's no addon at all (macOS reads sockets, not
|
||||
* `/proc`), we fall back to calling `fallbackSync` on the main thread — i.e.
|
||||
* exactly today's behaviour, no worse.
|
||||
*/
|
||||
export interface ProcessEnumerator {
|
||||
/** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed
|
||||
* out / failed and the caller should keep its prior state. */
|
||||
enumerate(): Promise<HookProcessBaseInfo[] | null>;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export interface NativeEnumeratorDeps {
|
||||
/** Resolved path to the hook `.node` addon, or null when there is none
|
||||
* (macOS / missing) — in which case we never spawn a worker. */
|
||||
addonPath: string | null;
|
||||
/** Synchronous lister used when worker isolation is unavailable. Returns
|
||||
* today's value (and may itself block — that's the no-worse-than-before
|
||||
* fallback). */
|
||||
fallbackSync: () => HookProcessBaseInfo[];
|
||||
/** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */
|
||||
processName: string;
|
||||
/** Per-enumeration deadline. Default 4000ms — comfortably above a healthy
|
||||
* enumeration (single-digit ms) but well under a human "is it dead?". */
|
||||
timeoutMs?: number;
|
||||
/** Cap on abandoned (blocked) workers before we stop spawning more and just
|
||||
* return UNKNOWN until they drain. Bounds thread growth across a long
|
||||
* hot-update window. Default 4. */
|
||||
maxOrphans?: number;
|
||||
log?: Logger;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4000;
|
||||
const DEFAULT_MAX_ORPHANS = 4;
|
||||
|
||||
// Worker body (CommonJS — eval workers default to CJS so `require` is available;
|
||||
// `process.dlopen` is a global and needs no module system). Loads the addon
|
||||
// handed in via workerData, then answers each 'enumerate' with the raw pid list
|
||||
// from the blocking native call. All the cheap post-processing stays on main.
|
||||
const WORKER_SOURCE = `
|
||||
const { parentPort, workerData } = require('node:worker_threads');
|
||||
let addon = null;
|
||||
try {
|
||||
const mod = { exports: {} };
|
||||
process.dlopen(mod, workerData.addonPath);
|
||||
addon = mod.exports;
|
||||
} catch (e) {
|
||||
parentPort.postMessage({ type: 'fatal', error: String((e && e.message) || e) });
|
||||
}
|
||||
if (addon) {
|
||||
parentPort.on('message', (msg) => {
|
||||
if (!msg || msg.type !== 'enumerate') return;
|
||||
try {
|
||||
const pids = addon.getAllMainProcess();
|
||||
parentPort.postMessage({ type: 'result', id: msg.id, pids: Array.from(pids) });
|
||||
} catch (e) {
|
||||
parentPort.postMessage({ type: 'error', id: msg.id, error: String((e && e.message) || e) });
|
||||
}
|
||||
});
|
||||
parentPort.postMessage({ type: 'ready' });
|
||||
}
|
||||
`;
|
||||
|
||||
function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] {
|
||||
return [...new Set(pids)]
|
||||
.filter((pid) => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map((pid) => ({ pid, name: processName, path: '' }));
|
||||
}
|
||||
|
||||
export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator {
|
||||
const log = deps.log ?? createLogger('ProcessEnumerator');
|
||||
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
|
||||
|
||||
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
|
||||
// fallback there is a cheap socket read, not a /proc walk.
|
||||
if (!deps.addonPath) {
|
||||
return {
|
||||
async enumerate() {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
},
|
||||
dispose() { /* nothing to tear down */ },
|
||||
};
|
||||
}
|
||||
|
||||
const addonPath = deps.addonPath;
|
||||
let worker: Worker | null = null;
|
||||
/** Set once we learn the addon can't load in a worker — permanent fallback. */
|
||||
let isolationBroken = false;
|
||||
let orphans = 0;
|
||||
let seq = 0;
|
||||
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
|
||||
let disposed = false;
|
||||
|
||||
const spawnWorker = (): void => {
|
||||
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
|
||||
worker = w;
|
||||
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
|
||||
if (msg.type === 'ready') return;
|
||||
if (msg.type === 'fatal') {
|
||||
// The addon won't load off-thread — give up on isolation for good and
|
||||
// fall back to the synchronous path from here on. Resolve any in-flight
|
||||
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
|
||||
log.warn('process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration', msg.error ?? '');
|
||||
isolationBroken = true;
|
||||
for (const { resolve } of pending.values()) resolve(null);
|
||||
pending.clear();
|
||||
teardownWorker();
|
||||
return;
|
||||
}
|
||||
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
|
||||
const entry = pending.get(msg.id);
|
||||
if (!entry) return;
|
||||
pending.delete(msg.id);
|
||||
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
|
||||
}
|
||||
});
|
||||
w.on('error', (err) => {
|
||||
log.warn('enumeration worker error: %s', errMsg(err));
|
||||
if (worker === w) teardownWorker();
|
||||
});
|
||||
};
|
||||
|
||||
const teardownWorker = (): void => {
|
||||
const w = worker;
|
||||
worker = null;
|
||||
if (!w) return;
|
||||
// terminate() can't preempt a thread blocked in the native call; it takes
|
||||
// effect once the call returns. Track it as an orphan until it actually
|
||||
// exits so we can bound how many we let pile up.
|
||||
orphans += 1;
|
||||
w.once('exit', () => { orphans = Math.max(0, orphans - 1); });
|
||||
void w.terminate().catch(() => { /* already gone */ });
|
||||
};
|
||||
|
||||
const syncFallback = (): HookProcessBaseInfo[] | null => {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate sync fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
|
||||
if (disposed || isolationBroken) return syncFallback();
|
||||
|
||||
if (!worker) {
|
||||
if (orphans >= maxOrphans) {
|
||||
// Too many blocked workers already piling up (a sustained hang) —
|
||||
// don't spawn more; report UNKNOWN and let them drain.
|
||||
return null;
|
||||
}
|
||||
spawnWorker();
|
||||
}
|
||||
const w = worker;
|
||||
if (!w) return syncFallback();
|
||||
|
||||
const id = ++seq;
|
||||
const resultPromise = new Promise<number[] | null>((resolve) => {
|
||||
pending.set(id, { resolve });
|
||||
});
|
||||
try {
|
||||
w.postMessage({ type: 'enumerate', id });
|
||||
} catch (err) {
|
||||
pending.delete(id);
|
||||
log.warn('failed to post enumerate request: %s', errMsg(err));
|
||||
teardownWorker();
|
||||
return syncFallback();
|
||||
}
|
||||
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<'timeout'>((resolve) => {
|
||||
timer = setTimeout(() => resolve('timeout'), timeoutMs);
|
||||
});
|
||||
const outcome = await Promise.race([resultPromise, timeout]);
|
||||
if (timer) clearTimeout(timer);
|
||||
|
||||
if (outcome === 'timeout') {
|
||||
pending.delete(id);
|
||||
log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs);
|
||||
teardownWorker();
|
||||
return null;
|
||||
}
|
||||
if (outcome === null) {
|
||||
// Native call threw inside the worker — treat as a transient failure,
|
||||
// keep prior state rather than nuking every session.
|
||||
return null;
|
||||
}
|
||||
return mapPids(outcome, deps.processName);
|
||||
},
|
||||
|
||||
dispose() {
|
||||
disposed = true;
|
||||
for (const { resolve } of pending.values()) resolve(null);
|
||||
pending.clear();
|
||||
const w = worker;
|
||||
worker = null;
|
||||
if (w) void w.terminate().catch(() => { /* ignore */ });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -1,327 +0,0 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { exec } from 'child_process';
|
||||
import net from 'net';
|
||||
import http from 'http';
|
||||
import https from 'https';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
const log = createLogger('LoginProbe');
|
||||
|
||||
const PORT_RANGE_START = 9210;
|
||||
const PORT_RANGE_END = 9219;
|
||||
const PROBE_TIMEOUT_MS = 1000;
|
||||
const CONNECTION_TIMEOUT_MS = 500;
|
||||
const COMMAND_TIMEOUT_MS = 1500;
|
||||
const OVERALL_PROBE_TIMEOUT_MS = 5000;
|
||||
const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as const };
|
||||
// QQ's Ptlogin quick-login ports plus its main process mean a single
|
||||
// logged-in client surfaces roughly this many processes. When no usable
|
||||
// probe port is found, a count BELOW this implies the target PID is still at
|
||||
// the login screen; AT/ABOVE it the environment is ambiguous (multiple or
|
||||
// unrelated `qq` processes), so we fall through to deep-link probing rather
|
||||
// than guess "logged out".
|
||||
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
|
||||
|
||||
export interface QqPortLoginInfo {
|
||||
port: number;
|
||||
uin: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
loggedIn: boolean;
|
||||
}
|
||||
|
||||
interface JwtPayload {
|
||||
errCode: number;
|
||||
errMsg: string;
|
||||
port: number;
|
||||
uin?: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
data?: {
|
||||
uin?: string;
|
||||
url?: string;
|
||||
};
|
||||
iat: number;
|
||||
}
|
||||
|
||||
function decodeJwt(token: string): JwtPayload | null {
|
||||
try {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) return null;
|
||||
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
|
||||
return JSON.parse(payload);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
|
||||
return new Promise((resolve) => {
|
||||
const client = new net.Socket();
|
||||
const link = 'tencent://';
|
||||
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
|
||||
|
||||
let responseData = '';
|
||||
let timer: NodeJS.Timeout;
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
client.removeAllListeners();
|
||||
client.destroy();
|
||||
};
|
||||
|
||||
timer = setTimeout(() => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
}, PROBE_TIMEOUT_MS);
|
||||
|
||||
client.setTimeout(CONNECTION_TIMEOUT_MS);
|
||||
|
||||
client.connect(port, '127.0.0.1', () => {
|
||||
client.write(payload);
|
||||
});
|
||||
|
||||
client.on('data', (data) => {
|
||||
responseData += data.toString();
|
||||
});
|
||||
|
||||
client.on('close', () => {
|
||||
cleanup();
|
||||
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
|
||||
if (!jwtMatch) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const decoded = decodeJwt(jwtMatch[0]);
|
||||
if (!decoded || decoded.errCode !== 0) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const uin = decoded.uin || decoded.data?.uin || '';
|
||||
resolve({
|
||||
port,
|
||||
uin,
|
||||
uid: decoded.uid,
|
||||
nickName: decoded.nickName,
|
||||
loggedIn: uin.length > 0,
|
||||
});
|
||||
});
|
||||
|
||||
client.on('error', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
|
||||
client.on('timeout', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the
|
||||
* probe reads are modelled; QQ sends more but they're irrelevant here. */
|
||||
interface PtloginUin {
|
||||
uin?: string | number;
|
||||
account?: string | number;
|
||||
nickname?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One `pt_get_uins` call. Returns the parsed account array (possibly empty —
|
||||
* an EMPTY array is a real answer: "0 accounts", NOT an error) or `null` when
|
||||
* the port could not be reached / the body was not a usable pt_get_uins
|
||||
* response (connect refused, timeout, unparseable). Callers MUST distinguish
|
||||
* the two: `[]` feeds the logged-in/out decision, `null` means "network
|
||||
* problem, no answer" and should fall through to the deep-link fallback.
|
||||
*/
|
||||
async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin[] | null> {
|
||||
return new Promise((resolve) => {
|
||||
const protocol = useHttps ? 'https' : 'http';
|
||||
const url = `${protocol}://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
|
||||
|
||||
const headers = {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
};
|
||||
|
||||
const handleResponse = (res: http.IncomingMessage) => {
|
||||
let text = '';
|
||||
res.on('data', (chunk) => { text += chunk.toString(); });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const inner = text.split('[')[1].split(']')[0];
|
||||
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
|
||||
resolve(data);
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const req = useHttps
|
||||
? https.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false }, handleResponse)
|
||||
: http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse);
|
||||
|
||||
req.on('error', () => resolve(null));
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
|
||||
const useHttps = port % 2 !== 0;
|
||||
|
||||
const res1 = await fetchPtlogin(port, useHttps);
|
||||
const res2 = await fetchPtlogin(port, useHttps);
|
||||
|
||||
if (res1 === null && res2 === null) return 'fallback';
|
||||
|
||||
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
|
||||
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
|
||||
|
||||
if (target.length === 1) {
|
||||
const account = target[0];
|
||||
return {
|
||||
port,
|
||||
uin: String(account.uin || account.account || ''),
|
||||
nickName: account.nickname || '',
|
||||
loggedIn: true,
|
||||
};
|
||||
}
|
||||
|
||||
return 'fallback';
|
||||
}
|
||||
|
||||
|
||||
async function getQqProcessCount(): Promise<number> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync(
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh',
|
||||
EXEC_OPTIONS,
|
||||
);
|
||||
return stdout.toLowerCase().split('\n').filter(line => line.includes('qq.exe')).length;
|
||||
} else {
|
||||
const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS);
|
||||
return parseInt(stdout.trim(), 10) || 0;
|
||||
}
|
||||
} catch {
|
||||
// On failure report the ambiguous threshold so we never falsely
|
||||
// conclude "logged out".
|
||||
return LOGGED_OUT_PROCESS_COUNT_MAX;
|
||||
}
|
||||
}
|
||||
|
||||
async function getProcessPorts(pid: number): Promise<number[] | null> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
if (parts.length < 5) continue;
|
||||
const owningPid = parts[parts.length - 1];
|
||||
if (owningPid !== String(pid)) continue;
|
||||
|
||||
const localAddr = parts[1];
|
||||
const portMatch = localAddr.match(/:(\d+)$/);
|
||||
if (!portMatch) continue;
|
||||
ports.add(Number(portMatch[1]));
|
||||
}
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
const { stdout } = await execAsync('ss -tlnp', EXEC_OPTIONS);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) continue;
|
||||
const match = line.match(/:(\d+)\s/);
|
||||
if (match) {
|
||||
ports.add(Number(match[1]));
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
if (ports === null) return null;
|
||||
|
||||
if (ports.length === 0) {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return { port: 0, uin: '', loggedIn: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
|
||||
|
||||
const matchedOddPorts = ports.filter(p => ODD_PT_PORTS.includes(p));
|
||||
const matchedEvenPorts = ports.filter(p => EVEN_PT_PORTS.includes(p));
|
||||
|
||||
let ptPortsToTry: number[] = [];
|
||||
if (matchedOddPorts.length > 0) {
|
||||
ptPortsToTry = matchedOddPorts;
|
||||
} else if (matchedEvenPorts.length > 0) {
|
||||
ptPortsToTry = matchedEvenPorts;
|
||||
}
|
||||
|
||||
if (ptPortsToTry.length > 0) {
|
||||
for (const port of ptPortsToTry) {
|
||||
const ptResult = await tryPtloginMethod(port);
|
||||
if (ptResult !== 'fallback') {
|
||||
return ptResult;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return {
|
||||
port: ports[0] || 0,
|
||||
uin: '',
|
||||
loggedIn: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const deepLinkPorts = ports.filter(p => p >= PORT_RANGE_START && p <= PORT_RANGE_END);
|
||||
for (const port of deepLinkPorts) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let timedOut = false;
|
||||
const timeout = new Promise<null>(resolve => {
|
||||
timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
resolve(null);
|
||||
}, OVERALL_PROBE_TIMEOUT_MS);
|
||||
});
|
||||
try {
|
||||
const result = await Promise.race([probeQqLoginInfoInternal(pid), timeout]);
|
||||
if (timedOut) log.warn('login check timed out: PID=%d', pid);
|
||||
return result;
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookManager } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
// Regression cover for the WebUI SSE wiring: HookManager must call its
|
||||
// optional `onSessionsChanged` callback every time the observable set of
|
||||
// HookProcessInfo (what `listProcesses()` would return) changes, so the
|
||||
// /api/state/stream handler can push a fresh processes snapshot to the
|
||||
// browser without REST polling.
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
|
||||
interface Harness {
|
||||
manager: HookManager;
|
||||
pipeWatcher: PipeWatcher;
|
||||
bridgeManager: BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
setProcesses: (next: number[]) => void;
|
||||
setLivePipes: (next: number[]) => void;
|
||||
onSessionsChanged: ReturnType<typeof vi.fn>;
|
||||
clientFactory: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
|
||||
function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness {
|
||||
let pids = opts.processes ?? [];
|
||||
let live = new Set<number>(opts.livePipes ?? []);
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
const clientFactory = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { /* succeed without doing anything */ };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
onPidReceiveHealthChanged: vi.fn(),
|
||||
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
const onSessionsChanged = vi.fn();
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: clientFactory,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
onSessionsChanged,
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
pipeWatcher,
|
||||
bridgeManager,
|
||||
onSessionsChanged,
|
||||
clientFactory,
|
||||
setProcesses: (next) => { pids = next; },
|
||||
setLivePipes: (next) => { live = new Set(next); },
|
||||
};
|
||||
}
|
||||
|
||||
describe('HookManager.onSessionsChanged', () => {
|
||||
it('fires when the watcher discovers a new QQ process', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
await ctx.pipeWatcher.start();
|
||||
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports a process is gone', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
// Inject so the session is in 'connecting' state; the next pipe-up
|
||||
// makes attemptConnect succeed and status flips to 'loaded'.
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setLivePipes([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
ctx.onSessionsChanged.mockImplementation(() => { throw new Error('listener boom'); });
|
||||
await ctx.pipeWatcher.start();
|
||||
ctx.setProcesses([4242]);
|
||||
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
|
||||
await flush();
|
||||
// A second tick still fires the callback — it wasn't unregistered by
|
||||
// the prior throw.
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
ctx.setProcesses([4242, 5555]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
|
||||
const pids = [4242];
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
const manager = new HookManager({
|
||||
bridgeManager: {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: vi.fn(() => {
|
||||
const c = new EventEmitter() as any;
|
||||
c.isClosed = false; c.isLoggedIn = false;
|
||||
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
c.connectAll = async () => undefined;
|
||||
c.close = () => { c.isClosed = true; };
|
||||
return c;
|
||||
}),
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
// onSessionsChanged deliberately omitted
|
||||
});
|
||||
await pipeWatcher.start();
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
const list = await manager.listProcesses();
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0].pid).toBe(4242);
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookManager receive-health wiring (#233)', () => {
|
||||
it('forwards stale and recovered receive health for the owning PID', async () => {
|
||||
const ctx = makeManager({ processes: [4242], livePipes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await ctx.manager.refreshProcess(4242);
|
||||
await flush();
|
||||
|
||||
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
try {
|
||||
client.emit('packet', {
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
vi.advanceTimersByTime(105_000);
|
||||
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenCalledWith(4242, false);
|
||||
|
||||
client.emit('packet', {
|
||||
seq: 2,
|
||||
error: 0,
|
||||
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(4242, true);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,428 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { HookInjectResult, ManualMapHandle } from '../src/injector';
|
||||
import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
import {
|
||||
createLogger,
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function managerTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter(
|
||||
(entry) => entry.level === 'trace' && entry.scope === 'Hook',
|
||||
);
|
||||
}
|
||||
|
||||
function makeManager(opts: {
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
processes?: number[];
|
||||
onSessionsChanged?: () => void;
|
||||
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
|
||||
}) {
|
||||
let pids = opts.processes ?? [];
|
||||
const live = new Set<number>();
|
||||
const inject = vi.fn(opts.inject ?? (() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})));
|
||||
const unload = vi.fn();
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
// FakeClient — never connected; just needs to satisfy EventEmitter +
|
||||
// a minimal subset of QqHookClient for HookSession.tearDownClient().
|
||||
const makeClient = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { throw new Error('test: never really connect'); };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
onSessionsChanged: opts.onSessionsChanged,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
inject,
|
||||
pipeWatcher,
|
||||
setProcesses: (next: number[]) => { pids = next; },
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
describe('HookManager runtime TRACE', () => {
|
||||
it('records discovery and process-gone facts while unchanged ticks stay silent', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
const sessionsChanged = vi.fn();
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: false,
|
||||
processes: [],
|
||||
onSessionsChanged: sessionsChanged,
|
||||
});
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
const baseline = managerTrace(entries).length;
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
expect(managerTrace(entries)).toHaveLength(baseline);
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
|
||||
const facts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_manager_fact '),
|
||||
);
|
||||
expect(facts.map((entry) => entry.message)).toEqual([
|
||||
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
|
||||
'hook_manager_fact event=process_gone pid=4242 tracked=true',
|
||||
]);
|
||||
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('records bounded transient retries and recovery as separate attempts', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
})
|
||||
.mockImplementationOnce(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
}));
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/),
|
||||
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
|
||||
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
expect(attempts[2]!.req).toBe(attempts[3]!.req);
|
||||
expect(attempts[0]!.req).not.toBe(attempts[2]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
let resolveInjection!: (result: HookInjectResult) => void;
|
||||
const injection = new Promise<HookInjectResult>((resolve) => {
|
||||
resolveInjection = resolve;
|
||||
});
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: true,
|
||||
processes: [4242],
|
||||
inject: () => injection,
|
||||
});
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
const manualLoad = ctx.manager.loadProcess(4242);
|
||||
resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
|
||||
await manualLoad;
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'permanent failure',
|
||||
error: 'ptrace denied',
|
||||
ticks: 1,
|
||||
attempts: 1,
|
||||
reason: 'permanent_failure',
|
||||
},
|
||||
{
|
||||
name: 'retry exhaustion',
|
||||
error: 'target process does not map /lib/libc.so.6 while resolving mmap',
|
||||
ticks: 4,
|
||||
attempts: 3,
|
||||
reason: 'retry_exhausted',
|
||||
},
|
||||
])('records $name terminal', async ({ error, ticks, attempts, reason }) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => { throw new Error(error); });
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
for (let tick = 0; tick < ticks; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
|
||||
const starts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_start '),
|
||||
);
|
||||
const terminals = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_terminal '),
|
||||
);
|
||||
expect(starts).toHaveLength(attempts);
|
||||
expect(terminals).toHaveLength(attempts);
|
||||
expect(terminals.at(-1)!.message).toContain(`reason=${reason}`);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookManager.autoLoadOnDiscovery', () => {
|
||||
it('does NOT inject on process-discovered when flag is off', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
expect(ctx.inject).not.toHaveBeenCalled();
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('injects every newly-discovered PID when flag is on', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
// session.load() is queued via a per-session promise chain; flush twice
|
||||
// so the auto-load runs to completion before we assert.
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.inject).toHaveBeenCalledWith(4242);
|
||||
|
||||
// A second PID appearing mid-flight should also trigger an inject.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('swallows inject errors so the watcher keeps running', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Second PID should still be auto-loaded — the failure on 4242 must
|
||||
// not leak out of the listener and break the watcher's emit loop.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('retries a transient libc mapping failure on the next watcher tick', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(4242);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('does not retry permanent auto-load errors', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => { throw new Error('ptrace denied'); });
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('stops retrying a transient libc mapping failure after three attempts', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
for (let tick = 0; tick < 4; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(3);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
// `shouldAutoLoadPid` reads /proc/<pid>/cmdline directly, so we point
|
||||
// it at a temporary directory that mimics the procfs layout. This lets
|
||||
// the tests run on macOS / CI without a live Linux QQ process.
|
||||
describe('shouldAutoLoadPid', () => {
|
||||
let tmpProc: string;
|
||||
const originalReadFileSync = fs.readFileSync;
|
||||
const log = createLogger('test');
|
||||
const originalPlatform = process.platform;
|
||||
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((p: string, ...rest: unknown[]) => {
|
||||
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
|
||||
if (match) {
|
||||
return originalReadFileSync(path.join(tmpProc, match[1], 'cmdline'), ...(rest as [BufferEncoding]));
|
||||
}
|
||||
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
|
||||
}) as typeof fs.readFileSync;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
|
||||
if (originalAutoLoadAll === undefined) delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
else process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
|
||||
fs.rmSync(tmpProc, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function writeCmdline(pid: number, args: string[]): void {
|
||||
const dir = path.join(tmpProc, String(pid));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
|
||||
}
|
||||
|
||||
it('allows the QQ main process (no --type=)', () => {
|
||||
writeCmdline(50, ['qq', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(50, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects Electron zygotes', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects renderer/gpu/utility children', () => {
|
||||
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
|
||||
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
|
||||
writeCmdline(72, ['/opt/QQ/qq', '--type=utility', '--utility-sub-type=network.mojom.NetworkService']);
|
||||
expect(shouldAutoLoadPid(70, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(71, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(72, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
||||
// No cmdline file needed — we return true before touching procfs.
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
|
||||
expect(shouldAutoLoadPid(99999, log)).toBe(true);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,56 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
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,
|
||||
});
|
||||
|
||||
describe('statusFor — settled HookProcessStatus derivation', () => {
|
||||
it('not injected → available (regardless of other flags)', () => {
|
||||
expect(statusFor(F({ injected: false }))).toBe('available');
|
||||
// !injected dominates: stale connected/loggedIn bits must not leak through.
|
||||
expect(statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true }))).toBe('available');
|
||||
});
|
||||
|
||||
it('injected, connected, loggedIn → online', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online');
|
||||
});
|
||||
|
||||
it('injected, connected, not loggedIn → loaded', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded');
|
||||
});
|
||||
|
||||
it('injected, not connected, had logged in → disconnected', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe('disconnected');
|
||||
});
|
||||
|
||||
it('injected, not connected, never logged in → connecting', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe('connecting');
|
||||
});
|
||||
|
||||
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
|
||||
const base = { injected: true, connected: false, loggedIn: false };
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected');
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting');
|
||||
});
|
||||
|
||||
it('covers exactly the five settled states across the flag space', () => {
|
||||
const seen = new Set<HookProcessStatus>();
|
||||
for (const injected of [false, true]) {
|
||||
for (const connected of [false, true]) {
|
||||
for (const loggedIn of [false, true]) {
|
||||
for (const wasLoggedIn of [false, true]) {
|
||||
seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect([...seen].sort()).toEqual(
|
||||
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
|
||||
);
|
||||
// The two out-of-band states are never produced by the pure derivation.
|
||||
expect(seen.has('loading')).toBe(false);
|
||||
expect(seen.has('error')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { createNativeProcessEnumerator } from '../src/process-enumerator';
|
||||
import type { HookProcessBaseInfo } from '../src/injector';
|
||||
|
||||
const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' });
|
||||
|
||||
describe('createNativeProcessEnumerator', () => {
|
||||
describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => {
|
||||
it('returns the sync lister result', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => [QQ(10), QQ(20)],
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]);
|
||||
en.dispose();
|
||||
});
|
||||
|
||||
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => { throw new Error('boom'); },
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toBeNull();
|
||||
en.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe('worker isolation that cannot load the addon → permanent fallback', () => {
|
||||
it('falls back to the sync lister after the worker reports a fatal load error', async () => {
|
||||
const fallback = vi.fn(() => [QQ(7)]);
|
||||
const en = createNativeProcessEnumerator({
|
||||
// A path that exists nowhere → process.dlopen throws in the worker →
|
||||
// the worker posts 'fatal' → isolation is abandoned for good.
|
||||
addonPath: '/nonexistent/snowluma-test.node',
|
||||
fallbackSync: fallback,
|
||||
processName: 'qq',
|
||||
timeoutMs: 200,
|
||||
});
|
||||
|
||||
// First call spawns the worker; the fatal message drains it to UNKNOWN.
|
||||
const first = await en.enumerate();
|
||||
expect(first).toBeNull();
|
||||
|
||||
// Give the 'fatal' message a moment to flip isolationBroken if it hadn't
|
||||
// already, then subsequent calls take the synchronous fallback.
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
const second = await en.enumerate();
|
||||
expect(second).toEqual([QQ(7)]);
|
||||
expect(fallback).toHaveBeenCalled();
|
||||
en.dispose();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,650 +0,0 @@
|
||||
import net from 'net';
|
||||
import { mkdtemp, rm, writeFile } from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { Duplex } from 'stream';
|
||||
import {
|
||||
currentRequestId,
|
||||
getLogLevel,
|
||||
runWithRequestId,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
HEADER_SIZE,
|
||||
listLiveLinuxPipePids,
|
||||
PIPE_MAGIC,
|
||||
PIPE_VERSION,
|
||||
PipeOp,
|
||||
QqHookClient,
|
||||
} from '../src/qq-hook-client';
|
||||
|
||||
let tmpDir: string | null = null;
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
async function makeRuntimeDir(): Promise<string> {
|
||||
tmpDir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-hook-'));
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
function pipeFrame({
|
||||
op,
|
||||
requestId = 0,
|
||||
status = 0,
|
||||
value0 = 0n,
|
||||
cmd = '',
|
||||
message = '',
|
||||
body = Buffer.alloc(0),
|
||||
}: {
|
||||
op: PipeOp;
|
||||
requestId?: number;
|
||||
status?: number;
|
||||
value0?: bigint;
|
||||
cmd?: string;
|
||||
message?: string;
|
||||
body?: Buffer;
|
||||
}): Buffer {
|
||||
const cmdBytes = Buffer.from(cmd);
|
||||
const messageBytes = Buffer.from(message);
|
||||
const header = Buffer.alloc(HEADER_SIZE);
|
||||
header.writeUInt32LE(PIPE_MAGIC, 0);
|
||||
header.writeUInt16LE(PIPE_VERSION, 4);
|
||||
header.writeUInt16LE(op, 6);
|
||||
header.writeUInt32LE(requestId, 8);
|
||||
header.writeInt32LE(status, 12);
|
||||
header.writeUInt32LE(cmdBytes.length, 20);
|
||||
header.writeUInt32LE(messageBytes.length, 24);
|
||||
header.writeUInt32LE(body.length, 28);
|
||||
header.writeBigUInt64LE(value0, 32);
|
||||
return Buffer.concat([header, cmdBytes, messageBytes, body]);
|
||||
}
|
||||
|
||||
function readSendFrame(payload: Buffer): {
|
||||
requestId: number;
|
||||
cmd: string;
|
||||
body: Buffer;
|
||||
} {
|
||||
const cmdLength = payload.readUInt32LE(20);
|
||||
const messageLength = payload.readUInt32LE(24);
|
||||
const bodyLength = payload.readUInt32LE(28);
|
||||
const cmdStart = HEADER_SIZE;
|
||||
const bodyStart = cmdStart + cmdLength + messageLength;
|
||||
return {
|
||||
requestId: payload.readUInt32LE(8),
|
||||
cmd: payload.subarray(cmdStart, cmdStart + cmdLength).toString(),
|
||||
body: Buffer.from(payload.subarray(bodyStart, bodyStart + bodyLength)),
|
||||
};
|
||||
}
|
||||
|
||||
function mockControlPipe(
|
||||
pid: number,
|
||||
onWrite: (socket: net.Socket, payload: Buffer) => void,
|
||||
): ReturnType<typeof vi.spyOn> {
|
||||
return vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
const socket = new Duplex({
|
||||
read() { /* peer data is injected with emit('data') */ },
|
||||
write(chunk, _encoding, callback) {
|
||||
onWrite(socket, Buffer.from(chunk));
|
||||
callback();
|
||||
},
|
||||
}) as net.Socket;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('connect');
|
||||
queueMicrotask(() => socket.emit('data', pipeFrame({
|
||||
op: PipeOp.hello,
|
||||
value0: BigInt(pid),
|
||||
})));
|
||||
});
|
||||
return socket;
|
||||
}) as typeof net.createConnection);
|
||||
}
|
||||
|
||||
function traceMessages(entries: LogEntry[]): string[] {
|
||||
return entries
|
||||
.filter((entry) => entry.level === 'trace' && entry.scope === 'QQHook.Packet')
|
||||
.map((entry) => entry.message);
|
||||
}
|
||||
|
||||
function runtimeTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter(
|
||||
(entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime',
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
setLogLevel(previousLogLevel);
|
||||
vi.restoreAllMocks();
|
||||
if (!tmpDir) return;
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
tmpDir = null;
|
||||
});
|
||||
|
||||
describe('listLiveLinuxPipePids', () => {
|
||||
it('ignores stale-looking control socket names when the probe rejects them', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.recv.sock'), '');
|
||||
|
||||
const pids = await listLiveLinuxPipePids(runtimeDir, async () => false);
|
||||
|
||||
expect([...pids]).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns only connectable control sockets', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.56.control.sock'), '');
|
||||
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 pids = await listLiveLinuxPipePids(runtimeDir, probe);
|
||||
|
||||
expect([...pids]).toEqual([56]);
|
||||
expect(probe).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('QqHookClient — runtime TRACE', () => {
|
||||
it('records control and receive pipe hello lifecycles under the parent request', async () => {
|
||||
const pid = 778820;
|
||||
const entries: LogEntry[] = [];
|
||||
let connectionIndex = 0;
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
const kind = connectionIndex === 0 ? 'control' : 'recv';
|
||||
connectionIndex += 1;
|
||||
const socket = new Duplex({
|
||||
read() { /* peer data is injected with emit('data') */ },
|
||||
}) as net.Socket;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('connect');
|
||||
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());
|
||||
|
||||
const trace = runtimeTrace(entries);
|
||||
expect(trace).toHaveLength(6);
|
||||
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_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+$/),
|
||||
]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
createConnection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('records a pre-request connection failure without a pipe request id', async () => {
|
||||
const pid = 778821;
|
||||
const entries: LogEntry[] = [];
|
||||
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;
|
||||
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');
|
||||
|
||||
const trace = runtimeTrace(entries);
|
||||
expect(trace).toHaveLength(2);
|
||||
expect(trace.every((entry) => entry.req !== undefined)).toBe(true);
|
||||
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(trace.map((entry) => entry.message).join('\n')).not.toContain('requestId=');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
createConnection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('assigns fresh request contexts to material login and close events only', async () => {
|
||||
const pid = 778822;
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const connection = mockControlPipe(pid, () => { /* no packet writes */ });
|
||||
const client = new QqHookClient(pid);
|
||||
const eventRequestIds: Array<{ event: 'login' | 'close'; req: number | undefined }> = [];
|
||||
client.on('loginState', () => {
|
||||
eventRequestIds.push({ event: 'login', req: currentRequestId() });
|
||||
});
|
||||
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({
|
||||
op: PipeOp.loginState,
|
||||
status: 1,
|
||||
value0: 123456n,
|
||||
message: '123456',
|
||||
}));
|
||||
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 '),
|
||||
);
|
||||
expect(facts).toHaveLength(2);
|
||||
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
|
||||
expect(facts[0]!.req).not.toBe(facts[1]!.req);
|
||||
expect(facts.map((entry) => entry.message)).toEqual([
|
||||
'hook_runtime_fact pid=778822 event=login_state_changed previousLoggedIn=false previousUin="0" loggedIn=true uin="123456"',
|
||||
'hook_runtime_fact pid=778822 event=pipe_closed kind=control loggedIn=true uin="123456"',
|
||||
]);
|
||||
expect(eventRequestIds).toEqual([
|
||||
{ event: 'login', req: facts[0]!.req },
|
||||
{ event: 'login', req: undefined },
|
||||
{ event: 'close', req: facts[1]!.req },
|
||||
]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
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),
|
||||
]);
|
||||
const replyBody = Buffer.from([0xff, 0x00, 0x7f]);
|
||||
const entries: LogEntry[] = [];
|
||||
const writes: Buffer[] = [];
|
||||
let traceCountAtWrite = 0;
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
const frame = readSendFrame(payload);
|
||||
writes.push(payload);
|
||||
traceCountAtWrite = traceMessages(entries).length;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId: frame.requestId }));
|
||||
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 sent = readSendFrame(writes[0]);
|
||||
expect(sent).toMatchObject({
|
||||
requestId: 1,
|
||||
cmd: 'OidbSvcTrpcTcp.0x1234_1',
|
||||
body: requestBody,
|
||||
});
|
||||
expect(reply).toMatchObject({
|
||||
requestId: 1,
|
||||
error: 27,
|
||||
message: 'fixture reply',
|
||||
body: replyBody,
|
||||
});
|
||||
expect(traceCountAtWrite).toBe(1);
|
||||
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')}`,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
req: 4101,
|
||||
message: `packet_recv serviceCmd="OidbSvcTrpcTcp.0x1234_1" requestId=1 error=27 message="fixture reply" length=${replyBody.length} body=${replyBody.toString('hex')}`,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
req: 4101,
|
||||
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('...');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('records empty request and reply bodies exactly', async () => {
|
||||
const pid = 778811;
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
const { requestId } = readSendFrame(payload);
|
||||
queueMicrotask(() => {
|
||||
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId }));
|
||||
socket.emit('data', pipeFrame({ op: PipeOp.sendReply, requestId }));
|
||||
});
|
||||
});
|
||||
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+$/),
|
||||
]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('records no-reply acknowledgement as the terminal outcome', async () => {
|
||||
const pid = 778812;
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
const { requestId } = readSendFrame(payload);
|
||||
queueMicrotask(() => {
|
||||
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId }));
|
||||
});
|
||||
});
|
||||
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+$/),
|
||||
]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('records reply timeout and transport failure with their real request ids', async () => {
|
||||
vi.useFakeTimers();
|
||||
const pid = 778813;
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
let writeCount = 0;
|
||||
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 */ });
|
||||
try {
|
||||
const timedOut = client.sendAndWait('Timeout.Command', Buffer.from([0xff]), {
|
||||
ackTimeoutMs: 50,
|
||||
replyTimeoutMs: 50,
|
||||
});
|
||||
const timedOutOutcome = timedOut.then(
|
||||
() => null,
|
||||
(error: unknown) => error,
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
const timeoutError = await timedOutOutcome;
|
||||
expect(timeoutError).toBeInstanceOf(Error);
|
||||
expect((timeoutError as Error).message).toBe('send reply 1 timed out after 50 ms');
|
||||
|
||||
const failed = client.sendAndWait('Closed.Command', Buffer.from([0x00]), {
|
||||
ackTimeoutMs: 50,
|
||||
replyTimeoutMs: 50,
|
||||
});
|
||||
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+$/),
|
||||
]));
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('classifies acknowledgement timeout and pipe request failure', async () => {
|
||||
vi.useFakeTimers();
|
||||
const pid = 778815;
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
let writeCount = 0;
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
const { requestId } = readSendFrame(payload);
|
||||
writeCount += 1;
|
||||
if (writeCount === 2) {
|
||||
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,
|
||||
});
|
||||
const timedOutOutcome = timedOut.then(
|
||||
() => null,
|
||||
(error: unknown) => error,
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
expect(await timedOutOutcome).toMatchObject({
|
||||
message: 'send ack 1 timed out after 25 ms',
|
||||
});
|
||||
|
||||
await expect(client.sendAndWait(
|
||||
'Pipe.Error',
|
||||
Buffer.from([0xff]),
|
||||
)).rejects.toThrow('send ack 2 timed out after 25 ms');
|
||||
|
||||
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();
|
||||
connection.mockRestore();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps concurrent packet records atomic with distinct real request ids', async () => {
|
||||
const pid = 778816;
|
||||
const entries: LogEntry[] = [];
|
||||
const writes: Array<ReturnType<typeof readSendFrame>> = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
writes.push(readSendFrame(payload));
|
||||
if (writes.length !== 2) return;
|
||||
queueMicrotask(() => {
|
||||
for (const frame of [...writes].reverse()) {
|
||||
socket.emit('data', pipeFrame({
|
||||
op: PipeOp.sendAck,
|
||||
requestId: frame.requestId,
|
||||
}));
|
||||
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),
|
||||
);
|
||||
try {
|
||||
const [first, second] = await Promise.all([
|
||||
client.sendAndWait('First\nCommand', firstBody),
|
||||
client.sendAndWait('Second.Command', secondBody),
|
||||
]);
|
||||
|
||||
expect([first.requestId, second.requestId]).toEqual([1, 2]);
|
||||
expect(writes.map((frame) => frame.requestId)).toEqual([1, 2]);
|
||||
const messages = traceMessages(entries);
|
||||
expect(messages).toHaveLength(6);
|
||||
expect(messages.every((message) => !message.includes('\n'))).toBe(true);
|
||||
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);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not evaluate packet TRACE producers while TRACE is disabled', async () => {
|
||||
const pid = 778814;
|
||||
setLogLevel('debug');
|
||||
const byteLength = vi.spyOn(Buffer.prototype, 'toString');
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
const { requestId } = readSendFrame(payload);
|
||||
queueMicrotask(() => {
|
||||
socket.emit('data', pipeFrame({ op: PipeOp.sendAck, requestId }));
|
||||
socket.emit('data', pipeFrame({ op: PipeOp.sendReply, requestId }));
|
||||
});
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
try {
|
||||
await client.sendAndWait('Disabled.Command', Buffer.from([0x00, 0xff]));
|
||||
|
||||
expect(byteLength).not.toHaveBeenCalledWith('hex');
|
||||
} finally {
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
byteLength.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('QqHookClient — pipe close mid-send', () => {
|
||||
// Regression: when the control pipe closes while a send() is awaiting its
|
||||
// ack, rejectControlPending() rejects BOTH the ack and reply deferreds. The
|
||||
// reply is only `await`ed after the ack, so if the ack rejects first the
|
||||
// reply promise is rejected with NO awaiter — an UNHANDLED rejection that
|
||||
// crashes the Node process (Docker: supervisor restarts it ~1s later; on
|
||||
// Windows it just dies → "connection pipe closed", bot down). The .catch()
|
||||
// guard on each deferred prevents it; without the guard this test trips the
|
||||
// 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
|
||||
h.writeUInt16LE(1, 4); // PIPE_VERSION
|
||||
h.writeUInt16LE(1, 6); // PipeOp.hello
|
||||
h.writeBigUInt64LE(BigInt(PID), 32); // value0 = pid
|
||||
return h;
|
||||
};
|
||||
|
||||
let controlConn: net.Socket | null = null;
|
||||
let signalControlWrite!: () => void;
|
||||
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') */ },
|
||||
write(_chunk, _encoding, callback) {
|
||||
signalControlWrite();
|
||||
callback();
|
||||
},
|
||||
}) as net.Socket;
|
||||
controlConn = socket;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('connect');
|
||||
queueMicrotask(() => socket.emit('data', helloFrame()));
|
||||
});
|
||||
return socket;
|
||||
}) as typeof net.createConnection);
|
||||
|
||||
const unhandled: unknown[] = [];
|
||||
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 */ });
|
||||
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);
|
||||
await controlWriteStarted;
|
||||
controlConn?.destroy();
|
||||
|
||||
const outcome = await sent;
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
expect(outcome).toBeInstanceOf(Error);
|
||||
expect((outcome as Error).message).toBe('control pipe closed');
|
||||
expect(unhandled, `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`).toHaveLength(0);
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled);
|
||||
client.close();
|
||||
createConnection.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,39 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const execMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('child_process', () => ({ exec: execMock }));
|
||||
|
||||
import { probeQqLoginInfo } from '../src/qq-port-probe';
|
||||
|
||||
describe('probeQqLoginInfo — bounded execution', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
execMock.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('allows a later probe after a timed-out attempt', async () => {
|
||||
execMock.mockImplementation(() => undefined);
|
||||
const first = probeQqLoginInfo(4242);
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
await expect(first).resolves.toBeNull();
|
||||
|
||||
execMock
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, { stdout: '', stderr: '' });
|
||||
})
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, { stdout: '1\n', stderr: '' });
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
loggedIn: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,9 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.13.0",
|
||||
"name": "@snowluma/channel-hook",
|
||||
"version": "1.9.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
"description": "SnowLuma `inject` channel implementation — in-process NTQQ hook runtime. Bundles HookManager / HookSession / pipe-watcher / injector / qq-hook-client plus the `HookChannel` and `HookAdapter` that `Hub` (in @snowluma/core) registers as the primary transport on Windows. Depends on `@snowluma/channel` for the abstract `Channel` + `ChannelAdapter` contracts.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
@@ -12,6 +11,14 @@
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./hook-channel": {
|
||||
"types": "./src/hook-channel.ts",
|
||||
"default": "./src/hook-channel.ts"
|
||||
},
|
||||
"./hook-adapter": {
|
||||
"types": "./src/hook-adapter.ts",
|
||||
"default": "./src/hook-adapter.ts"
|
||||
},
|
||||
"./hook-manager": {
|
||||
"types": "./src/hook-manager.ts",
|
||||
"default": "./src/hook-manager.ts"
|
||||
@@ -50,10 +57,11 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/channel": "workspace:*",
|
||||
"@snowluma/common": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "catalog:",
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
174
packages/channel-hook/src/hook-adapter.ts
Normal file
174
packages/channel-hook/src/hook-adapter.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { HookChannel } from './hook-channel';
|
||||
import { HookManager, type HookManagerDeps, type HookSink } from './hook-manager';
|
||||
|
||||
/** Subset of `HookManagerDeps` the operator is allowed to forward
|
||||
* through the adapter. The `sink` is owned by the adapter itself and
|
||||
* intentionally not exposed. */
|
||||
export type HookAdapterOptions = Omit<HookManagerDeps, 'sink'>;
|
||||
|
||||
/**
|
||||
* `HookAdapter` — the `ChannelAdapter` for the NTQQ hook runtime. It
|
||||
* owns the `HookManager` and translates its three sink callbacks
|
||||
* (`onHookLogin` / `onPacket` / `onPidDisconnected`) into lifecycle
|
||||
* events on a per-UIN `HookChannel`.
|
||||
*
|
||||
* Why an adapter rather than letting the `Hub` keep the hook sink:
|
||||
* this is the only place in the codebase that legitimately needs to
|
||||
* know about PIDs. Quarantining that knowledge here keeps the `Hub`
|
||||
* (and everything above it) free of `pid`, leaving the door open for
|
||||
* a future `SocketAdapter` that doesn't have the concept at all.
|
||||
*
|
||||
* Internal bookkeeping:
|
||||
*
|
||||
* - `pidToUin` — quick "which UIN does this PID feed?" lookup,
|
||||
* populated on login (and lazily during defensive
|
||||
* packet routing for PIDs that arrived ahead of
|
||||
* their login notification).
|
||||
* - `pidToSender` — the live `PacketSender` per PID, so a re-login
|
||||
* from the same PID rotates the outbound sender
|
||||
* without dropping the channel.
|
||||
* - `uinToPids` — reverse index for fast "did this UIN lose its
|
||||
* last PID?" checks on disconnect.
|
||||
* - `channelsByUin` — one `HookChannel` per UIN; the hub only sees
|
||||
* `Channel` instances, never the PID set living
|
||||
* inside them.
|
||||
*/
|
||||
export class HookAdapter implements ChannelAdapter, HookSink {
|
||||
readonly kind = 'inject' as const;
|
||||
|
||||
private readonly hookManager_: HookManager;
|
||||
|
||||
private readonly pidToUin = new Map<number, string>();
|
||||
private readonly pidToSender = new Map<number, PacketSender>();
|
||||
private readonly uinToPids = new Map<string, Set<number>>();
|
||||
private readonly channelsByUin = new Map<string, HookChannel>();
|
||||
|
||||
private host_: ChannelAdapterHost | null = null;
|
||||
private disposed_ = false;
|
||||
|
||||
constructor(opts: HookAdapterOptions = {}) {
|
||||
// `sink: this` wires HookManager → adapter sink. The HookManager
|
||||
// doesn't know about the broader ChannelAdapter contract; it only
|
||||
// sees the three sink methods we implement below.
|
||||
this.hookManager_ = new HookManager({ ...opts, sink: this });
|
||||
}
|
||||
|
||||
/** The underlying `HookManager`, exposed so WebUI can keep its
|
||||
* `/api/processes/*` endpoints pointing at the hook process table.
|
||||
* Higher-level code (OneBot, channel consumers) MUST NOT reach into
|
||||
* this — that's the whole point of the adapter layer. */
|
||||
get hookManager(): HookManager { return this.hookManager_; }
|
||||
|
||||
// ─── ChannelAdapter contract ─────────────────────────────────────
|
||||
|
||||
start(host: ChannelAdapterHost): void {
|
||||
this.host_ = host;
|
||||
host.log.debug('hook adapter started');
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed_) return;
|
||||
this.disposed_ = true;
|
||||
// Tear down hook sessions first so no more sink callbacks fire.
|
||||
this.hookManager_.dispose();
|
||||
// Then proactively remove every channel we published; the hub
|
||||
// will call `channel.dispose()` on its way out.
|
||||
for (const id of [...this.channelsByUin.values()].map(c => c.id)) {
|
||||
this.host_?.removeChannel(id);
|
||||
}
|
||||
this.pidToUin.clear();
|
||||
this.pidToSender.clear();
|
||||
this.uinToPids.clear();
|
||||
this.channelsByUin.clear();
|
||||
this.host_ = null;
|
||||
}
|
||||
|
||||
// ─── HookSink contract (called by HookManager) ──────────────────
|
||||
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||
if (this.disposed_ || !isRealUin(uin)) return;
|
||||
|
||||
this.recordPidMapping(pid, uin, packetClient);
|
||||
const channel = this.ensureChannel(uin);
|
||||
channel.attachPid(pid, packetClient);
|
||||
}
|
||||
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
if (this.disposed_ || !pkt.uin || !isRealUin(pkt.uin)) return;
|
||||
|
||||
const uin = pkt.uin;
|
||||
const channel = this.ensureChannel(uin);
|
||||
|
||||
// Defensive: a packet may arrive before its login notification
|
||||
// when the channel is being re-adopted (SnowLuma restarted while
|
||||
// the hook stayed resident in QQ.exe). If we have a sender for
|
||||
// this PID, weave it in so subsequent sends through this channel
|
||||
// succeed.
|
||||
if (pkt.pid) {
|
||||
const sender = this.pidToSender.get(pkt.pid);
|
||||
if (sender && !this.pidToUin.has(pkt.pid)) {
|
||||
this.recordPidMapping(pkt.pid, uin, sender);
|
||||
channel.attachPid(pkt.pid, sender);
|
||||
}
|
||||
}
|
||||
|
||||
channel.deliverPacket(pkt);
|
||||
}
|
||||
|
||||
onPidDisconnected(pid: number): void {
|
||||
if (this.disposed_) return;
|
||||
this.pidToSender.delete(pid);
|
||||
|
||||
const uin = this.pidToUin.get(pid);
|
||||
if (!uin) return;
|
||||
this.pidToUin.delete(pid);
|
||||
|
||||
const pids = this.uinToPids.get(uin);
|
||||
if (pids) {
|
||||
pids.delete(pid);
|
||||
if (pids.size === 0) this.uinToPids.delete(uin);
|
||||
}
|
||||
|
||||
const channel = this.channelsByUin.get(uin);
|
||||
if (!channel) return;
|
||||
channel.detachPid(pid);
|
||||
|
||||
if (channel.isEmpty) {
|
||||
this.channelsByUin.delete(uin);
|
||||
this.host_?.removeChannel(channel.id);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── internal ────────────────────────────────────────────────────
|
||||
|
||||
private recordPidMapping(pid: number, uin: string, sender: PacketSender): void {
|
||||
this.pidToUin.set(pid, uin);
|
||||
this.pidToSender.set(pid, sender);
|
||||
let pids = this.uinToPids.get(uin);
|
||||
if (!pids) {
|
||||
pids = new Set();
|
||||
this.uinToPids.set(uin, pids);
|
||||
}
|
||||
pids.add(pid);
|
||||
}
|
||||
|
||||
private ensureChannel(uin: string): HookChannel {
|
||||
let channel = this.channelsByUin.get(uin);
|
||||
if (channel) return channel;
|
||||
channel = new HookChannel(uin);
|
||||
this.channelsByUin.set(uin, channel);
|
||||
this.host_?.addChannel(channel);
|
||||
return channel;
|
||||
}
|
||||
}
|
||||
|
||||
// QQ uins are 5-12 decimal digits; "0" is the hook's "no login yet"
|
||||
// sentinel. Anything else (empty, alpha, too short) is a sign the hook
|
||||
// callback fired before login info was probed — we ignore those.
|
||||
function isRealUin(uin: string): boolean {
|
||||
if (!uin || uin === '0') return false;
|
||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||
}
|
||||
82
packages/channel-hook/src/hook-channel.ts
Normal file
82
packages/channel-hook/src/hook-channel.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { Channel } from '@snowluma/channel';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
/**
|
||||
* `HookChannel` — concrete transport backed by the in-process NTQQ
|
||||
* hook. One UIN may be served simultaneously by several injected
|
||||
* processes; the channel therefore tracks an unordered set of PIDs and
|
||||
* keeps a single live `PacketSender` (the most recently logged-in
|
||||
* pipe) for outbound traffic.
|
||||
*
|
||||
* PID bookkeeping is scoped to this transport because the socket-only
|
||||
* runtime never has the concept; quarantining it here keeps the
|
||||
* abstract `Channel` and the `Hub` free of pid awareness.
|
||||
*
|
||||
* The owning `HookAdapter` is responsible for calling
|
||||
* `attachPid(pid, sender)` on every successful hook login,
|
||||
* `detachPid(pid)` when the watcher reports a pipe drop, and tearing
|
||||
* the channel down once `isEmpty` returns true.
|
||||
*/
|
||||
export class HookChannel extends Channel {
|
||||
readonly kind = 'inject' as const;
|
||||
readonly uin: string;
|
||||
|
||||
private readonly pids_ = new Set<number>();
|
||||
private packetClient_: PacketSender | null = null;
|
||||
|
||||
constructor(uin: string) {
|
||||
super();
|
||||
this.uin = uin;
|
||||
}
|
||||
|
||||
get id(): string { return `inject:${this.uin}`; }
|
||||
|
||||
/** PIDs currently routing packets into this channel. Read-only view
|
||||
* for diagnostics — mutate only via `attachPid` / `detachPid`. */
|
||||
get pids(): ReadonlySet<number> { return this.pids_; }
|
||||
|
||||
/** True iff no PID is currently bound; the adapter uses this to
|
||||
* decide when to remove the channel from the `Hub`. */
|
||||
get isEmpty(): boolean { return this.pids_.size === 0; }
|
||||
|
||||
/** Bind a freshly-logged-in PID (and its outbound `PacketSender`)
|
||||
* to this channel. Idempotent — re-binding the same PID just rotates
|
||||
* the active sender. */
|
||||
attachPid(pid: number, sender: PacketSender): void {
|
||||
this.pids_.add(pid);
|
||||
this.packetClient_ = sender;
|
||||
}
|
||||
|
||||
/** Forget a PID. If it owned the active sender we drop it; the next
|
||||
* `attachPid` (or pipe-up) will install a fresh one. */
|
||||
detachPid(pid: number): void {
|
||||
this.pids_.delete(pid);
|
||||
if (this.pids_.size === 0) {
|
||||
this.packetClient_ = null;
|
||||
}
|
||||
}
|
||||
|
||||
override async sendRawPacket(
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs = 15000,
|
||||
): Promise<SendPacketResult> {
|
||||
const client = this.packetClient_;
|
||||
if (!client) {
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: 'hook channel has no live packet sender',
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
return client.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
}
|
||||
|
||||
override dispose(): void {
|
||||
super.dispose();
|
||||
this.packetClient_ = null;
|
||||
this.pids_.clear();
|
||||
}
|
||||
}
|
||||
316
packages/channel-hook/src/hook-manager.ts
Normal file
316
packages/channel-hook/src/hook-manager.ts
Normal file
@@ -0,0 +1,316 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types';
|
||||
import fs from 'fs';
|
||||
import { HookSession, type HookSessionDeps } from './hook-session';
|
||||
import {
|
||||
injectHookProcess,
|
||||
listHookProcesses,
|
||||
unloadHookProcess,
|
||||
type HookProcessBaseInfo,
|
||||
} from './injector';
|
||||
import { PipeWatcher } from './pipe-watcher';
|
||||
import { QqHookClient } from './qq-hook-client';
|
||||
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
|
||||
import type { HookProcessInfo } from './types';
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sink that the hook layer calls back into when it observes a new login,
|
||||
* a parsed packet, or a PID disconnect. The concrete implementation is
|
||||
* `HookAdapter`, which sits between this hook runtime and the `Hub` in
|
||||
* `@snowluma/core`. Declaring it here keeps `@snowluma/channel` (and
|
||||
* future `@snowluma/channel-hook`) free of any dependency on
|
||||
* `@snowluma/core` — the hook package is self-contained.
|
||||
*/
|
||||
export interface HookSink {
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
|
||||
onPacket(pkt: PacketInfo): void;
|
||||
onPidDisconnected(pid: number): void;
|
||||
}
|
||||
|
||||
export type HookManagerDeps = {
|
||||
sink: HookSink;
|
||||
/** Sink for parsed packets from any live HookSession. Defaults to
|
||||
* `sink.onPacket` — every packet flows straight into the per-UIN
|
||||
* channel dispatcher with no intermediate event emitter. */
|
||||
onPacket?: PacketSink;
|
||||
/** Native injector entrypoints. Defaults to the real native addon. */
|
||||
injector?: HookSessionDeps['injector'];
|
||||
/** Hook pipe-client factory. Defaults to `new QqHookClient(pid)`. */
|
||||
makeClient?: HookSessionDeps['makeClient'];
|
||||
/** Pre-built watcher. Defaults to a PipeWatcher wrapping the native listings. */
|
||||
pipeWatcher?: PipeWatcher;
|
||||
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
|
||||
watcherIntervalMs?: number;
|
||||
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
|
||||
listProcesses?: () => HookProcessBaseInfo[];
|
||||
/** When true, every newly-discovered QQ process is auto-injected (fires
|
||||
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
|
||||
* Failed loads are logged and leave the session in the 'error' state. */
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
log?: Logger;
|
||||
};
|
||||
|
||||
/**
|
||||
* HookManager — thin orchestrator over a per-PID HookSession map and a
|
||||
* singleton PipeWatcher.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Route user commands (load/unload/refresh) to the matching session.
|
||||
* - Route watcher diff events to the matching session.
|
||||
* - Forward session events ('login' / 'disconnected') to the `HookSink`.
|
||||
* - Retry stuck-in-connecting sessions on every watcher tick (so a
|
||||
* failed connect eventually recovers without a manual refresh).
|
||||
*
|
||||
* The native injector, native pipe-client, and native process/pipe
|
||||
* listings are all swappable dependencies so tests can run without a
|
||||
* real QQ.exe or a native addon.
|
||||
*/
|
||||
export class HookManager {
|
||||
private readonly sink: HookSink;
|
||||
private readonly onPacket: PacketSink;
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly pipeWatcher: PipeWatcher;
|
||||
private readonly ownsPipeWatcher: boolean;
|
||||
private readonly listProcessesNative: () => HookProcessBaseInfo[];
|
||||
private readonly autoLoadOnDiscovery: boolean;
|
||||
private readonly log: Logger;
|
||||
private readonly sessions = new Map<number, HookSession>();
|
||||
private readonly startPromise: Promise<void>;
|
||||
|
||||
private disposed = false;
|
||||
|
||||
constructor(deps: HookManagerDeps) {
|
||||
this.sink = deps.sink;
|
||||
this.onPacket = deps.onPacket ?? ((pkt) => deps.sink.onPacket(pkt));
|
||||
this.log = deps.log ?? createLogger('Hook');
|
||||
|
||||
this.injector = deps.injector ?? {
|
||||
inject: injectHookProcess,
|
||||
unload: (pid, handle) => {
|
||||
if (!handle) return;
|
||||
unloadHookProcess(pid, handle);
|
||||
},
|
||||
};
|
||||
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
|
||||
this.listProcessesNative = deps.listProcesses ?? listHookProcesses;
|
||||
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
|
||||
|
||||
if (deps.pipeWatcher) {
|
||||
this.pipeWatcher = deps.pipeWatcher;
|
||||
this.ownsPipeWatcher = false;
|
||||
} else {
|
||||
this.pipeWatcher = new PipeWatcher({
|
||||
listProcesses: this.listProcessesNative,
|
||||
listLivePipes: () => QqHookClient.listLivePipes(),
|
||||
intervalMs: deps.watcherIntervalMs,
|
||||
log: this.log,
|
||||
});
|
||||
this.ownsPipeWatcher = true;
|
||||
}
|
||||
|
||||
this.bindWatcher();
|
||||
this.startPromise = this.pipeWatcher.start();
|
||||
}
|
||||
|
||||
// ─────────────── public API (unchanged from prior HookManager) ───────────────
|
||||
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
await this.startPromise;
|
||||
let processes: HookProcessBaseInfo[];
|
||||
try {
|
||||
processes = this.listProcessesNative();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
processes = [];
|
||||
}
|
||||
const result: HookProcessInfo[] = [];
|
||||
for (const proc of processes) {
|
||||
const session = this.ensureSession(proc.pid);
|
||||
session.attachProcessInfo(proc);
|
||||
result.push(session.toInfo());
|
||||
}
|
||||
return result.sort((a, b) => a.pid - b.pid);
|
||||
}
|
||||
|
||||
async loadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
const info = await session.load();
|
||||
// Pull the next tick forward so a freshly-injected pipe gets noticed
|
||||
// within the next event-loop turn instead of after the full interval.
|
||||
this.pipeWatcher.wake();
|
||||
return info;
|
||||
}
|
||||
|
||||
async unloadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
return session.unload();
|
||||
}
|
||||
|
||||
async refreshProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
return session.refresh();
|
||||
}
|
||||
|
||||
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
this.assertValidPid(pid);
|
||||
return probeQqLoginInfo(pid);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
for (const session of this.sessions.values()) {
|
||||
session.dispose();
|
||||
}
|
||||
this.sessions.clear();
|
||||
if (this.ownsPipeWatcher) {
|
||||
this.pipeWatcher.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── wiring ───────────────
|
||||
|
||||
private bindWatcher(): void {
|
||||
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.ensureSession(info.pid);
|
||||
session.attachProcessInfo(info);
|
||||
// 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
|
||||
// the session's status field.
|
||||
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
|
||||
void session.load().catch((err) => {
|
||||
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
|
||||
});
|
||||
}
|
||||
});
|
||||
this.pipeWatcher.on('process-gone', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.notifyProcessGone();
|
||||
});
|
||||
this.pipeWatcher.on('pipe-up', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.onPipeUp();
|
||||
});
|
||||
this.pipeWatcher.on('pipe-down', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.onPipeDown();
|
||||
});
|
||||
// After every tick, retry sessions that are stuck in 'connecting' OR
|
||||
// 'disconnected' while the pipe is up. Mirrors the original
|
||||
// tickWatcher's per-tick reconcileConnect pass; onPipeUp is idempotent
|
||||
// so calling it for an already-connected session is harmless.
|
||||
//
|
||||
// The 'disconnected' branch matters on Windows: when the QQ-NT side of
|
||||
// the named pipe stays alive but the SnowLuma-side socket dies (read
|
||||
// EPIPE / idle-timeout / similar transient I/O fault), the watcher
|
||||
// sees the pipe as still-live (the OS-level pipe is still listed by
|
||||
// `listLivePipes`) so it never fires another `pipe-up`. Without
|
||||
// retrying 'disconnected' sessions here the session is stranded
|
||||
// forever — a real-world symptom users reported as "Windows running
|
||||
// for a while then stops" with logs `pipe error: read EPIPE` →
|
||||
// `session closed: UIN=…`.
|
||||
this.pipeWatcher.on('tick', () => {
|
||||
if (this.disposed) return;
|
||||
for (const session of this.sessions.values()) {
|
||||
if ((session.status === 'connecting' || session.status === 'disconnected')
|
||||
&& this.pipeWatcher.isPipeLive(session.pid)) {
|
||||
session.onPipeUp();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ensureSession(pid: number): HookSession {
|
||||
let session = this.sessions.get(pid);
|
||||
if (session) return session;
|
||||
|
||||
session = new HookSession(pid, {
|
||||
injector: this.injector,
|
||||
makeClient: this.makeClient,
|
||||
pipeWatcher: this.pipeWatcher,
|
||||
onPacket: this.onPacket,
|
||||
log: this.log,
|
||||
});
|
||||
session.attachProcessInfo({ name: defaultProcessName() });
|
||||
|
||||
session.on('login', (uin: string, sender) => {
|
||||
this.sink.onHookLogin(pid, uin, sender);
|
||||
});
|
||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||
if (wasLoggedIn) this.sink.onPidDisconnected(pid);
|
||||
});
|
||||
session.on('disposed', () => {
|
||||
this.sessions.delete(pid);
|
||||
});
|
||||
|
||||
this.sessions.set(pid, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
private assertValidPid(pid: number): void {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
}
|
||||
}
|
||||
|
||||
function defaultProcessName(): string {
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter for auto-load only. Returns false for Linux Electron child
|
||||
* processes (zygote/renderer/gpu/utility), which the native enumerator
|
||||
* mis-classifies as "main QQ" because their cmdline contains "qq" and
|
||||
* they transiently inherit wrapper.node via fork copy-on-write.
|
||||
*
|
||||
* Injecting into a zygote spawns the hook's resolver thread inside it;
|
||||
* every renderer Electron later forks then inherits that thread + the
|
||||
* partially-init'd hook state, which breaks QQ's IPC and login UI.
|
||||
*
|
||||
* Manual loadProcess() bypasses this gate — the operator is responsible
|
||||
* for picking the right PID from WebUI.
|
||||
*/
|
||||
export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
|
||||
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;
|
||||
|
||||
let cmdline: string;
|
||||
try {
|
||||
cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
|
||||
} catch {
|
||||
// Can't read cmdline (process gone, permission, etc.) — let the
|
||||
// existing load() path handle it; if the process is dead the load
|
||||
// will fail with a clear error.
|
||||
return true;
|
||||
}
|
||||
if (cmdline.includes('--type=')) {
|
||||
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';
|
||||
|
||||
439
packages/channel-hook/src/hook-session.ts
Normal file
439
packages/channel-hook/src/hook-session.ts
Normal file
@@ -0,0 +1,439 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookPacketClient } from './hook-packet-client';
|
||||
import type { HookInjectResult } from './injector';
|
||||
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
|
||||
import type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
|
||||
export type HookSessionDeps = {
|
||||
injector: {
|
||||
inject: (pid: number) => HookInjectResult;
|
||||
unload: (pid: number, handle: HookInjectResult['handle']) => void;
|
||||
};
|
||||
makeClient: (pid: number) => QqHookClient;
|
||||
/** Sync fast-path check used by load() to skip re-injection when a
|
||||
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
|
||||
* fresh poll — used after unload to dodge the up-to-1500ms cache
|
||||
* staleness that would otherwise false-flag a successful unload. */
|
||||
pipeWatcher: {
|
||||
isPipeLive: (pid: number) => boolean;
|
||||
tickNow?: () => Promise<void>;
|
||||
};
|
||||
/** Sink for parsed packets. Called with the canonical PacketInfo
|
||||
* shape for every packet received while logged in. If omitted,
|
||||
* packets are dropped (useful in unit tests that don't care). */
|
||||
onPacket?: PacketSink;
|
||||
log?: Logger;
|
||||
};
|
||||
|
||||
/**
|
||||
* HookSession — owns the lifecycle of one QQ.exe process: injection,
|
||||
* pipe client, login state, and the public status field.
|
||||
*
|
||||
* Concurrency: every state-mutating method goes through a per-session
|
||||
* promise chain so user clicks (load/unload/refresh) and watcher-driven
|
||||
* events (onPipeUp/onPipeDown) never interleave.
|
||||
*
|
||||
* Communication: emits high-level events instead of calling the sink
|
||||
* directly, so HookManager forwards them and tests can attach spies.
|
||||
*
|
||||
* Emitted events:
|
||||
* 'login' (uin, packetSender) — real-UIN login detected
|
||||
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
|
||||
* 'status-changed' (status, error) — status field mutated
|
||||
* 'disposed' () — session stopped tracking this PID
|
||||
*/
|
||||
export class HookSession extends EventEmitter {
|
||||
readonly pid: number;
|
||||
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
|
||||
private readonly onPacket: PacketSink | null;
|
||||
private readonly log: Logger;
|
||||
|
||||
private _status: HookProcessStatus = 'available';
|
||||
private _error = '';
|
||||
private _uin = '0';
|
||||
private _method = '';
|
||||
private _name = '';
|
||||
private _path = '';
|
||||
|
||||
private injected = false;
|
||||
private connected = false;
|
||||
private loggedIn = false;
|
||||
private injectResult: HookInjectResult | null = null;
|
||||
private client: QqHookClient | null = null;
|
||||
private sender: HookPacketClient | null = null;
|
||||
private bound = false;
|
||||
private opChain: Promise<unknown> = Promise.resolve();
|
||||
private disposed = false;
|
||||
|
||||
constructor(pid: number, deps: HookSessionDeps) {
|
||||
super();
|
||||
this.pid = pid;
|
||||
this.injector = deps.injector;
|
||||
this.makeClient = deps.makeClient;
|
||||
this.pipeWatcher = deps.pipeWatcher;
|
||||
this.onPacket = deps.onPacket ?? null;
|
||||
this.log = deps.log ?? createLogger('HookSession');
|
||||
}
|
||||
|
||||
// ─────────────── 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; }
|
||||
|
||||
attachProcessInfo(info: { name?: string; path?: string }): void {
|
||||
if (info.name) this._name = info.name;
|
||||
if (info.path) this._path = info.path;
|
||||
}
|
||||
|
||||
toInfo(): HookProcessInfo {
|
||||
return {
|
||||
pid: this.pid,
|
||||
name: this._name,
|
||||
path: this._path,
|
||||
injected: this.injected,
|
||||
connected: this.connected,
|
||||
loggedIn: this.loggedIn,
|
||||
uin: this._uin,
|
||||
status: this._status,
|
||||
error: this._error,
|
||||
method: this._method,
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────── user-facing commands ───────────────
|
||||
|
||||
load(): Promise<HookProcessInfo> {
|
||||
return this.serialize(() => this.loadInternal());
|
||||
}
|
||||
|
||||
unload(): Promise<HookProcessInfo> {
|
||||
return this.serialize(() => this.unloadInternal());
|
||||
}
|
||||
|
||||
refresh(): Promise<HookProcessInfo> {
|
||||
return this.serialize(() => this.refreshInternal());
|
||||
}
|
||||
|
||||
// ─────────────── watcher-driven events (called by manager) ───────────────
|
||||
|
||||
/** Pipe came up (or stayed up across a SnowLuma restart). Drives connect
|
||||
* 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;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
// Adopt a DLL that survived a SnowLuma restart.
|
||||
if (!this.injected) {
|
||||
this.injected = true;
|
||||
if (!this._method) this._method = 'reconnect';
|
||||
}
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.connected) {
|
||||
await this.attemptConnect();
|
||||
} else {
|
||||
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
|
||||
}
|
||||
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
onPipeDown(): void {
|
||||
if (this.disposed) return;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
if (!this.connected) {
|
||||
// Nothing to tear down; just keep status visible.
|
||||
if (this.injected) this.setStatus('connecting', this._error);
|
||||
return;
|
||||
}
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
this.setStatus(
|
||||
this.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available',
|
||||
'',
|
||||
);
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
}).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;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
this.injected = false;
|
||||
this.injectResult = null;
|
||||
this._method = '';
|
||||
this.setStatus('available', '');
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
this.disposed = true;
|
||||
this.emit('disposed');
|
||||
this.removeAllListeners();
|
||||
}).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
this.tearDownClient();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
// ─────────────── per-session serialization ───────────────
|
||||
|
||||
private serialize<T>(op: () => Promise<T>): Promise<T> {
|
||||
const previous = this.opChain;
|
||||
let release!: () => void;
|
||||
const completion = new Promise<void>(resolve => { release = resolve; });
|
||||
this.opChain = previous.then(() => completion);
|
||||
return (async () => {
|
||||
try {
|
||||
await previous.catch(() => undefined);
|
||||
return await op();
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
// ─────────────── internal transitions ───────────────
|
||||
|
||||
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
|
||||
// resident in QQ.exe. If the watcher already sees a live pipe,
|
||||
// skip re-injection and let onPipeUp drive the reconnect.
|
||||
if (this.pipeWatcher.isPipeLive(this.pid)) {
|
||||
this.injected = true;
|
||||
this._method = this._method || 'reconnect';
|
||||
this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid);
|
||||
} else {
|
||||
this.injectResult = this.injector.inject(this.pid);
|
||||
this.injected = true;
|
||||
this._method = this.injectResult.method;
|
||||
}
|
||||
}
|
||||
this.setStatus(
|
||||
this.connected ? (this.loggedIn ? 'online' : 'loaded') : 'connecting',
|
||||
'',
|
||||
);
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this.setStatus('error', this._error);
|
||||
this.log.error('load failed: PID=%d err=%s', this.pid, this._error);
|
||||
}
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
private async unloadInternal(): Promise<HookProcessInfo> {
|
||||
this._error = '';
|
||||
try {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
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);
|
||||
}
|
||||
|
||||
this.injected = false;
|
||||
this.injectResult = null;
|
||||
this._method = '';
|
||||
this._uin = '0';
|
||||
|
||||
// Verify the unload took: if the pipe is still up the DLL is still
|
||||
// resident. The cached snapshot is up to 1500ms stale and we just
|
||||
// changed the world, so force a fresh poll first — otherwise even
|
||||
// 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);
|
||||
this.log.warn('unload verification failed: PID=%d pipe still up', this.pid);
|
||||
} else {
|
||||
this.setStatus('available', '');
|
||||
}
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
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 {
|
||||
const pipeUp = this.pipeWatcher.isPipeLive(this.pid);
|
||||
if (pipeUp) {
|
||||
// Adopt an unknown DLL the same way onPipeUp would.
|
||||
if (!this.injected) {
|
||||
this.injected = true;
|
||||
this._method = this._method || 'reconnect';
|
||||
}
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.connected) {
|
||||
await this.attemptConnect();
|
||||
} else {
|
||||
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
|
||||
}
|
||||
} else {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
this.setStatus(this.injected ? 'disconnected' : 'available', '');
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
}
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
|
||||
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
|
||||
}
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
// ─────────────── client plumbing ───────────────
|
||||
|
||||
private async attemptConnect(): Promise<void> {
|
||||
if (this.connected) return;
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.client) {
|
||||
this.client = this.makeClient(this.pid);
|
||||
this.sender = new HookPacketClient(this.client);
|
||||
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;
|
||||
this.setStatus(client.isLoggedIn ? 'online' : 'loaded', '');
|
||||
const loginState = client.getLoginState();
|
||||
if (loginState.loggedIn) this.handleLoginState(loginState);
|
||||
this.log.info('pipe connected: PID=%d', this.pid);
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
// Drop the client so the next attempt builds a fresh socket pair.
|
||||
this.tearDownClient();
|
||||
this.setStatus(this.injected ? 'connecting' : 'available', this._error);
|
||||
}
|
||||
}
|
||||
|
||||
private bindClient(client: QqHookClient): void {
|
||||
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;
|
||||
// Only the currently-registered client should drive a reconcile;
|
||||
// listeners may fire for an already-replaced client.
|
||||
if (this.client !== client) return;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
if (this.client !== client) return;
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
if (!this.injected) {
|
||||
this.setStatus('available', '');
|
||||
} else if (wasLoggedIn) {
|
||||
this.setStatus('disconnected', '');
|
||||
} else {
|
||||
this.setStatus('connecting', '');
|
||||
}
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
}).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
});
|
||||
}
|
||||
|
||||
private tearDownClient(): void {
|
||||
const client = this.client;
|
||||
if (client) {
|
||||
client.removeAllListeners();
|
||||
try { client.close(); } catch { /* ignore */ }
|
||||
}
|
||||
this.client = null;
|
||||
this.sender = null;
|
||||
this.bound = false;
|
||||
this.connected = false;
|
||||
this.loggedIn = false;
|
||||
}
|
||||
|
||||
private handleLoginState(state: QqHookLoginState): void {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
const previousUin = this._uin;
|
||||
this._uin = state.uin || state.uinNumber.toString();
|
||||
this.loggedIn = state.loggedIn && isRealUin(this._uin);
|
||||
|
||||
if (this.loggedIn) {
|
||||
this.setStatus('online', '');
|
||||
} else if (this.connected) {
|
||||
this.setStatus('loaded', this._error);
|
||||
}
|
||||
|
||||
if (!this.loggedIn || !this.sender) return;
|
||||
if (wasLoggedIn && previousUin === this._uin) return;
|
||||
|
||||
this.emit('login', this._uin, this.sender);
|
||||
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
|
||||
}
|
||||
|
||||
private handlePacket(packet: QqHookPacket): void {
|
||||
if (!this.loggedIn) return;
|
||||
const uin = packet.uin || this._uin;
|
||||
if (!isRealUin(uin)) return;
|
||||
if (!this.onPacket) return;
|
||||
// Re-shape the hook-client wire packet into the canonical PacketInfo
|
||||
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
|
||||
// renaming was that module's entire purpose, so it lives at the source
|
||||
// now (no need for a single-listener event-emitter in between).
|
||||
this.onPacket({
|
||||
pid: this.pid,
|
||||
uin,
|
||||
serviceCmd: packet.cmd,
|
||||
seqId: packet.seq,
|
||||
retCode: packet.error,
|
||||
fromClient: false,
|
||||
body: Buffer.from(packet.body),
|
||||
});
|
||||
}
|
||||
|
||||
private setStatus(status: HookProcessStatus, error: string): void {
|
||||
if (this._status === status && this._error === error) return;
|
||||
this._status = status;
|
||||
this._error = error;
|
||||
this.emit('status-changed', status, error);
|
||||
}
|
||||
}
|
||||
|
||||
function isRealUin(uin: string): boolean {
|
||||
if (!uin || uin === '0') return false;
|
||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
15
packages/channel-hook/src/index.ts
Normal file
15
packages/channel-hook/src/index.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
// `@snowluma/channel-hook` — the `inject` channel implementation
|
||||
// (NTQQ in-process hook). Registered with `Hub` from `@snowluma/core`
|
||||
// as a `ChannelAdapter` of kind `'inject'`. Everything pid-related is
|
||||
// scoped to this package — neither `@snowluma/channel` nor anything
|
||||
// downstream knows about it.
|
||||
|
||||
// ─── Hook runtime ──────────────────────────────────────────────────
|
||||
export {
|
||||
HookManager, type HookSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
|
||||
type HookProcessStatus, type QqPortLoginInfo
|
||||
} from './hook-manager';
|
||||
|
||||
// ─── Concrete Channel + Adapter ────────────────────────────────────
|
||||
export { HookChannel } from './hook-channel';
|
||||
export { HookAdapter, type HookAdapterOptions } from './hook-adapter';
|
||||
@@ -2,8 +2,6 @@ import { existsSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
import { listSnowlumaPipePidsSync } from './qq-hook-client';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface ManualMapHandle {
|
||||
@@ -15,7 +13,7 @@ export interface ManualMapHandle {
|
||||
|
||||
interface NativeHookAddon {
|
||||
getAllMainProcess(): number[];
|
||||
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
|
||||
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle;
|
||||
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
|
||||
}
|
||||
|
||||
@@ -57,9 +55,9 @@ function defaultProcessName(): string {
|
||||
function nativeSearchDirs(): string[] {
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
|
||||
// 2. Dev via tsx (packages/channel/src/injector.ts): __dirname=<root>/packages/channel/src
|
||||
// → walk up to <root>/packages and append runtime/native
|
||||
// Same offset works for `packages/bridge/dist/index.mjs` after build.
|
||||
// Same offset works for `packages/channel/dist/index.mjs` after build.
|
||||
// 3. cwd-based fallback when neither __dirname-relative path resolves.
|
||||
return [
|
||||
path.resolve(__dirname, 'native'),
|
||||
@@ -100,17 +98,6 @@ export function getNativeHookLoadError(): string | null {
|
||||
}
|
||||
|
||||
export function listHookProcesses(): HookProcessBaseInfo[] {
|
||||
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
|
||||
// means QQ ran with our dylib already mapped, so the dylib's listener
|
||||
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
|
||||
// in the runtime dir as a known process (the watcher's subsequent
|
||||
// connectable-probe gates the pipe-up emit, so a stale dangling socket
|
||||
// here doesn't drive a false connect).
|
||||
if (process.platform === 'darwin') {
|
||||
return [...listSnowlumaPipePidsSync()]
|
||||
.sort((a, b) => a - b)
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) return [];
|
||||
return [...new Set(addon.getAllMainProcess())]
|
||||
@@ -119,7 +106,7 @@ export function listHookProcesses(): HookProcessBaseInfo[] {
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
|
||||
export async function injectHookProcess(pid: number): Promise<HookInjectResult> {
|
||||
export function injectHookProcess(pid: number): HookInjectResult {
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
@@ -129,7 +116,7 @@ export async function injectHookProcess(pid: number): Promise<HookInjectResult>
|
||||
if (!dllPath) {
|
||||
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
|
||||
}
|
||||
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) };
|
||||
return { method: 'loadModuleManual', handle: addon.loadModuleManual(pid, dllPath) };
|
||||
}
|
||||
|
||||
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
|
||||
@@ -6,11 +6,8 @@ const DEFAULT_INTERVAL_MS = 1500;
|
||||
const MIN_INTERVAL_MS = 250;
|
||||
|
||||
export type PipeWatcherDeps = {
|
||||
/** Native: list QQ.exe processes currently running. May be async and may
|
||||
* return `null` (UNKNOWN) when enumeration timed out / failed — in which
|
||||
* case this tick keeps the prior process+pipe state instead of treating the
|
||||
* missing data as "everything disappeared" (issue #158). */
|
||||
listProcesses: () => HookProcessBaseInfo[] | null | Promise<HookProcessBaseInfo[] | null>;
|
||||
/** Native: list QQ.exe processes currently running. */
|
||||
listProcesses: () => HookProcessBaseInfo[];
|
||||
/** Native: PIDs that currently have a live SnowLuma named pipe. */
|
||||
listLivePipes: () => Promise<Set<number>>;
|
||||
/** Polling interval in ms. Defaults to 1500, floored to 250. */
|
||||
@@ -141,22 +138,12 @@ export class PipeWatcher extends EventEmitter {
|
||||
}
|
||||
this.ticking = true;
|
||||
try {
|
||||
let processes: HookProcessBaseInfo[] | null;
|
||||
let processes: HookProcessBaseInfo[];
|
||||
try {
|
||||
processes = await this.listProcesses();
|
||||
processes = this.listProcesses();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
processes = null;
|
||||
}
|
||||
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
|
||||
// Treating missing data as "everything disappeared" would fire
|
||||
// process-gone for every live PID and dispose healthy sessions — the
|
||||
// freeze-then-teardown footgun behind issue #158. Still emit 'tick' so
|
||||
// the manager's per-tick reconnect retries keep running off last-known
|
||||
// live pipes.
|
||||
if (processes === null) {
|
||||
this.emit('tick');
|
||||
return;
|
||||
processes = [];
|
||||
}
|
||||
let livePipes: Set<number>;
|
||||
try {
|
||||
@@ -1,12 +1,5 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import {
|
||||
createLogger,
|
||||
renderTraceBytes,
|
||||
runWithoutRequestContext,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import { readdirSync, promises as fs } from 'fs';
|
||||
import { promises as fs } from 'fs';
|
||||
import net from 'net';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
@@ -17,8 +10,6 @@ export const HEADER_SIZE = 40;
|
||||
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
|
||||
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
|
||||
const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250;
|
||||
const packetLog = createLogger('QQHook.Packet');
|
||||
const runtimeLog = createLogger('QQHook.Runtime');
|
||||
|
||||
export enum PipeOp {
|
||||
hello = 1,
|
||||
@@ -94,59 +85,12 @@ interface PendingAck {
|
||||
wantReply: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync directory scan for `mojo.<pid>.control.sock` socket files in the
|
||||
* runtime dir, returning the pid set. Used by the darwin path of
|
||||
* `listHookProcesses()` — on macOS the DYLD_INSERT injection model means
|
||||
* there is no native enumerate-QQ-processes addon; the existence of our
|
||||
* dylib's listener socket IS the proof that a QQ process is hooked. The
|
||||
* sync variant is needed because the watcher's `listProcesses` dep is sync.
|
||||
*
|
||||
* Mirrors `listLiveLinuxPipePids` (the async + connectable-probe variant)
|
||||
* but skips the connectable probe — the existence of the socket file is
|
||||
* 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 = linuxRuntimeDir(),
|
||||
): Set<number> {
|
||||
const result = new Set<number>();
|
||||
let names: string[];
|
||||
try {
|
||||
names = readdirSync(runtimeDir);
|
||||
} catch {
|
||||
return result;
|
||||
}
|
||||
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 linuxRuntimeDir(): string {
|
||||
// Name kept for historical reasons (the function predates the macOS port);
|
||||
// applies to every non-win32 platform. The fallback order mirrors each
|
||||
// platform hook's runtime_dir(): explicit override first, then the OS-
|
||||
// native ephemeral-dir convention.
|
||||
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
|
||||
if (explicit && explicit.length > 0) return explicit;
|
||||
const xdg = process.env.XDG_RUNTIME_DIR;
|
||||
if (xdg && xdg.length > 0) return xdg;
|
||||
// macOS: dylib defaults to "$TMPDIR/snowluma-hook" (apps/qq/macos/
|
||||
// qq_hook_dylib.cpp's runtime_dir()). $TMPDIR is per-user on macOS
|
||||
// (under /var/folders/.../T) so this is the right place — Linux's
|
||||
// /tmp/snowluma-<uid> doesn't exist on a stock Mac.
|
||||
if (process.platform === 'darwin') {
|
||||
const tmpdir = process.env.TMPDIR;
|
||||
if (tmpdir && tmpdir.length > 0) {
|
||||
const trimmed = tmpdir.endsWith('/') ? tmpdir.slice(0, -1) : tmpdir;
|
||||
return path.join(trimmed, 'snowluma-hook');
|
||||
}
|
||||
}
|
||||
// Linux fallback: mirrors hook_stub.cpp runtime_dir() last-resort.
|
||||
// Mirrors hook_stub.cpp runtime_dir() fallback.
|
||||
// process.geteuid is POSIX-only; cast to allow non-Linux type checks.
|
||||
const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid;
|
||||
return `/tmp/snowluma-${uid}`;
|
||||
@@ -234,21 +178,11 @@ function createDeferred<T>(): Deferred<T> {
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
class OperationTimeoutError extends Error {
|
||||
constructor(
|
||||
readonly label: string,
|
||||
timeoutMs: number,
|
||||
) {
|
||||
super(`${label} timed out after ${timeoutMs} ms`);
|
||||
this.name = 'OperationTimeoutError';
|
||||
}
|
||||
}
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
|
||||
if (!timeoutMs || timeoutMs <= 0) return promise;
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
reject(new OperationTimeoutError(label, timeoutMs));
|
||||
reject(new Error(`${label} timed out after ${timeoutMs} ms`));
|
||||
}, timeoutMs);
|
||||
promise.then(
|
||||
value => {
|
||||
@@ -262,25 +196,6 @@ function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string):
|
||||
});
|
||||
}
|
||||
|
||||
class HookPipeRequestError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'HookPipeRequestError';
|
||||
}
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
return 'transport_failure';
|
||||
}
|
||||
|
||||
function encodeFrame({
|
||||
op,
|
||||
requestId = 0,
|
||||
@@ -412,19 +327,6 @@ export class QqHookClient extends EventEmitter {
|
||||
return { ...this.loginState };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile a login edge that the native hook could not replay after the
|
||||
* pipe connected. The client remains the single source of truth so packet
|
||||
* sending, login waiters, and HookSession all observe the same transition.
|
||||
*/
|
||||
reconcileLoginState(state: QqHookLoginState): void {
|
||||
this.applyLoginState({
|
||||
loggedIn: state.loggedIn,
|
||||
uin: state.uin || state.uinNumber.toString(),
|
||||
uinNumber: state.uinNumber,
|
||||
});
|
||||
}
|
||||
|
||||
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
|
||||
await this.connect();
|
||||
if (this.loginState.loggedIn) {
|
||||
@@ -486,7 +388,14 @@ export class QqHookClient extends EventEmitter {
|
||||
if (this.controlConnectPromise) {
|
||||
return this.controlConnectPromise;
|
||||
}
|
||||
this.controlConnectPromise = this.connectPipe('control');
|
||||
this.controlConnectPromise = (async () => {
|
||||
this.controlSocket = await this.connectSocket(
|
||||
QqHookClient.controlPipeName(this.pid),
|
||||
'control',
|
||||
frame => this.handleControlFrame(frame));
|
||||
this.controlHello = await this.waitForHello(false);
|
||||
return this.controlHello;
|
||||
})();
|
||||
try {
|
||||
return await this.controlConnectPromise;
|
||||
} finally {
|
||||
@@ -507,7 +416,14 @@ export class QqHookClient extends EventEmitter {
|
||||
if (this.recvConnectPromise) {
|
||||
return this.recvConnectPromise;
|
||||
}
|
||||
this.recvConnectPromise = this.connectPipe('recv');
|
||||
this.recvConnectPromise = (async () => {
|
||||
this.recvSocket = await this.connectSocket(
|
||||
QqHookClient.recvPipeName(this.pid),
|
||||
'recv',
|
||||
frame => this.handleRecvFrame(frame));
|
||||
this.recvHello = await this.waitForHello(true);
|
||||
return this.recvHello;
|
||||
})();
|
||||
try {
|
||||
return await this.recvConnectPromise;
|
||||
} finally {
|
||||
@@ -540,30 +456,15 @@ export class QqHookClient extends EventEmitter {
|
||||
}
|
||||
this.nextRequestId = (requestId + 1) >>> 0;
|
||||
if (this.nextRequestId === 0) this.nextRequestId = 1;
|
||||
const startedAt = Date.now();
|
||||
const bodyBytes = toBuffer(body);
|
||||
const payload = encodeFrame({
|
||||
op: PipeOp.sendRequest,
|
||||
requestId,
|
||||
flags: wantReply ? PipeFlagWantReply : 0,
|
||||
cmd,
|
||||
body: bodyBytes,
|
||||
body,
|
||||
});
|
||||
packetLog.trace(() => [
|
||||
'packet_send serviceCmd=%j requestId=%d length=%d body=%s',
|
||||
cmd,
|
||||
requestId,
|
||||
bodyBytes.length,
|
||||
renderTraceBytes(bodyBytes),
|
||||
]);
|
||||
|
||||
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
|
||||
// Always attach a handler so a rejection can never become "unhandled" (which
|
||||
// crashes Node). When the pipe closes, rejectControlPending() rejects every
|
||||
// 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 */ });
|
||||
this.pendingAcks.set(requestId, {
|
||||
resolve: ackDeferred.resolve,
|
||||
reject: ackDeferred.reject,
|
||||
@@ -573,7 +474,6 @@ 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 */ });
|
||||
this.pendingReplies.set(requestId, replyDeferred);
|
||||
}
|
||||
|
||||
@@ -581,50 +481,15 @@ export class QqHookClient extends EventEmitter {
|
||||
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',
|
||||
cmd,
|
||||
requestId,
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
return { requestId };
|
||||
}
|
||||
const reply = await withTimeout(
|
||||
return await withTimeout(
|
||||
replyDeferred!.promise,
|
||||
replyTimeoutMs,
|
||||
`send reply ${requestId}`);
|
||||
packetLog.trace(() => [
|
||||
'packet_recv serviceCmd=%j requestId=%d error=%d message=%j length=%d body=%s',
|
||||
cmd,
|
||||
requestId,
|
||||
reply.error,
|
||||
reply.message,
|
||||
reply.body.length,
|
||||
renderTraceBytes(reply.body),
|
||||
]);
|
||||
packetLog.trace(() => [
|
||||
'packet_terminal serviceCmd=%j requestId=%d outcome=%s reason=%s error=%d elapsedMs=%d',
|
||||
cmd,
|
||||
requestId,
|
||||
reply.error === 0 ? 'ok' : 'failed',
|
||||
reply.error === 0 ? 'reply_received' : 'reply_error',
|
||||
reply.error,
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
return reply;
|
||||
} catch (error) {
|
||||
this.pendingAcks.delete(requestId);
|
||||
this.pendingReplies.delete(requestId);
|
||||
const reason = packetFailureReason(error, requestId);
|
||||
packetLog.trace(() => [
|
||||
'packet_terminal serviceCmd=%j requestId=%d outcome=%s reason=%s error=%j elapsedMs=%d',
|
||||
cmd,
|
||||
requestId,
|
||||
reason.endsWith('_timeout') ? 'timeout' : 'failed',
|
||||
reason,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -763,60 +628,6 @@ export class QqHookClient extends EventEmitter {
|
||||
return writePromise;
|
||||
}
|
||||
|
||||
private async connectPipe(kind: 'control' | 'recv'): Promise<QqHookHello> {
|
||||
return runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
const pipeName = kind === 'control'
|
||||
? QqHookClient.controlPipeName(this.pid)
|
||||
: QqHookClient.recvPipeName(this.pid);
|
||||
let phase: 'connect' | 'hello' = 'connect';
|
||||
runtimeLog.trace(
|
||||
'hook_pipe_start pid=%d kind=%s pipeName=%j',
|
||||
this.pid,
|
||||
kind,
|
||||
pipeName,
|
||||
);
|
||||
try {
|
||||
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;
|
||||
runtimeLog.trace(
|
||||
'hook_pipe_branch pid=%d kind=%s branch=socket_connected',
|
||||
this.pid,
|
||||
kind,
|
||||
);
|
||||
phase = 'hello';
|
||||
const hello = await this.waitForHello(kind === 'recv');
|
||||
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,
|
||||
kind,
|
||||
renderParamsVerbose(hello),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
return hello;
|
||||
} catch (error) {
|
||||
runtimeLog.trace(() => [
|
||||
'hook_pipe_terminal pid=%d kind=%s outcome=failed reason=%s error=%j elapsedMs=%d',
|
||||
this.pid,
|
||||
kind,
|
||||
phase === 'connect' ? 'connect_failed' : 'hello_failed',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private connectSocket(pipeName: string, kind: 'control' | 'recv', onFrame: (frame: PipeFrame) => void): Promise<net.Socket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = net.createConnection(pipeName);
|
||||
@@ -837,10 +648,8 @@ export class QqHookClient extends EventEmitter {
|
||||
this.emit('error', error);
|
||||
});
|
||||
socket.on('close', () => {
|
||||
runWithTraceRequest(() => {
|
||||
this.handleSocketClose(kind);
|
||||
this.emit('close', kind);
|
||||
});
|
||||
this.handleSocketClose(kind);
|
||||
this.emit('close', kind);
|
||||
});
|
||||
resolve(socket);
|
||||
});
|
||||
@@ -870,13 +679,6 @@ export class QqHookClient extends EventEmitter {
|
||||
}
|
||||
|
||||
private handleSocketClose(kind: 'control' | 'recv'): void {
|
||||
runtimeLog.trace(
|
||||
'hook_runtime_fact pid=%d event=pipe_closed kind=%s loggedIn=%s uin=%j',
|
||||
this.pid,
|
||||
kind,
|
||||
this.loginState.loggedIn,
|
||||
this.loginState.uin,
|
||||
);
|
||||
if (kind === 'control') {
|
||||
this.controlSocket = null;
|
||||
this.controlHello = null;
|
||||
@@ -894,32 +696,17 @@ export class QqHookClient extends EventEmitter {
|
||||
const loggedIn = flaggedLoggedIn || statusLoggedIn;
|
||||
const uinNumber = BigInt(frame.value0);
|
||||
const uin = frame.msg || uinNumber.toString();
|
||||
this.applyLoginState({ loggedIn, uin, uinNumber });
|
||||
}
|
||||
|
||||
private applyLoginState(next: QqHookLoginState): void {
|
||||
const previous = this.loginState;
|
||||
const next = { loggedIn, uin, uinNumber };
|
||||
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',
|
||||
this.pid,
|
||||
previous.loggedIn,
|
||||
previous.uin,
|
||||
next.loggedIn,
|
||||
next.uin,
|
||||
);
|
||||
this.emit('loginState', next);
|
||||
this.emit('loginState', next);
|
||||
if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) {
|
||||
if (next.loggedIn) {
|
||||
const waiters = this.loginWaiters;
|
||||
this.loginWaiters = [];
|
||||
for (const waiter of waiters) waiter.resolve({ ...next });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private handleControlFrame(frame: PipeFrame): void {
|
||||
@@ -951,7 +738,7 @@ export class QqHookClient extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
if (frame.op === PipeOp.error) {
|
||||
const error = new HookPipeRequestError(frame.msg || `pipe error ${frame.status}`);
|
||||
const error = new Error(frame.msg || `pipe error ${frame.status}`);
|
||||
const ack = this.pendingAcks.get(frame.requestId);
|
||||
if (ack) {
|
||||
this.pendingAcks.delete(frame.requestId);
|
||||
168
packages/channel-hook/src/qq-port-probe.ts
Normal file
168
packages/channel-hook/src/qq-port-probe.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
import { exec } from 'child_process';
|
||||
import net from 'net';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
const PORT_RANGE_START = 9210;
|
||||
const PORT_RANGE_END = 9219;
|
||||
const PROBE_TIMEOUT_MS = 1000;
|
||||
const CONNECTION_TIMEOUT_MS = 500;
|
||||
|
||||
export interface QqPortLoginInfo {
|
||||
port: number;
|
||||
uin: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
loggedIn: boolean;
|
||||
}
|
||||
|
||||
interface JwtPayload {
|
||||
errCode: number;
|
||||
errMsg: string;
|
||||
port: number;
|
||||
uin?: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
data?: {
|
||||
uin?: string;
|
||||
url?: string;
|
||||
};
|
||||
iat: number;
|
||||
}
|
||||
|
||||
function decodeJwt(token: string): JwtPayload | null {
|
||||
try {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) return null;
|
||||
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
|
||||
return JSON.parse(payload);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
|
||||
return new Promise((resolve) => {
|
||||
const client = new net.Socket();
|
||||
const link = 'tencent://';
|
||||
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
|
||||
|
||||
let responseData = '';
|
||||
let timer: NodeJS.Timeout;
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
client.removeAllListeners();
|
||||
client.destroy();
|
||||
};
|
||||
|
||||
timer = setTimeout(() => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
}, PROBE_TIMEOUT_MS);
|
||||
|
||||
client.setTimeout(CONNECTION_TIMEOUT_MS);
|
||||
|
||||
client.connect(port, '127.0.0.1', () => {
|
||||
client.write(payload);
|
||||
});
|
||||
|
||||
client.on('data', (data) => {
|
||||
responseData += data.toString();
|
||||
});
|
||||
|
||||
client.on('close', () => {
|
||||
cleanup();
|
||||
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
|
||||
if (!jwtMatch) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const decoded = decodeJwt(jwtMatch[0]);
|
||||
if (!decoded || decoded.errCode !== 0) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const uin = decoded.uin || decoded.data?.uin || '';
|
||||
resolve({
|
||||
port,
|
||||
uin,
|
||||
uid: decoded.uid,
|
||||
nickName: decoded.nickName,
|
||||
loggedIn: uin.length > 0,
|
||||
});
|
||||
});
|
||||
|
||||
client.on('error', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
|
||||
client.on('timeout', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
if (parts.length < 5) continue;
|
||||
const owningPid = parts[parts.length - 1];
|
||||
if (owningPid !== String(pid)) continue;
|
||||
const localAddr = parts[1];
|
||||
const portMatch = localAddr.match(/:(\d+)$/);
|
||||
if (!portMatch) continue;
|
||||
const port = Number(portMatch[1]);
|
||||
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
|
||||
ports.add(port);
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
const match = line.match(/:(\d+)\s/);
|
||||
if (match) {
|
||||
const port = Number(match[1]);
|
||||
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
|
||||
ports.add(port);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
|
||||
if (ports.length === 0) {
|
||||
for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const port of ports) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
182
packages/channel-hook/tests/hook-manager.test.ts
Normal file
182
packages/channel-hook/tests/hook-manager.test.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { HookSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
|
||||
function makeManager(opts: {
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
processes?: number[];
|
||||
}) {
|
||||
let pids = opts.processes ?? [];
|
||||
const live = new Set<number>();
|
||||
const inject = vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE }));
|
||||
const unload = vi.fn();
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
// FakeClient — never connected; just needs to satisfy EventEmitter +
|
||||
// a minimal subset of QqHookClient for HookSession.tearDownClient().
|
||||
const makeClient = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { throw new Error('test: never really connect'); };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const sink = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as HookSink;
|
||||
const manager = new HookManager({
|
||||
sink,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
inject,
|
||||
pipeWatcher,
|
||||
setProcesses: (next: number[]) => { pids = next; },
|
||||
};
|
||||
}
|
||||
|
||||
describe('HookManager.autoLoadOnDiscovery', () => {
|
||||
it('does NOT inject on process-discovered when flag is off', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
expect(ctx.inject).not.toHaveBeenCalled();
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('injects every newly-discovered PID when flag is on', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
// session.load() is queued via a per-session promise chain; flush twice
|
||||
// so the auto-load runs to completion before we assert.
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.inject).toHaveBeenCalledWith(4242);
|
||||
|
||||
// A second PID appearing mid-flight should also trigger an inject.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('swallows inject errors so the watcher keeps running', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Second PID should still be auto-loaded — the failure on 4242 must
|
||||
// not leak out of the listener and break the watcher's emit loop.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
// `shouldAutoLoadPid` reads /proc/<pid>/cmdline directly, so we point
|
||||
// it at a temporary directory that mimics the procfs layout. This lets
|
||||
// the tests run on macOS / CI without a live Linux QQ process.
|
||||
describe('shouldAutoLoadPid', () => {
|
||||
let tmpProc: string;
|
||||
const originalReadFileSync = fs.readFileSync;
|
||||
const log = createLogger('test');
|
||||
const originalPlatform = process.platform;
|
||||
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((p: string, ...rest: unknown[]) => {
|
||||
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
|
||||
if (match) {
|
||||
return originalReadFileSync(path.join(tmpProc, match[1], 'cmdline'), ...(rest as [BufferEncoding]));
|
||||
}
|
||||
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
|
||||
}) as typeof fs.readFileSync;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
|
||||
if (originalAutoLoadAll === undefined) delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
else process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
|
||||
fs.rmSync(tmpProc, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function writeCmdline(pid: number, args: string[]): void {
|
||||
const dir = path.join(tmpProc, String(pid));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
|
||||
}
|
||||
|
||||
it('allows the QQ main process (no --type=)', () => {
|
||||
writeCmdline(50, ['qq', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(50, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects Electron zygotes', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects renderer/gpu/utility children', () => {
|
||||
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
|
||||
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
|
||||
writeCmdline(72, ['/opt/QQ/qq', '--type=utility', '--utility-sub-type=network.mojom.NetworkService']);
|
||||
expect(shouldAutoLoadPid(70, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(71, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(72, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
||||
// No cmdline file needed — we return true before touching procfs.
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
|
||||
expect(shouldAutoLoadPid(99999, log)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import { EventEmitter } from 'events';
|
||||
import { HookManager } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { HookSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
@@ -41,14 +41,14 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
intervalMs: 60_000, // manual ticks only
|
||||
});
|
||||
|
||||
const bridgeManager = {
|
||||
const sink = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
} as unknown as HookSink;
|
||||
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
sink,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
@@ -82,9 +82,9 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
|
||||
// The "QQ never logs in" hypothesis: BridgeManager should never have
|
||||
// been told about a login or a disconnect.
|
||||
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
|
||||
expect(sink.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(sink.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(sink.onPacket).not.toHaveBeenCalled();
|
||||
|
||||
// Hook layer should hold at most one live client.
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
446
packages/channel-hook/tests/hook-session.test.ts
Normal file
446
packages/channel-hook/tests/hook-session.test.ts
Normal file
@@ -0,0 +1,446 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookSession } from '../src/hook-session';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
|
||||
/** Minimal stand-in for QqHookClient. Tests drive login/packet/error/close
|
||||
* events directly via fire* helpers. connectAll succeeds unless told otherwise. */
|
||||
class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
shouldFailConnect = false;
|
||||
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');
|
||||
}
|
||||
getLoginState() { return { ...this.loginState }; }
|
||||
close(): void {
|
||||
if (this.isClosed) return;
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
|
||||
fireLogin(uin: string): void {
|
||||
this.isLoggedIn = true;
|
||||
this.loginState = { loggedIn: true, uin, uinNumber: BigInt(uin) };
|
||||
this.emit('loginState', { ...this.loginState });
|
||||
}
|
||||
|
||||
firePacket(packet: QqHookPacket): void {
|
||||
this.emit('packet', packet);
|
||||
}
|
||||
}
|
||||
|
||||
function makeSession(opts: {
|
||||
pid?: number;
|
||||
pipeLive?: boolean;
|
||||
clientFailsConnect?: boolean;
|
||||
onPacket?: PacketSink;
|
||||
} = {}) {
|
||||
const pid = opts.pid ?? 1234;
|
||||
let pipeLive = opts.pipeLive ?? false;
|
||||
const clients: FakeClient[] = [];
|
||||
const injector = {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
};
|
||||
|
||||
const session = new HookSession(pid, {
|
||||
injector,
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
if (opts.clientFailsConnect) c.shouldFailConnect = true;
|
||||
clients.push(c);
|
||||
// Cast: FakeClient mirrors only the surface HookSession touches.
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
onPacket: opts.onPacket,
|
||||
});
|
||||
|
||||
return {
|
||||
session,
|
||||
injector,
|
||||
clients,
|
||||
currentClient: () => clients[clients.length - 1]!,
|
||||
setPipeLive: (v: boolean) => { pipeLive = v; },
|
||||
};
|
||||
}
|
||||
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
|
||||
describe('HookSession — load', () => {
|
||||
it('with no live pipe: injects, status → connecting, method from inject result', async () => {
|
||||
const { session, injector } = makeSession({ pipeLive: false });
|
||||
const info = await session.load();
|
||||
|
||||
expect(injector.inject).toHaveBeenCalledOnce();
|
||||
expect(info.status).toBe('connecting');
|
||||
expect(info.method).toBe('loadModuleManual');
|
||||
expect(info.injected).toBe(true);
|
||||
});
|
||||
|
||||
it('fast-path: pipe already live → skip inject, method → "reconnect"', async () => {
|
||||
const { session, injector } = makeSession({ pipeLive: true });
|
||||
const info = await session.load();
|
||||
|
||||
expect(injector.inject).not.toHaveBeenCalled();
|
||||
expect(info.method).toBe('reconnect');
|
||||
expect(info.injected).toBe(true);
|
||||
expect(info.status).toBe('connecting');
|
||||
});
|
||||
|
||||
it('inject failure → status error, error message captured', async () => {
|
||||
const injector = {
|
||||
inject: vi.fn(() => { throw new Error('inject boom'); }),
|
||||
unload: vi.fn(),
|
||||
};
|
||||
const session = new HookSession(1234, {
|
||||
injector,
|
||||
makeClient: () => new FakeClient() as unknown as QqHookClient,
|
||||
pipeWatcher: { isPipeLive: () => false },
|
||||
});
|
||||
const info = await session.load();
|
||||
expect(info.status).toBe('error');
|
||||
expect(info.error).toBe('inject boom');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — pipe up/down → connect lifecycle', () => {
|
||||
it('onPipeUp after load: client connects → status loaded', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
expect(ctx.clients).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('emits "login" with (uin, sender) after client signals loggedIn', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
const [uin, sender] = loginSpy.mock.calls[0]!;
|
||||
expect(uin).toBe('10001');
|
||||
expect(typeof (sender as { sendPacket: unknown }).sendPacket).toBe('function');
|
||||
expect(ctx.session.status).toBe('online');
|
||||
expect(ctx.session.uin).toBe('10001');
|
||||
});
|
||||
|
||||
it('does not re-emit "login" on duplicate loginState with same uin', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('connect failure: stays in connecting, error message captured (will retry on next tick)', async () => {
|
||||
const ctx = makeSession({ pipeLive: true, clientFailsConnect: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
expect(ctx.session.status).toBe('connecting');
|
||||
expect(ctx.session.error).toBe('connect failed');
|
||||
});
|
||||
|
||||
it('onPipeDown while logged in: emits disconnected(true), status disconnected', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
ctx.session.onPipeDown();
|
||||
await flush();
|
||||
|
||||
expect(discSpy).toHaveBeenCalledWith(true);
|
||||
expect(ctx.session.status).toBe('disconnected');
|
||||
});
|
||||
|
||||
it('onPipeDown while connected-but-not-logged-in: emits disconnected(false), status connecting', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
// No login fired — we're connected but not logged in.
|
||||
|
||||
ctx.session.onPipeDown();
|
||||
await flush();
|
||||
|
||||
// disconnected(false) is currently NOT emitted — disconnect events are
|
||||
// reserved for "we owe BridgeManager a disconnect notification". This
|
||||
// preserves the original behaviour.
|
||||
expect(discSpy).not.toHaveBeenCalled();
|
||||
expect(ctx.session.status).toBe('connecting');
|
||||
});
|
||||
|
||||
it('repeated pipe down → up cycles reach consistent state', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
expect(ctx.session.status).toBe('online');
|
||||
|
||||
ctx.session.onPipeDown();
|
||||
await flush();
|
||||
expect(ctx.session.status).toBe('disconnected');
|
||||
|
||||
// Pipe returns — session builds a fresh client.
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
expect(ctx.clients.length).toBeGreaterThan(1);
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — unload', () => {
|
||||
it('while logged in: emits disconnected(true), calls unload, status available', async () => {
|
||||
const ctx = makeSession({ pipeLive: false });
|
||||
await ctx.session.load();
|
||||
ctx.setPipeLive(true);
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
ctx.setPipeLive(false); // unload verification will see the pipe gone
|
||||
|
||||
await ctx.session.unload();
|
||||
|
||||
expect(discSpy).toHaveBeenCalledWith(true);
|
||||
expect(ctx.injector.unload).toHaveBeenCalledOnce();
|
||||
expect(ctx.session.status).toBe('available');
|
||||
});
|
||||
|
||||
it('when pipe stays live after unload: status connecting with retry message', async () => {
|
||||
const ctx = makeSession({ pipeLive: false });
|
||||
await ctx.session.load();
|
||||
// Simulate the unload-failed scenario: pipe is still up after unload.
|
||||
ctx.setPipeLive(true);
|
||||
|
||||
const info = await ctx.session.unload();
|
||||
|
||||
expect(info.status).toBe('connecting');
|
||||
expect(info.error).toContain('命名管道仍然存在');
|
||||
});
|
||||
|
||||
it('forces a fresh tick before verifying so a stale snapshot does not false-flag a successful unload', async () => {
|
||||
// Reproduces the Windows-WebUI bug: PipeWatcher's cached snapshot is
|
||||
// up to 1500ms stale, so right after a successful native unload the
|
||||
// pre-fix code would read isPipeLive() == true and report failure
|
||||
// even though the DLL is gone. With the fix, tickNow() refreshes
|
||||
// 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 session = new HookSession(pid, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => new FakeClient() as unknown as QqHookClient,
|
||||
pipeWatcher: { isPipeLive: () => pipeLive, tickNow },
|
||||
});
|
||||
await session.load();
|
||||
pipeLive = true; // ensure the pre-check snapshot says "live"
|
||||
|
||||
const info = await session.unload();
|
||||
|
||||
expect(tickNow).toHaveBeenCalledOnce();
|
||||
expect(info.status).toBe('available');
|
||||
expect(info.error).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — serialization', () => {
|
||||
it('user mashing load → unload → load runs in order, end state consistent', async () => {
|
||||
const ctx = makeSession({ pipeLive: false });
|
||||
|
||||
const p1 = ctx.session.load();
|
||||
const p2 = ctx.session.unload();
|
||||
const p3 = ctx.session.load();
|
||||
await Promise.all([p1, p2, p3]);
|
||||
|
||||
expect(ctx.injector.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.injector.unload).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.session.status).toBe('connecting');
|
||||
});
|
||||
|
||||
it('onPipeUp queued behind in-flight load resolves correctly', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
|
||||
const loadPromise = ctx.session.load();
|
||||
ctx.session.onPipeUp(); // queued behind load
|
||||
|
||||
await loadPromise;
|
||||
await flush();
|
||||
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — process gone', () => {
|
||||
it('emits disconnected(true) then disposed when killed while logged in', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
const events: string[] = [];
|
||||
ctx.session.on('disconnected', () => events.push('disconnected'));
|
||||
ctx.session.on('disposed', () => events.push('disposed'));
|
||||
|
||||
ctx.session.notifyProcessGone();
|
||||
await flush();
|
||||
|
||||
expect(events).toEqual(['disconnected', 'disposed']);
|
||||
expect(ctx.session.isDisposed).toBe(true);
|
||||
});
|
||||
|
||||
it('emits only disposed when killed before login', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const events: string[] = [];
|
||||
ctx.session.on('disconnected', () => events.push('disconnected'));
|
||||
ctx.session.on('disposed', () => events.push('disposed'));
|
||||
|
||||
ctx.session.notifyProcessGone();
|
||||
await flush();
|
||||
|
||||
expect(events).toEqual(['disposed']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — packet forwarding', () => {
|
||||
// These tests cover the field-rename + filter logic that used to live
|
||||
// inside the deleted NtqqHandler.onHookPacket. Inlining it here means
|
||||
// we can exercise the transformation with a plain vi.fn() sink, no
|
||||
// event-emitter machinery required.
|
||||
|
||||
it('forwards parsed packets to onPacket sink with PacketInfo shape', async () => {
|
||||
const onPacket = vi.fn();
|
||||
const ctx = makeSession({ pipeLive: true, onPacket });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 42,
|
||||
error: 0,
|
||||
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
uin: '10001',
|
||||
body: Buffer.from([0x01, 0x02, 0x03]),
|
||||
});
|
||||
|
||||
expect(onPacket).toHaveBeenCalledOnce();
|
||||
const pkt = onPacket.mock.calls[0]![0];
|
||||
expect(pkt).toMatchObject({
|
||||
pid: 1234,
|
||||
uin: '10001',
|
||||
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
seqId: 42,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
});
|
||||
expect(Buffer.isBuffer(pkt.body)).toBe(true);
|
||||
expect([...pkt.body]).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('falls back to session uin when packet.uin is empty', async () => {
|
||||
const onPacket = vi.fn();
|
||||
const ctx = makeSession({ pipeLive: true, onPacket });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 1, error: 0, cmd: 'foo', uin: '', body: Buffer.alloc(0),
|
||||
});
|
||||
|
||||
expect(onPacket.mock.calls[0]![0].uin).toBe('10001');
|
||||
});
|
||||
|
||||
it('drops packets received before login', async () => {
|
||||
const onPacket = vi.fn();
|
||||
const ctx = makeSession({ pipeLive: true, onPacket });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
// No login fired yet.
|
||||
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.alloc(0),
|
||||
});
|
||||
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('drops packets whose uin is non-real ("0" / too short / non-numeric)', async () => {
|
||||
const onPacket = vi.fn();
|
||||
const ctx = makeSession({ pipeLive: true, onPacket });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
// Packet uin '0' falls back to session uin '10001' — that one passes.
|
||||
// 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),
|
||||
});
|
||||
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('is a no-op when no onPacket sink is provided', async () => {
|
||||
const ctx = makeSession({ pipeLive: true }); // no onPacket
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
// Should not throw / crash.
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.from([7]),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -192,40 +192,4 @@ describe('PipeWatcher', () => {
|
||||
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => {
|
||||
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
let live = new Set<number>([1234]);
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => result,
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
const events = captureEvents(watcher);
|
||||
|
||||
// Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ
|
||||
// hot-update). Prior process + pipe state MUST be preserved — no teardown.
|
||||
result = null;
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
// Enumeration recovers with the same set → still no churn.
|
||||
result = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
|
||||
// A REAL disappearance (empty list, not null) still fires the teardown.
|
||||
result = [];
|
||||
live = new Set();
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
|
||||
watcher.stop();
|
||||
});
|
||||
});
|
||||
44
packages/channel-hook/tests/qq-hook-client.test.ts
Normal file
44
packages/channel-hook/tests/qq-hook-client.test.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { mkdtemp, rm, writeFile } from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { listLiveLinuxPipePids } from '../src/qq-hook-client';
|
||||
|
||||
let tmpDir: string | null = null;
|
||||
|
||||
async function makeRuntimeDir(): Promise<string> {
|
||||
tmpDir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-hook-'));
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (!tmpDir) return;
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
tmpDir = null;
|
||||
});
|
||||
|
||||
describe('listLiveLinuxPipePids', () => {
|
||||
it('ignores stale-looking control socket names when the probe rejects them', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.recv.sock'), '');
|
||||
|
||||
const pids = await listLiveLinuxPipePids(runtimeDir, async () => false);
|
||||
|
||||
expect([...pids]).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns only connectable control sockets', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.56.control.sock'), '');
|
||||
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 pids = await listLiveLinuxPipePids(runtimeDir, probe);
|
||||
|
||||
expect([...pids]).toEqual([56]);
|
||||
expect(probe).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
16
packages/channel-hook/tsconfig.json
Normal file
16
packages/channel-hook/tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*",
|
||||
"tests"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
34
packages/channel-socket/package.json
Normal file
34
packages/channel-socket/package.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "@snowluma/channel-socket",
|
||||
"version": "1.9.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma `socket` channel implementation — placeholder for the future pure-socket runtime (no QQ.exe, no hook). Today registers as a no-op `ChannelAdapter` so the Hub-adapter architecture is exercised end-to-end. Will gain a `SocketClient` long-lived TCP login session when the protocol runtime lands.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./socket-channel": {
|
||||
"types": "./src/socket-channel.ts",
|
||||
"default": "./src/socket-channel.ts"
|
||||
},
|
||||
"./socket-adapter": {
|
||||
"types": "./src/socket-adapter.ts",
|
||||
"default": "./src/socket-adapter.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/channel": "workspace:*",
|
||||
"@snowluma/common": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
8
packages/channel-socket/src/index.ts
Normal file
8
packages/channel-socket/src/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// `@snowluma/channel-socket` — future pure-socket transport (no
|
||||
// QQ.exe, no hook). Today an empty stub so `Hub` can register it as a
|
||||
// `ChannelAdapter` of kind `'socket'` and exercise the adapter pool
|
||||
// end-to-end. Will materialise a real `SocketChannel` once the
|
||||
// pure-socket login client lands.
|
||||
|
||||
export { SocketChannel } from './socket-channel';
|
||||
export { SocketAdapter } from './socket-adapter';
|
||||
30
packages/channel-socket/src/socket-adapter.ts
Normal file
30
packages/channel-socket/src/socket-adapter.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel';
|
||||
|
||||
/**
|
||||
* `SocketAdapter` — placeholder for the future pure-socket runtime.
|
||||
* Once a `SocketClient` (long-lived TCP login session, heartbeat,
|
||||
* reconnect loop, …) lands, this adapter will:
|
||||
*
|
||||
* 1. Read its account list from runtime config.
|
||||
* 2. Spin up one `SocketClient` per configured account.
|
||||
* 3. On successful login, materialise a `SocketChannel` and call
|
||||
* `host.addChannel(channel)`.
|
||||
* 4. On logout / fatal error, call `host.removeChannel(channel.id)`.
|
||||
*
|
||||
* Until that lands the adapter is registered as a no-op so the wider
|
||||
* architecture (Hub → ChannelAdapter[] → Channel → Core) is already in
|
||||
* place and exercised in production. Registering it is harmless:
|
||||
* `start()` does nothing, `dispose()` does nothing, no channels are
|
||||
* ever produced.
|
||||
*/
|
||||
export class SocketAdapter implements ChannelAdapter {
|
||||
readonly kind = 'socket' as const;
|
||||
|
||||
start(host: ChannelAdapterHost): void {
|
||||
host.log.debug('socket adapter is a stub; no socket clients will be opened');
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
// Nothing to tear down yet.
|
||||
}
|
||||
}
|
||||
41
packages/channel-socket/src/socket-channel.ts
Normal file
41
packages/channel-socket/src/socket-channel.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Channel } from '@snowluma/channel';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
/**
|
||||
* `SocketChannel` — placeholder transport for the future pure-socket
|
||||
* runtime (no QQ.exe, no hook). It already participates in the `Hub`
|
||||
* (in `@snowluma/core`) so the wider architecture (ChannelAdapter pool
|
||||
* → Hub → Core → OneBot) is exercised end-to-end today; once a real
|
||||
* `SocketClient` lands the transport will gain a constructor argument
|
||||
* and `sendRawPacket` will route through it.
|
||||
*
|
||||
* Until then `sendRawPacket` returns a structured "not implemented"
|
||||
* failure rather than throwing, so the surrounding code treats it as
|
||||
* a regular transport-down result.
|
||||
*/
|
||||
export class SocketChannel extends Channel {
|
||||
readonly kind = 'socket' as const;
|
||||
readonly uin: string;
|
||||
|
||||
constructor(uin: string) {
|
||||
super();
|
||||
this.uin = uin;
|
||||
}
|
||||
|
||||
get id(): string { return `socket:${this.uin}`; }
|
||||
|
||||
override async sendRawPacket(
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
): Promise<SendPacketResult> {
|
||||
void serviceCmd; void body; void timeoutMs;
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: 'socket channel transport is not yet implemented',
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
44
packages/channel/package.json
Normal file
44
packages/channel/package.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "@snowluma/channel",
|
||||
"version": "1.9.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma transport abstract layer. Defines the `Channel` abstract base + `ChannelCtx` capability POJO + `ChannelAdapter` port that `Hub` (in @snowluma/core) consumes. Concrete transports live in `@snowluma/channel-hook` (in-process NTQQ hook) and `@snowluma/channel-socket` (future pure-socket).",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./channel": {
|
||||
"types": "./src/channel.ts",
|
||||
"default": "./src/channel.ts"
|
||||
},
|
||||
"./channel-interface": {
|
||||
"types": "./src/channel-interface.ts",
|
||||
"default": "./src/channel-interface.ts"
|
||||
},
|
||||
"./channel-ctx": {
|
||||
"types": "./src/channel-ctx.ts",
|
||||
"default": "./src/channel-ctx.ts"
|
||||
},
|
||||
"./adapter": {
|
||||
"types": "./src/adapter.ts",
|
||||
"default": "./src/adapter.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/common": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
}
|
||||
}
|
||||
15
packages/channel/src/adapter.ts
Normal file
15
packages/channel/src/adapter.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { Logger } from '@snowluma/common/logger';
|
||||
import type { Channel } from './channel';
|
||||
import type { ChannelKind } from './channel-interface';
|
||||
|
||||
export interface ChannelAdapterHost {
|
||||
addChannel(channel: Channel): void;
|
||||
removeChannel(channelId: string): void;
|
||||
readonly log: Logger;
|
||||
}
|
||||
|
||||
export interface ChannelAdapter {
|
||||
readonly kind: ChannelKind;
|
||||
start(host: ChannelAdapterHost): Promise<void> | void;
|
||||
dispose(): Promise<void> | void;
|
||||
}
|
||||
26
packages/channel/src/channel-ctx.ts
Normal file
26
packages/channel/src/channel-ctx.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { Channel } from './channel';
|
||||
import type { ChannelKind } from './channel-interface';
|
||||
|
||||
export interface ChannelCtx {
|
||||
readonly uin: string;
|
||||
readonly kind: ChannelKind;
|
||||
readonly sendRawPacket: (
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
) => Promise<SendPacketResult>;
|
||||
readonly onPacket: (handler: ((pkt: PacketInfo) => void) | null) => void;
|
||||
readonly dispose: () => void;
|
||||
}
|
||||
|
||||
export function makeChannelCtx(channel: Channel): ChannelCtx {
|
||||
return {
|
||||
uin: channel.uin,
|
||||
kind: channel.kind,
|
||||
sendRawPacket: (cmd, body, timeoutMs) => channel.sendRawPacket(cmd, body, timeoutMs),
|
||||
onPacket: (handler) => channel.setPacketHandler(handler),
|
||||
dispose: () => channel.dispose(),
|
||||
};
|
||||
}
|
||||
73
packages/channel/src/channel-interface.ts
Normal file
73
packages/channel/src/channel-interface.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
|
||||
/**
|
||||
* Discriminator for the two channel transport implementations:
|
||||
*
|
||||
* - `'inject'` — backed by an in-process NTQQ hook (one or more
|
||||
* QQ.exe processes injected with the SnowLuma DLL,
|
||||
* talking over named pipes). Implemented by
|
||||
* `HookChannel` in `@snowluma/channel-hook`.
|
||||
* - `'socket'` — backed by a direct protocol client (no QQ.exe, no
|
||||
* hook). Reserved for the future pure-protocol
|
||||
* runtime; `SocketChannel` is a stub until then.
|
||||
*
|
||||
* Mirrored on `CoreCtx.kind` so account-level consumers can branch on
|
||||
* transport without `instanceof` checks against a concrete subclass
|
||||
* (diagnostics, kind-specific WebUI panels, …).
|
||||
*/
|
||||
export type ChannelKind = 'inject' | 'socket';
|
||||
|
||||
/**
|
||||
* `ChannelInterface` — **strictly transport**. A channel owns one
|
||||
* wire-level connection to QQ for a given UIN: it sends opaque packets
|
||||
* out and surfaces received packets to whoever subscribed via
|
||||
* `setPacketHandler`.
|
||||
*
|
||||
* It deliberately knows nothing about identity caches, the event bus,
|
||||
* the api hub, or the cmd-dispatch pipeline — that machinery lives on
|
||||
* the `Core` layer (`@snowluma/core`) which wraps a `Channel` (via a
|
||||
* `ChannelCtx` capability POJO) to expose a business-level API to
|
||||
* OneBot and friends.
|
||||
*
|
||||
* Direct consumers are limited to:
|
||||
* - `ChannelAdapter` implementations (they create / dispose channels
|
||||
* and pump received packets through `deliverPacket`),
|
||||
* - `Hub` in `@snowluma/core` (the only place that turns a `Channel`
|
||||
* into a `ChannelCtx` and hands the ctx to `Core`),
|
||||
* - `Core` (only via the `ChannelCtx` projection; never holds a
|
||||
* Channel reference directly).
|
||||
*
|
||||
* OneBot and api modules NEVER import `ChannelInterface`; they consume
|
||||
* `CoreCtx` from `@snowluma/core`.
|
||||
*/
|
||||
export interface ChannelInterface {
|
||||
/** Transport family backing this channel. */
|
||||
readonly kind: ChannelKind;
|
||||
/** Stable, unique-per-live-channel id inside the `Hub`
|
||||
* (e.g. `'inject:3161592748'`). */
|
||||
readonly id: string;
|
||||
/** QQ number this transport carries. */
|
||||
readonly uin: string;
|
||||
|
||||
/** Wire-level send. The only escape hatch the apis layer eventually
|
||||
* routes through (via `Core.sendRawPacket` → `ChannelCtx.sendRawPacket`). */
|
||||
sendRawPacket(
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
): Promise<SendPacketResult>;
|
||||
|
||||
/** Subscribe to inbound packets. Called once by `Hub` (via
|
||||
* `ChannelCtx.onPacket`) when a `Core` is constructed on top of this
|
||||
* channel. Passing `null` detaches. */
|
||||
setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void;
|
||||
|
||||
/** Adapter-side hook: feed a freshly-received packet into the
|
||||
* current subscriber (if any). Called by `ChannelAdapter`s when
|
||||
* their underlying runtime delivers a frame. */
|
||||
deliverPacket(pkt: PacketInfo): void;
|
||||
|
||||
/** Release transport-side resources. Idempotent. */
|
||||
dispose(): void;
|
||||
}
|
||||
34
packages/channel/src/channel.ts
Normal file
34
packages/channel/src/channel.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type { ChannelInterface, ChannelKind } from './channel-interface';
|
||||
|
||||
export abstract class Channel implements ChannelInterface {
|
||||
abstract readonly kind: ChannelKind;
|
||||
abstract readonly id: string;
|
||||
abstract readonly uin: string;
|
||||
|
||||
abstract sendRawPacket(
|
||||
serviceCmd: string,
|
||||
body: Uint8Array,
|
||||
timeoutMs?: number,
|
||||
): Promise<SendPacketResult>;
|
||||
|
||||
private packetHandler_: ((pkt: PacketInfo) => void) | null = null;
|
||||
private disposed_ = false;
|
||||
|
||||
setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void {
|
||||
this.packetHandler_ = handler;
|
||||
}
|
||||
|
||||
deliverPacket(pkt: PacketInfo): void {
|
||||
this.packetHandler_?.(pkt);
|
||||
}
|
||||
|
||||
get isDisposed(): boolean { return this.disposed_; }
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed_) return;
|
||||
this.disposed_ = true;
|
||||
this.packetHandler_ = null;
|
||||
}
|
||||
}
|
||||
0
packages/channel/src/hub-events.ts
Normal file
0
packages/channel/src/hub-events.ts
Normal file
5
packages/channel/src/index.ts
Normal file
5
packages/channel/src/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export { type ChannelAdapter, type ChannelAdapterHost } from './adapter';
|
||||
export { Channel } from './channel';
|
||||
export { makeChannelCtx, type ChannelCtx } from './channel-ctx';
|
||||
export { type ChannelInterface, type ChannelKind } from './channel-interface';
|
||||
|
||||
16
packages/channel/tsconfig.json
Normal file
16
packages/channel/tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*",
|
||||
"tests"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
// Vitest config for @snowluma/common. Pure-TS package (no proton), so a
|
||||
// plain node-environment runner over tests/ is enough.
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
@@ -1,7 +1,6 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.13.0",
|
||||
"version": "1.9.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
@@ -16,18 +15,6 @@
|
||||
"types": "./src/logger.ts",
|
||||
"default": "./src/logger.ts"
|
||||
},
|
||||
"./coerce": {
|
||||
"types": "./src/coerce.ts",
|
||||
"default": "./src/coerce.ts"
|
||||
},
|
||||
"./single-flight-cache": {
|
||||
"types": "./src/single-flight-cache.ts",
|
||||
"default": "./src/single-flight-cache.ts"
|
||||
},
|
||||
"./concurrency": {
|
||||
"types": "./src/concurrency.ts",
|
||||
"default": "./src/concurrency.ts"
|
||||
},
|
||||
"./hex": {
|
||||
"types": "./src/hex.ts",
|
||||
"default": "./src/hex.ts"
|
||||
@@ -40,10 +27,6 @@
|
||||
"types": "./src/log-file-transport.ts",
|
||||
"default": "./src/log-file-transport.ts"
|
||||
},
|
||||
"./log-sanitize": {
|
||||
"types": "./src/log-sanitize.ts",
|
||||
"default": "./src/log-sanitize.ts"
|
||||
},
|
||||
"./log-summary": {
|
||||
"types": "./src/log-summary.ts",
|
||||
"default": "./src/log-summary.ts"
|
||||
@@ -59,19 +42,13 @@
|
||||
"./runtime": {
|
||||
"types": "./src/runtime.ts",
|
||||
"default": "./src/runtime.ts"
|
||||
},
|
||||
"./uin": {
|
||||
"types": "./src/uin.ts",
|
||||
"default": "./src/uin.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
// Scalar coercion primitives for normalizing untrusted JSON config into
|
||||
// typed values with fallbacks. Zero dependencies — these were duplicated
|
||||
// verbatim across notifications/config and webui/ui-config; this is their
|
||||
// single home. Input tolerance is deliberate (numeric strings coerce), but
|
||||
// validity is strict (a wrong type yields the caller's fallback, never a
|
||||
// silent 0/'' — except where the primitive's contract says otherwise).
|
||||
|
||||
/** True only for a plain, non-null, non-array object. */
|
||||
export function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/** The value when it is a real boolean, else the fallback. Strings/numbers
|
||||
* are NOT coerced — `'true'` and `1` both yield the fallback. */
|
||||
export function boolOr(value: unknown, fallback: boolean): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
/** A finite number (numeric strings coerced) clamped to `[min, max]`, else
|
||||
* the fallback. Fractional precision is preserved — use `clampInt` to floor. */
|
||||
export function clampNum(value: unknown, min: number, max: number, fallback: number): number {
|
||||
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
return Math.min(max, Math.max(min, n));
|
||||
}
|
||||
|
||||
/** `clampNum` truncated toward zero — clamp first, then drop the fraction. */
|
||||
export function clampInt(value: unknown, min: number, max: number, fallback: number): number {
|
||||
return Math.trunc(clampNum(value, min, max, fallback));
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
/**
|
||||
* Map `items` through `fn` in sequential batches of at most `concurrency`
|
||||
* items, awaiting each batch (`Promise.all`) before starting the next.
|
||||
* Results come back in input order.
|
||||
*
|
||||
* Batched, not a rolling pool: every item in a batch must settle before the
|
||||
* next batch starts. This caps peak parallelism — used to keep rate-limited
|
||||
* fan-out (e.g. the per-uin OIDB profile fetches during forward-node
|
||||
* enrichment) from bursting past a safe width and tripping Tencent
|
||||
* risk-control. Pair it with a cap on `items` (slice) and per-item error
|
||||
* handling inside `fn` for a fully bounded, best-effort enrichment — the
|
||||
* shape that was previously hand-rolled at each such call site.
|
||||
*/
|
||||
export async function mapWithConcurrency<T, R>(
|
||||
items: readonly T[],
|
||||
concurrency: number,
|
||||
fn: (item: T, index: number) => Promise<R>,
|
||||
): Promise<R[]> {
|
||||
const limit = Math.max(1, Math.trunc(concurrency));
|
||||
const results = new Array<R>(items.length);
|
||||
for (let i = 0; i < items.length; i += limit) {
|
||||
const batch = items.slice(i, i + limit);
|
||||
const settled = await Promise.all(batch.map((item, j) => fn(item, i + j)));
|
||||
for (let j = 0; j < settled.length; j++) results[i + j] = settled[j]!;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,81 +0,0 @@
|
||||
const ESC = 0x1b;
|
||||
const BEL = 0x07;
|
||||
const C1_CSI = 0x9b;
|
||||
const C1_ST = 0x9c;
|
||||
const C1_OSC = 0x9d;
|
||||
const C1_STRING_STARTERS = new Set([0x90, 0x98, 0x9e, 0x9f]);
|
||||
|
||||
function skipCsi(line: string, start: number): number {
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (code >= 0x40 && code <= 0x7e) return i + 1;
|
||||
}
|
||||
return line.length;
|
||||
}
|
||||
|
||||
function skipControlString(line: string, start: number, allowBell: boolean): number {
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (allowBell && code === BEL) return i + 1;
|
||||
if (code === C1_ST) return i + 1;
|
||||
if (code === ESC && line.charCodeAt(i + 1) === 0x5c) return i + 2;
|
||||
}
|
||||
return line.length;
|
||||
}
|
||||
|
||||
function skipEscSequence(line: string, start: number): number {
|
||||
if (start >= line.length) return line.length;
|
||||
|
||||
const first = line.charCodeAt(start);
|
||||
if (first === 0x5b) return skipCsi(line, start + 1);
|
||||
if (first === 0x5d) return skipControlString(line, start + 1, true);
|
||||
if (first === 0x50 || first === 0x58 || first === 0x5e || first === 0x5f) {
|
||||
return skipControlString(line, start + 1, false);
|
||||
}
|
||||
|
||||
let i = start;
|
||||
while (i < line.length) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (code < 0x20 || code > 0x2f) break;
|
||||
i += 1;
|
||||
}
|
||||
const final = line.charCodeAt(i);
|
||||
return final >= 0x30 && final <= 0x7e ? i + 1 : start;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove terminal presentation and control sequences from a log line.
|
||||
*
|
||||
* The parser handles both seven-bit ESC forms and eight-bit C1 forms,
|
||||
* including CSI styling, OSC hyperlinks, and DCS/SOS/PM/APC control strings.
|
||||
* TAB and LF remain available for formatted records such as stack traces.
|
||||
* Unterminated terminal strings consume the remainder instead of leaking their
|
||||
* invisible payload into persisted or downloaded logs.
|
||||
*/
|
||||
export function sanitizeLogLine(line: string): string {
|
||||
let plain = '';
|
||||
for (let i = 0; i < line.length;) {
|
||||
const code = line.charCodeAt(i);
|
||||
|
||||
if (code === ESC) {
|
||||
i = skipEscSequence(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
if (code === C1_CSI) {
|
||||
i = skipCsi(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
|
||||
i = skipControlString(line, i + 1, code === C1_OSC);
|
||||
continue;
|
||||
}
|
||||
if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
plain += line[i];
|
||||
i += 1;
|
||||
}
|
||||
return plain;
|
||||
}
|
||||
@@ -1,39 +1,7 @@
|
||||
const MAX_FIELD = 40;
|
||||
const MAX_TOTAL = 200;
|
||||
const SENSITIVE_SEGMENTS = new Set([
|
||||
'authorization',
|
||||
'cookie',
|
||||
'credential',
|
||||
'credentials',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
]);
|
||||
|
||||
function isSensitiveKey(key: string): boolean {
|
||||
const segments = key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
|
||||
return segments.some((segment, index) => {
|
||||
if (SENSITIVE_SEGMENTS.has(segment)) return true;
|
||||
const next = segments[index + 1];
|
||||
return next === 'key' && (
|
||||
segment === 'api'
|
||||
|| segment === 'private'
|
||||
|| segment === 'session'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function valueRepr(v: unknown, key?: string): string {
|
||||
if (key !== undefined && isSensitiveKey(key)) return '"***"';
|
||||
function valueRepr(v: unknown): string {
|
||||
if (v === null) return 'null';
|
||||
if (v === undefined) return 'undefined';
|
||||
switch (typeof v) {
|
||||
@@ -63,251 +31,21 @@ export function summarizeParams(params: unknown): string {
|
||||
if (params === null || params === undefined) return '{}';
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL
|
||||
? `${s.slice(0, MAX_TOTAL - 3)}...`
|
||||
: s;
|
||||
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s;
|
||||
}
|
||||
if (Array.isArray(params)) return `[len=${params.length}]`;
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v, k)}`;
|
||||
const separatorLength = out.length > 0 ? 1 : 0;
|
||||
if (total + separatorLength + entry.length > MAX_TOTAL) {
|
||||
if (out.length === 0) {
|
||||
return `${entry.slice(0, MAX_TOTAL - 3)}...`;
|
||||
}
|
||||
|
||||
const rendered = out.join(' ');
|
||||
return rendered.length + 4 <= MAX_TOTAL
|
||||
? `${rendered} ...`
|
||||
: `${rendered.slice(0, MAX_TOTAL - 3)}...`;
|
||||
const entry = `${k}=${valueRepr(v)}`;
|
||||
// +1 accounts for the separating space we'd insert when joining.
|
||||
if (total > 0 && total + entry.length + 1 > MAX_TOTAL) {
|
||||
out.push('...');
|
||||
break;
|
||||
}
|
||||
out.push(entry);
|
||||
total += separatorLength + entry.length;
|
||||
total += entry.length + (out.length > 1 ? 1 : 0);
|
||||
}
|
||||
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 AUTHORIZATION_BOUNDARY_SEGMENTS = new Set([
|
||||
'authorization',
|
||||
'cookie',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
]);
|
||||
|
||||
function keySegments(key: string): string[] {
|
||||
return key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
}
|
||||
|
||||
function isKeyKind(key: string, kind: 'authorization' | 'cookie'): boolean {
|
||||
return keySegments(key).includes(kind);
|
||||
}
|
||||
|
||||
function isAuthorizationBoundaryKey(key: string): boolean {
|
||||
const segments = keySegments(key);
|
||||
return segments.some((segment, index) => {
|
||||
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) return true;
|
||||
const next = segments[index + 1];
|
||||
return next === 'key' && (
|
||||
segment === 'api'
|
||||
|| segment === 'private'
|
||||
|| segment === 'session'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function quotedValueEnd(message: string, start: number): number | undefined {
|
||||
const quote = message[start];
|
||||
if (quote !== '"' && quote !== "'") return undefined;
|
||||
|
||||
for (let index = start + 1; index < message.length; index += 1) {
|
||||
if (message[index] === '\\') {
|
||||
index += 1;
|
||||
} else if (message[index] === quote) {
|
||||
return index + 1;
|
||||
}
|
||||
}
|
||||
return message.length;
|
||||
}
|
||||
|
||||
function cookieValueEnd(message: string, start: number): number {
|
||||
const initialQuotedEnd = quotedValueEnd(message, start);
|
||||
let end: number;
|
||||
if (initialQuotedEnd !== undefined) {
|
||||
end = initialQuotedEnd;
|
||||
} else {
|
||||
end = start;
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
}
|
||||
|
||||
while (end < message.length) {
|
||||
let semicolon: number = end;
|
||||
while (message[semicolon] === ' ' || message[semicolon] === '\t') {
|
||||
semicolon += 1;
|
||||
}
|
||||
if (message[semicolon] !== ';') break;
|
||||
|
||||
let nameStart = semicolon + 1;
|
||||
while (message[nameStart] === ' ' || message[nameStart] === '\t') {
|
||||
nameStart += 1;
|
||||
}
|
||||
let nameEnd = nameStart;
|
||||
while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) nameEnd += 1;
|
||||
if (nameEnd === nameStart) break;
|
||||
|
||||
end = nameEnd;
|
||||
if (message[end] !== '=') continue;
|
||||
|
||||
const attribute = message.slice(nameStart, nameEnd).toLowerCase();
|
||||
const valueStart = end + 1;
|
||||
const quotedEnd = quotedValueEnd(message, valueStart);
|
||||
if (quotedEnd !== undefined) {
|
||||
end = quotedEnd;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attribute !== 'expires') {
|
||||
end = valueStart;
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
end = valueStart;
|
||||
while (end < message.length && !/[;}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
assignments.lastIndex = valueStart;
|
||||
const nextField = assignments.exec(message);
|
||||
if (nextField && nextField.index < end) end = nextField.index;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
function genericValueEnd(message: string, start: number): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
if (quotedEnd !== undefined) return quotedEnd;
|
||||
|
||||
let end = start;
|
||||
while (end < message.length && !/[\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
function authorizationValueEnd(
|
||||
message: string,
|
||||
start: number,
|
||||
query: boolean,
|
||||
): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
if (quotedEnd !== undefined) return quotedEnd;
|
||||
|
||||
if (query) {
|
||||
const queryEnd = message.indexOf('&', start);
|
||||
return queryEnd >= 0 ? queryEnd : message.length;
|
||||
}
|
||||
|
||||
let end = message.length;
|
||||
const structural = message.slice(start).search(/[\r\n}\]]/);
|
||||
if (structural >= 0) end = start + structural;
|
||||
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
const remaining = message.slice(start, end);
|
||||
for (let match = assignments.exec(remaining); match; match = assignments.exec(remaining)) {
|
||||
if (isAuthorizationBoundaryKey(match[3]!)) {
|
||||
end = start + match.index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
/** Redact explicit authentication assignments in ordinary formatted logs. */
|
||||
export function redactLogMessage(message: string): string {
|
||||
let out = '';
|
||||
let cursor = 0;
|
||||
ASSIGNMENT_START.lastIndex = 0;
|
||||
|
||||
for (let match = ASSIGNMENT_START.exec(message); match; match = ASSIGNMENT_START.exec(message)) {
|
||||
const key = match[3]!;
|
||||
if (!isSensitiveKey(key)) {
|
||||
ASSIGNMENT_START.lastIndex = Math.max(
|
||||
match.index + 1,
|
||||
ASSIGNMENT_START.lastIndex - 1,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const valueStart = ASSIGNMENT_START.lastIndex;
|
||||
const valueEnd = isKeyKind(key, 'authorization')
|
||||
? authorizationValueEnd(
|
||||
message,
|
||||
valueStart,
|
||||
match[1] === '?' || match[1] === '&',
|
||||
)
|
||||
: isKeyKind(key, 'cookie')
|
||||
? cookieValueEnd(message, valueStart)
|
||||
: genericValueEnd(message, valueStart);
|
||||
|
||||
out += message.slice(cursor, valueStart) + '***';
|
||||
cursor = valueEnd;
|
||||
ASSIGNMENT_START.lastIndex = valueEnd;
|
||||
}
|
||||
|
||||
return out + message.slice(cursor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lossless nested renderer for explicit TRACE diagnostics. TRACE is an
|
||||
* operator-enabled, memory-only mode and intentionally leaves values
|
||||
* unredacted so a reproduction contains the complete business input.
|
||||
*/
|
||||
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';
|
||||
|
||||
switch (typeof value) {
|
||||
case 'string':
|
||||
return JSON.stringify(value);
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(value);
|
||||
case 'object': {
|
||||
if (seen.has(value as object)) return '"[circular]"';
|
||||
seen.add(value as object);
|
||||
const out = Array.isArray(value)
|
||||
? `[${value.map((item) => walk(item)).join(',')}]`
|
||||
: `{${Object.entries(value as Record<string, unknown>)
|
||||
.map(([key, item]) => `${key}:${walk(item)}`)
|
||||
.join(',')}}`;
|
||||
seen.delete(value as object);
|
||||
return out;
|
||||
}
|
||||
default:
|
||||
return typeof value;
|
||||
}
|
||||
};
|
||||
|
||||
return walk(params);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
import { redactLogMessage } from './log-summary';
|
||||
import { sanitizeLogLine } from './log-sanitize';
|
||||
import {
|
||||
currentRequestId,
|
||||
nextRequestId,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
} from './request-context';
|
||||
|
||||
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
type FileLogLevel = Exclude<LogLevel, 'trace'>;
|
||||
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
@@ -19,8 +10,6 @@ export interface LogEntry {
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
/** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */
|
||||
req?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
@@ -37,7 +26,6 @@ interface LogOptions {
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
@@ -46,7 +34,6 @@ const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
};
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
@@ -55,7 +42,6 @@ const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
};
|
||||
|
||||
const COLOR_CODE: Record<LogLevel, number> = {
|
||||
trace: 90,
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
@@ -67,102 +53,39 @@ const COLOR_SCOPE = 35;
|
||||
const COLOR_DIM = 2;
|
||||
const COLOR_RESET = '\x1b[0m';
|
||||
const MAX_LOG_ENTRIES = 1000;
|
||||
|
||||
/** Trace ring cap — env-tunable since trace is the high-volume stream. */
|
||||
function resolveTraceBufferMax(): number {
|
||||
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
|
||||
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
|
||||
}
|
||||
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
|
||||
/**
|
||||
* Fixed-capacity circular buffer. O(1) push + eviction (no array `.shift()`),
|
||||
* so the high-throughput trace stream never pays an O(n) shift per overflow.
|
||||
*/
|
||||
class RingBuffer<T> {
|
||||
private readonly buf: (T | undefined)[];
|
||||
private start = 0;
|
||||
private count = 0;
|
||||
constructor(private readonly cap: number) {
|
||||
this.buf = new Array<T | undefined>(cap);
|
||||
}
|
||||
push(item: T): void {
|
||||
const end = (this.start + this.count) % this.cap;
|
||||
this.buf[end] = item;
|
||||
if (this.count < this.cap) this.count += 1;
|
||||
else this.start = (this.start + 1) % this.cap; // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!;
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
return this.recent(this.count);
|
||||
}
|
||||
get size(): number {
|
||||
return this.count;
|
||||
}
|
||||
}
|
||||
|
||||
const logRing = new RingBuffer<LogEntry>(MAX_LOG_ENTRIES);
|
||||
const traceRing = new RingBuffer<LogEntry>(TRACE_BUFFER_MAX);
|
||||
const logEntries: LogEntry[] = [];
|
||||
const logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
return raw;
|
||||
}
|
||||
return 'info';
|
||||
}
|
||||
|
||||
function resolveFileMinLevel(): FileLogLevel {
|
||||
const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
if (raw === undefined || raw.trim() === '') return 'debug';
|
||||
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === 'debug' || normalized === 'info' || normalized === 'success' ||
|
||||
normalized === 'warn' || normalized === 'error') {
|
||||
return normalized;
|
||||
}
|
||||
throw new TypeError(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
}
|
||||
|
||||
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
|
||||
// setLogLevel() lets WebUI / SDK callers flip it without a restart.
|
||||
// Only governs console + ring buffer + subscribers;
|
||||
// the file transport level is seeded independently from
|
||||
// SNOWLUMA_LOG_FILE_LEVEL (default debug)
|
||||
// and is not affected by setLogLevel().
|
||||
// Only governs console + ring buffer + subscribers; the file
|
||||
// transport always sees debug-and-up regardless.
|
||||
let currentLevel: LogLevel = resolveMinLevel();
|
||||
const currentFileLevel: FileLogLevel = resolveFileMinLevel();
|
||||
|
||||
function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
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[] = ['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.
|
||||
|
||||
/**
|
||||
* Change the console / subscriber level at runtime. Invalid input is
|
||||
* a no-op (returns false). File transport is unaffected — it always
|
||||
* sees every level so post-mortems remain useful.
|
||||
*/
|
||||
export function setLogLevel(level: string): boolean {
|
||||
const lower = String(level).toLowerCase();
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
|
||||
@@ -187,15 +110,15 @@ function currentTime(): string {
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function render(level: LogLevel, options: LogOptions, message: string, reqId?: number): string {
|
||||
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
|
||||
const message = format(...args);
|
||||
const ts = currentTime();
|
||||
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
|
||||
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
|
||||
const reqTag = reqId !== undefined ? `[req#${reqId}]` : '';
|
||||
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
@@ -203,60 +126,31 @@ function render(level: LogLevel, options: LogOptions, message: string, reqId?: n
|
||||
// Pad first, then color only the visible tag so escape codes don't eat
|
||||
// into the alignment width.
|
||||
const cUin = uinTag
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
|
||||
}
|
||||
|
||||
function emit(
|
||||
level: LogLevel,
|
||||
options: LogOptions,
|
||||
args: unknown[],
|
||||
forceInitialCredentials = false,
|
||||
): void {
|
||||
// Console / subscriber and file filters are independent. If no destination
|
||||
// accepts the record, stop before formatting or building a LogEntry.
|
||||
const passesConsole = forceInitialCredentials || shouldLog(level);
|
||||
const passesFile = level !== 'trace'
|
||||
&& (forceInitialCredentials || 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;
|
||||
|
||||
// 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' || forceInitialCredentials
|
||||
? formattedMessage
|
||||
: redactLogMessage(formattedMessage);
|
||||
const line = render(level, options, message, reqId);
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
// Console / subscriber level filter. File output is debug-and-up always;
|
||||
// see log-file-transport.ts.
|
||||
const passesConsole = shouldLog(level);
|
||||
const message = format(...args);
|
||||
const line = render(level, options, args);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line: sanitizeLogLine(line),
|
||||
line,
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
logEntries.push(entry);
|
||||
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
|
||||
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
|
||||
@@ -268,13 +162,10 @@ function emit(
|
||||
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
// File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL,
|
||||
// default debug). `trace` is memory / WebUI only (omitted here to avoid huge
|
||||
// on-disk volume). ANSI stripping happens inside the transport. UIN routes
|
||||
// the line to its per-account sub-file in addition to the shared one.
|
||||
if (passesFile) {
|
||||
getFileTransport().write(line, options.uin);
|
||||
}
|
||||
// File transport always sees every level (debug-and-up) for post-mortem
|
||||
// value; ANSI stripping happens inside the transport. UIN routes the
|
||||
// line to its per-account sub-file in addition to the shared one.
|
||||
getFileTransport().write(line, options.uin);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -287,19 +178,9 @@ export function closeLogger(): Promise<void> {
|
||||
return getFileTransport().close();
|
||||
}
|
||||
|
||||
function mergeLogRings(): LogEntry[] {
|
||||
return traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
}
|
||||
|
||||
export function getLogSnapshot(): LogEntry[] {
|
||||
return mergeLogRings();
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.trunc(limit));
|
||||
return mergeLogRings().slice(-n);
|
||||
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
|
||||
return logEntries.slice(-n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
@@ -310,13 +191,6 @@ export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
/**
|
||||
* High-volume, memory-only diagnostic level (never written to disk). Pass a
|
||||
* lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the
|
||||
* arguments (and any costly rendering) are built only when trace is active.
|
||||
* A plain `trace('msg', x)` works too but evaluates its args eagerly.
|
||||
*/
|
||||
trace: (...args: unknown[]) => void;
|
||||
debug: (...args: unknown[]) => void;
|
||||
info: (...args: unknown[]) => void;
|
||||
success: (...args: unknown[]) => void;
|
||||
@@ -333,7 +207,6 @@ export interface Logger {
|
||||
|
||||
function makeLogger(opts: LogOptions): Logger {
|
||||
return {
|
||||
trace: (...args: unknown[]) => emit('trace', opts, args),
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
@@ -353,26 +226,3 @@ function makeLogger(opts: LogOptions): Logger {
|
||||
export function createLogger(scope: string): Logger {
|
||||
return makeLogger({ scope });
|
||||
}
|
||||
|
||||
export function renderTraceBytes(body: Uint8Array): string {
|
||||
return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('hex');
|
||||
}
|
||||
|
||||
export function runWithTraceRequest<T>(fn: () => T): T {
|
||||
if (currentRequestId() !== undefined || currentLevel !== 'trace') return fn();
|
||||
return runWithRequestId(nextRequestId(), fn);
|
||||
}
|
||||
|
||||
export function logInitialWebuiCredentials(password: string): void {
|
||||
emit(
|
||||
'info',
|
||||
{ scope: 'WebUI' },
|
||||
['initial credentials: user=admin password=%s', password],
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
// Request-correlation primitives remain available for callers that already own
|
||||
// an explicit request id. New semantic entrypoints should prefer
|
||||
// runWithTraceRequest() so disabled TRACE does not allocate one.
|
||||
export { nextRequestId, runWithoutRequestContext, runWithRequestId, currentRequestId };
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
|
||||
interface RequestStore {
|
||||
id: number;
|
||||
}
|
||||
|
||||
const storage = new AsyncLocalStorage<RequestStore | undefined>();
|
||||
let counter = 0;
|
||||
|
||||
/**
|
||||
* Allocate the next per-process request id (monotonic). Wraps via uint32 so
|
||||
* it never overflows to a non-integer; `0` is skipped so "no id" stays
|
||||
* unambiguous.
|
||||
*/
|
||||
export function nextRequestId(): number {
|
||||
counter = (counter + 1) >>> 0;
|
||||
if (counter === 0) counter = 1;
|
||||
return counter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `fn` with `id` bound as the ambient request id for the entire async
|
||||
* chain it spawns. Any logger call anywhere in that chain — across packages,
|
||||
* across awaits — picks it up via {@link currentRequestId} with no signature
|
||||
* threading. Used by the OneBot action handler to correlate a request's whole
|
||||
* journey (entry → outbound packets → exit) under one `[req#N]` tag.
|
||||
*/
|
||||
export function runWithRequestId<T>(id: number, fn: () => T): T {
|
||||
return storage.run({ id }, fn);
|
||||
}
|
||||
|
||||
/** Run `fn` without inheriting an ambient request id. */
|
||||
export function runWithoutRequestContext<T>(fn: () => T): T {
|
||||
return storage.run(undefined, fn);
|
||||
}
|
||||
|
||||
/** The request id bound to the current async context, or undefined outside one. */
|
||||
export function currentRequestId(): number | undefined {
|
||||
return storage.getStore()?.id;
|
||||
}
|
||||
@@ -7,195 +7,52 @@ export interface RuntimeConfig {
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
* Defaults to false; the Docker image flips it on in supervisord.conf. */
|
||||
hookAutoLoad?: boolean;
|
||||
/** WebUI listener bind address. '0.0.0.0' = all interfaces (default),
|
||||
* '127.0.0.1' = localhost-only. Listener-level: change needs a restart. */
|
||||
webuiHost?: string;
|
||||
/** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this
|
||||
* only flips serving on/off. Listener-level: change needs a restart. */
|
||||
webuiTls?: { enabled?: boolean };
|
||||
/** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY),
|
||||
* consumed by the WebUI's client-ip resolver. '' = trust nobody. */
|
||||
trustProxy?: string;
|
||||
/** Aggregate cap for every managed file below the log root. */
|
||||
logMaxTotalMb?: number;
|
||||
/** Calendar-day retention. Zero disables date-based deletion. */
|
||||
logRetainDays?: number;
|
||||
/** Duplicate UIN-scoped lines into logs/<uin>/ in addition to the shared log. */
|
||||
logPerUin?: boolean;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||
|
||||
const DEFAULT_WEBUI_PORT = 5099;
|
||||
const DEFAULT_WEBUI_HOST = '0.0.0.0';
|
||||
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),
|
||||
);
|
||||
|
||||
/**
|
||||
* Pure on-disk-object → typed config normalization (defaults + validation,
|
||||
* no fs / no env). Exported for testing; `loadRuntimeConfig` wraps it.
|
||||
*/
|
||||
export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
const obj = isObject(parsed) ? parsed : {};
|
||||
return {
|
||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||
webuiHost: normalizeHost(obj.webuiHost),
|
||||
webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false },
|
||||
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
|
||||
logMaxTotalMb: normalizeRequiredInteger(
|
||||
obj.logMaxTotalMb,
|
||||
DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'logMaxTotalMb',
|
||||
),
|
||||
logRetainDays: normalizeRequiredInteger(
|
||||
obj.logRetainDays,
|
||||
DEFAULT_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'logRetainDays',
|
||||
),
|
||||
logPerUin: normalizeRequiredBool(obj.logPerUin, DEFAULT_LOG_PER_UIN, 'logPerUin'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure SNOWLUMA_* env → override patch (no fs). Env wins over runtime.json
|
||||
* (a trusted launcher like SnowLumaDesktop pins these per-launch without
|
||||
* rewriting the file). Absent vars produce no key.
|
||||
*/
|
||||
export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<RuntimeConfig> {
|
||||
const out: Partial<RuntimeConfig> = {};
|
||||
|
||||
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
|
||||
if (port !== undefined) out.webuiPort = port;
|
||||
|
||||
const host = env.SNOWLUMA_WEBUI_HOST;
|
||||
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;
|
||||
|
||||
const logMaxTotalMb = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'SNOWLUMA_LOG_MAX_TOTAL_MB',
|
||||
);
|
||||
if (logMaxTotalMb !== undefined) out.logMaxTotalMb = logMaxTotalMb;
|
||||
|
||||
const logRetainDays = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
);
|
||||
if (logRetainDays !== undefined) out.logRetainDays = logRetainDays;
|
||||
|
||||
const logPerUin = parseRequiredBoolEnv(
|
||||
env.SNOWLUMA_LOG_PER_UIN,
|
||||
'SNOWLUMA_LOG_PER_UIN',
|
||||
);
|
||||
if (logPerUin !== undefined) out.logPerUin = logPerUin;
|
||||
|
||||
return out;
|
||||
}
|
||||
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
};
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
|
||||
const parsed = tryLoadRuntimeConfig();
|
||||
const normalized = normalizeRuntimeConfig(parsed ?? {});
|
||||
|
||||
// Persist when the file is absent or when normalization changed/backfilled
|
||||
// anything (e.g. an older runtime.json lacking webuiHost/webuiTls).
|
||||
if (parsed === null || !sameRuntimeConfig(parsed, normalized)) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
|
||||
// Env overrides apply in-memory only — never written back to disk.
|
||||
return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the persisted config (normalized, no env overrides, no write). For the
|
||||
* settings panel's GET — shows what's actually saved/editable on disk.
|
||||
*/
|
||||
export function readRuntimeConfig(): RuntimeConfig {
|
||||
return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a partial update. Merges onto the ON-DISK config (not the env-merged
|
||||
* runtime view) so an env override (e.g. SNOWLUMA_WEBUI_PORT) is never baked
|
||||
* into runtime.json. Returns the new persisted config (without env overrides).
|
||||
*/
|
||||
export function updateRuntimeConfig(patch: Partial<RuntimeConfig>): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
const onDisk = normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
const next = normalizeRuntimeConfig({ ...onDisk, ...patch });
|
||||
saveRuntimeConfig(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): Record<string, unknown> | null {
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`;
|
||||
try {
|
||||
fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH);
|
||||
} catch (error) {
|
||||
try {
|
||||
fs.unlinkSync(temporaryPath);
|
||||
} catch (cleanupError) {
|
||||
if (!isErrnoCode(cleanupError, 'ENOENT')) {
|
||||
throw new AggregateError(
|
||||
[error, cleanupError],
|
||||
'failed to persist runtime config and remove its temporary file',
|
||||
);
|
||||
}
|
||||
const loaded = tryLoadRuntimeConfig();
|
||||
let normalized: RuntimeConfig;
|
||||
if (!loaded) {
|
||||
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
|
||||
normalized = { ...DEFAULT_RUNTIME_CONFIG };
|
||||
} else {
|
||||
normalized = {
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
|
||||
};
|
||||
if (
|
||||
normalized.webuiPort !== loaded.webuiPort
|
||||
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
|
||||
) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without
|
||||
// rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop)
|
||||
// pick a free port per-launch while CLI/Docker users continue to drive
|
||||
// it from runtime.json.
|
||||
const envPort = envPortOverride();
|
||||
if (envPort !== undefined) {
|
||||
normalized = { ...normalized, webuiPort: envPort };
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/** True when the raw on-disk object already matches the normalized config
|
||||
* on every known field (so we can skip a needless rewrite). */
|
||||
function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): boolean {
|
||||
const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined;
|
||||
return (
|
||||
parsed.webuiPort === n.webuiPort
|
||||
&& parsed.hookAutoLoad === n.hookAutoLoad
|
||||
&& parsed.webuiHost === n.webuiHost
|
||||
&& parsedTls === n.webuiTls?.enabled
|
||||
&& parsed.trustProxy === n.trustProxy
|
||||
&& parsed.logMaxTotalMb === n.logMaxTotalMb
|
||||
&& parsed.logRetainDays === n.logRetainDays
|
||||
&& parsed.logPerUin === n.logPerUin
|
||||
);
|
||||
}
|
||||
|
||||
function parsePortString(raw: unknown): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
function envPortOverride(): number | undefined {
|
||||
const raw = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
if (!raw || typeof raw !== 'string') return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
@@ -203,9 +60,25 @@ function parsePortString(raw: unknown): number | undefined {
|
||||
return port;
|
||||
}
|
||||
|
||||
function normalizeHost(value: unknown): string {
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
return DEFAULT_WEBUI_HOST;
|
||||
function tryLoadRuntimeConfig(): RuntimeConfig | null {
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!isObject(parsed)) return null;
|
||||
|
||||
return {
|
||||
webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(parsed.hookAutoLoad, false),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
function normalizePort(value: unknown, fallback: number): number {
|
||||
@@ -224,37 +97,6 @@ function normalizePort(value: unknown, fallback: number): number {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function normalizeRequiredInteger(
|
||||
value: unknown,
|
||||
fallback: number,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
): number {
|
||||
if (value === undefined) return fallback;
|
||||
const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
|
||||
if (
|
||||
typeof n === 'number'
|
||||
&& Number.isSafeInteger(n)
|
||||
&& n >= min
|
||||
&& n <= max
|
||||
) {
|
||||
return n;
|
||||
}
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
}
|
||||
|
||||
function normalizeRequiredBool(
|
||||
value: unknown,
|
||||
fallback: boolean,
|
||||
field: string,
|
||||
): boolean {
|
||||
if (value === undefined) return fallback;
|
||||
const parsed = parseBoolValue(value);
|
||||
if (parsed !== undefined) return parsed;
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
}
|
||||
|
||||
function normalizeBool(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'number') return value !== 0;
|
||||
@@ -266,40 +108,6 @@ function normalizeBool(value: unknown, fallback: boolean): boolean {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function parseRequiredIntegerEnv(
|
||||
raw: unknown,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (Number.isSafeInteger(n) && n >= min && n <= max) return n;
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
}
|
||||
|
||||
function parseRequiredBoolEnv(raw: unknown, field: string): boolean | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const parsed = parseBoolValue(raw);
|
||||
if (parsed !== undefined) return parsed;
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
}
|
||||
|
||||
function parseBoolValue(raw: unknown): boolean | undefined {
|
||||
if (typeof raw === 'boolean') return raw;
|
||||
if (raw === 1) return true;
|
||||
if (raw === 0) return false;
|
||||
if (typeof raw !== 'string') return undefined;
|
||||
const value = raw.trim().toLowerCase();
|
||||
if (value === 'true' || value === '1' || value === 'yes' || value === 'on') return true;
|
||||
if (value === 'false' || value === '0' || value === 'no' || value === 'off') return false;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isErrnoCode(error: unknown, code: string): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === code;
|
||||
}
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
/**
|
||||
* Single-flight + TTL memoization.
|
||||
*
|
||||
* Concentrates the "don't refetch what's fresh, and don't stampede the same
|
||||
* key with concurrent loads" pattern that was hand-rolled (slightly
|
||||
* differently each time) across the codebase — e.g. `ContactsApi`'s group
|
||||
* member-list cache and the WebUI update-check. Each copy re-implemented the
|
||||
* same fiddly trio: a TTL freshness check, an in-flight promise map to
|
||||
* de-dupe concurrent callers, and `finally`-cleanup of that map. Getting any
|
||||
* of the three subtly wrong (forgetting the `finally`, caching an error,
|
||||
* racing the timestamp) is a real hazard — so it lives in one place.
|
||||
*
|
||||
* The underlying concern is Tencent risk-control: a busy OneBot client can
|
||||
* fan out one uncached OIDB fetch per inbound message, and sustained bursts
|
||||
* trip a ban. TTL + single-flight collapse that fan-out.
|
||||
*/
|
||||
|
||||
export interface SingleFlightCacheOptions<K, V> {
|
||||
/** Freshness window in ms. A cached entry older than this is reloaded. */
|
||||
ttlMs: number;
|
||||
/** Load the value for a key. Rejections propagate and are never cached. */
|
||||
load: (key: K) => Promise<V>;
|
||||
/**
|
||||
* Decide whether a resolved value should be cached. Default: always.
|
||||
* Return `false` to leave an entry uncached (e.g. an error-shaped result the
|
||||
* next call should retry) while still de-duping concurrent in-flight callers.
|
||||
*/
|
||||
shouldCache?: (value: V) => boolean;
|
||||
/** Clock, injectable for tests. Defaults to `Date.now`. */
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export class SingleFlightCache<K, V> {
|
||||
private readonly ttlMs: number;
|
||||
private readonly load: (key: K) => Promise<V>;
|
||||
private readonly shouldCache: (value: V) => boolean;
|
||||
private readonly now: () => number;
|
||||
private readonly fresh = new Map<K, { at: number; value: V }>();
|
||||
private readonly inflight = new Map<K, Promise<V>>();
|
||||
|
||||
constructor(opts: SingleFlightCacheOptions<K, V>) {
|
||||
this.ttlMs = opts.ttlMs;
|
||||
this.load = opts.load;
|
||||
this.shouldCache = opts.shouldCache ?? (() => true);
|
||||
this.now = opts.now ?? Date.now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value for `key`.
|
||||
*
|
||||
* - Returns a fresh cached value when the last load was within `ttlMs`.
|
||||
* - Otherwise de-dupes concurrent callers onto a single `load()` and caches
|
||||
* the result (subject to `shouldCache`). A rejected `load` propagates to
|
||||
* every joined caller, clears the in-flight slot, and is not cached.
|
||||
* - `force` bypasses the freshness check but still joins an in-flight load
|
||||
* rather than starting a second one.
|
||||
*/
|
||||
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
|
||||
if (!opts.force) {
|
||||
const hit = this.fresh.get(key);
|
||||
if (hit && this.now() - hit.at < this.ttlMs) return Promise.resolve(hit.value);
|
||||
}
|
||||
const existing = this.inflight.get(key);
|
||||
if (existing) return existing;
|
||||
const task = (async () => {
|
||||
try {
|
||||
const value = await this.load(key);
|
||||
if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value });
|
||||
return value;
|
||||
} finally {
|
||||
this.inflight.delete(key);
|
||||
}
|
||||
})();
|
||||
this.inflight.set(key, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
/** Drop a cached entry. Does not abort an in-flight load. */
|
||||
invalidate(key: K): void {
|
||||
this.fresh.delete(key);
|
||||
}
|
||||
|
||||
/** Drop all cached entries. Does not abort in-flight loads. */
|
||||
clear(): void {
|
||||
this.fresh.clear();
|
||||
}
|
||||
}
|
||||
|
||||
export function createSingleFlightCache<K, V>(
|
||||
opts: SingleFlightCacheOptions<K, V>,
|
||||
): SingleFlightCache<K, V> {
|
||||
return new SingleFlightCache(opts);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Shared QQ UIN validity check. A "real" UIN is a live QQ account number, not
|
||||
// a garbage value the native hook can emit during the probe→inject race — e.g.
|
||||
// a 13-digit millisecond timestamp read from not-yet-populated QQ memory
|
||||
// (issue #162). No real QQ UIN exceeds 10 digits (they fit in uint32, max
|
||||
// 4294967295), so a pure digit string of 5..10 chars is the accept window.
|
||||
//
|
||||
// Callers rely on a `true` result guaranteeing a BigInt()-safe pure-digit
|
||||
// string. Keep that contract if the pattern ever changes.
|
||||
export function isRealUin(uin: string): boolean {
|
||||
return /^\d{5,10}$/.test(uin);
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { isObject, boolOr, clampNum, clampInt } from '../src/coerce';
|
||||
|
||||
describe('isObject', () => {
|
||||
it('is true only for plain non-null non-array objects', () => {
|
||||
expect(isObject({})).toBe(true);
|
||||
expect(isObject({ a: 1 })).toBe(true);
|
||||
expect(isObject(null)).toBe(false);
|
||||
expect(isObject([])).toBe(false);
|
||||
expect(isObject('x')).toBe(false);
|
||||
expect(isObject(42)).toBe(false);
|
||||
expect(isObject(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('boolOr', () => {
|
||||
it('returns the value only when it is a real boolean, else the fallback', () => {
|
||||
expect(boolOr(true, false)).toBe(true);
|
||||
expect(boolOr(false, true)).toBe(false);
|
||||
expect(boolOr('true', false)).toBe(false); // strings are NOT coerced
|
||||
expect(boolOr(1, false)).toBe(false);
|
||||
expect(boolOr(undefined, true)).toBe(true);
|
||||
expect(boolOr(null, true)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clampNum', () => {
|
||||
it('passes finite numbers through, clamped to [min,max]', () => {
|
||||
expect(clampNum(5, 0, 10, -1)).toBe(5);
|
||||
expect(clampNum(-3, 0, 10, -1)).toBe(0); // below min
|
||||
expect(clampNum(99, 0, 10, -1)).toBe(10); // above max
|
||||
});
|
||||
|
||||
it('coerces numeric strings', () => {
|
||||
expect(clampNum('7', 0, 10, -1)).toBe(7);
|
||||
expect(clampNum('7.5', 0, 10, -1)).toBe(7.5); // NOT truncated (that is clampInt)
|
||||
});
|
||||
|
||||
it('falls back on non-finite / non-numeric input', () => {
|
||||
expect(clampNum('abc', 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(NaN, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(Infinity, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(undefined, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(null, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum({}, 0, 10, 3)).toBe(3);
|
||||
});
|
||||
|
||||
it('preserves fractional precision within bounds', () => {
|
||||
expect(clampNum(0.42, 0, 1, 0)).toBe(0.42);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clampInt', () => {
|
||||
it('is clampNum truncated toward zero', () => {
|
||||
expect(clampInt(7.9, 0, 10, -1)).toBe(7);
|
||||
expect(clampInt('7.9', 0, 10, -1)).toBe(7);
|
||||
expect(clampInt(5, 0, 10, -1)).toBe(5);
|
||||
});
|
||||
|
||||
it('clamps before truncating', () => {
|
||||
expect(clampInt(99.9, 0, 10, -1)).toBe(10);
|
||||
expect(clampInt(-3.5, 0, 10, -1)).toBe(0);
|
||||
});
|
||||
|
||||
it('clamp-then-trunc ordering: a fractional lower bound is crossed by the clamp, not the trunc', () => {
|
||||
// Distinguishes clamp→trunc (this contract) from trunc→clamp: input 2.4
|
||||
// with min 2.5 → clamp lifts to 2.5, then trunc → 2. A trunc-first impl
|
||||
// would floor to 2 then clamp up to 2.5. Pins the order for the shared
|
||||
// primitive (future callers may use fractional bounds).
|
||||
expect(clampInt(2.4, 2.5, 10, 0)).toBe(2);
|
||||
});
|
||||
|
||||
it('falls back on non-finite input', () => {
|
||||
expect(clampInt('abc', 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(NaN, 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(undefined, 0, 10, 4)).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -1,68 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mapWithConcurrency } from '../src/concurrency';
|
||||
|
||||
const tick = () => new Promise<void>((r) => setTimeout(r, 0));
|
||||
|
||||
describe('mapWithConcurrency', () => {
|
||||
it('returns results in input order', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10);
|
||||
expect(out).toEqual([10, 20, 30, 40, 50]);
|
||||
});
|
||||
|
||||
it('passes the absolute index (across batch boundaries)', async () => {
|
||||
const seen: Array<[number, number]> = [];
|
||||
await mapWithConcurrency(['a', 'b', 'c', 'd', 'e'], 2, async (item, i) => {
|
||||
seen.push([i, item.charCodeAt(0)]);
|
||||
return i;
|
||||
});
|
||||
expect(seen.map(([i]) => i).sort((x, y) => x - y)).toEqual([0, 1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it('never runs more than `concurrency` at once (batched), and serializes across batches', async () => {
|
||||
let inFlight = 0;
|
||||
let peak = 0;
|
||||
const order: number[] = [];
|
||||
await mapWithConcurrency([0, 1, 2, 3, 4, 5, 6], 3, async (n) => {
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
order.push(n);
|
||||
inFlight--;
|
||||
return n;
|
||||
});
|
||||
expect(peak).toBeLessThanOrEqual(3);
|
||||
// batched: first 3 (0,1,2) settle before the next batch (3,4,5) starts.
|
||||
expect(order.slice(0, 3).sort((a, b) => a - b)).toEqual([0, 1, 2]);
|
||||
expect(order.slice(3, 6).sort((a, b) => a - b)).toEqual([3, 4, 5]);
|
||||
expect(order[6]).toBe(6);
|
||||
});
|
||||
|
||||
it('handles a length not divisible by concurrency (short final batch)', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 3, async (n) => n);
|
||||
expect(out).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it('runs everything in one batch when concurrency >= length', async () => {
|
||||
let peak = 0, inFlight = 0;
|
||||
const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => {
|
||||
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
|
||||
});
|
||||
expect(out).toEqual([1, 2, 3]);
|
||||
expect(peak).toBe(3);
|
||||
});
|
||||
|
||||
it('returns [] for an empty input without calling fn', async () => {
|
||||
let called = 0;
|
||||
const out = await mapWithConcurrency([], 4, async (n) => { called++; return n; });
|
||||
expect(out).toEqual([]);
|
||||
expect(called).toBe(0);
|
||||
});
|
||||
|
||||
it('treats concurrency < 1 as 1 (fully serial)', async () => {
|
||||
let peak = 0, inFlight = 0;
|
||||
await mapWithConcurrency([1, 2, 3], 0, async (n) => {
|
||||
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
|
||||
});
|
||||
expect(peak).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex';
|
||||
|
||||
describe('hex', () => {
|
||||
it('toHex / toHexUpper render bytes as zero-padded hex', () => {
|
||||
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
|
||||
expect(toHex(b)).toBe('000fa0ff');
|
||||
expect(toHexUpper(b)).toBe('000FA0FF');
|
||||
expect(toHex(Uint8Array.of())).toBe('');
|
||||
});
|
||||
|
||||
it('hexPreview appends "..." only past maxBytes', () => {
|
||||
const b = Uint8Array.from([1, 2, 3, 4, 5]);
|
||||
expect(hexPreview(b)).toBe('0102030405'); // under the default 64-byte cap
|
||||
expect(hexPreview(b, 5)).toBe('0102030405'); // exactly at the cap → no ellipsis
|
||||
expect(hexPreview(b, 2)).toBe('0102...'); // truncated
|
||||
expect(hexPreview(b, 0)).toBe('...'); // nothing shown, but bytes remain
|
||||
});
|
||||
|
||||
it('fromHex round-trips toHex and rejects odd-length input', () => {
|
||||
const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]);
|
||||
expect(fromHex(toHex(b)).equals(b)).toBe(true);
|
||||
expect(toHex(fromHex('00ffa0'))).toBe('00ffa0');
|
||||
expect(() => fromHex('abc')).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { sanitizeLogLine } from '../src/log-sanitize';
|
||||
|
||||
describe('sanitizeLogLine', () => {
|
||||
it('removes SGR styling in seven-bit and eight-bit forms', () => {
|
||||
expect(sanitizeLogLine('\x1b[31mred\x1b[0m / \u009b32mgreen\u009b0m')).toBe('red / green');
|
||||
});
|
||||
|
||||
it('removes OSC hyperlinks without removing their visible label', () => {
|
||||
expect(
|
||||
sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07'),
|
||||
).toBe('visible');
|
||||
});
|
||||
|
||||
it('removes terminal control-string payloads', () => {
|
||||
expect(sanitizeLogLine('before\x1bPprivate payload\x1b\\after')).toBe('beforeafter');
|
||||
});
|
||||
|
||||
it('preserves tabs and newlines while removing other controls', () => {
|
||||
expect(sanitizeLogLine('one\ttwo\nthree\r\x00')).toBe('one\ttwo\nthree');
|
||||
});
|
||||
|
||||
it('does not leak unterminated terminal strings', () => {
|
||||
expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible');
|
||||
});
|
||||
});
|
||||
@@ -1,234 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
redactLogMessage,
|
||||
renderParamsVerbose,
|
||||
summarizeParams,
|
||||
} from '../src/log-summary';
|
||||
|
||||
describe('summarizeParams', () => {
|
||||
it('renders null/undefined as {}', () => {
|
||||
expect(summarizeParams(null)).toBe('{}');
|
||||
expect(summarizeParams(undefined)).toBe('{}');
|
||||
});
|
||||
|
||||
it('renders a top-level non-object via String() WITHOUT quotes', () => {
|
||||
// The reported change-request: a top-level primitive is NOT JSON-quoted.
|
||||
expect(summarizeParams('hello')).toBe('hello');
|
||||
expect(summarizeParams(123)).toBe('123');
|
||||
});
|
||||
|
||||
it('collapses a top-level array to [len=N]', () => {
|
||||
expect(summarizeParams([1, 2, 3])).toBe('[len=3]');
|
||||
});
|
||||
|
||||
it('quotes string fields, collapses nested values, truncates long strings', () => {
|
||||
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] }))
|
||||
.toBe('a=1 b="x" c={...} e=[len=2]');
|
||||
expect(summarizeParams({ s: 'x'.repeat(50) }))
|
||||
.toBe(`s="${'x'.repeat(40)}..."`);
|
||||
});
|
||||
|
||||
it('redacts authentication fields without exposing their values', () => {
|
||||
const out = summarizeParams({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
Authorization: 'Bearer authorization-value',
|
||||
user_password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
group_id: 12345,
|
||||
});
|
||||
|
||||
expect(out).toContain('token="***"');
|
||||
expect(out).toContain('Cookie="***"');
|
||||
expect(out).toContain('Authorization="***"');
|
||||
expect(out).toContain('user_password="***"');
|
||||
expect(out).toContain('apiKey="***"');
|
||||
expect(out).toContain('group_id=12345');
|
||||
expect(out).not.toMatch(
|
||||
/token-value|cookie-value|authorization-value|password-value|key-value/,
|
||||
);
|
||||
});
|
||||
|
||||
it('does not treat sensitive substrings inside ordinary keys as credentials', () => {
|
||||
expect(summarizeParams({
|
||||
retoken: 'visible',
|
||||
cookietown: 'visible',
|
||||
myauthorization: 'visible',
|
||||
})).toBe(
|
||||
'retoken="visible" cookietown="visible" myauthorization="visible"',
|
||||
);
|
||||
});
|
||||
|
||||
it('caps total output and appends "..." on overflow', () => {
|
||||
const big: Record<string, number> = {};
|
||||
for (let i = 0; i < 60; i++) big['key' + i] = i;
|
||||
const out = summarizeParams(big);
|
||||
expect(out.startsWith('key0=0')).toBe(true);
|
||||
expect(out.endsWith('...')).toBe(true);
|
||||
expect(out.length).toBeLessThanOrEqual(200);
|
||||
});
|
||||
|
||||
it('caps a single oversized first key and top-level primitive', () => {
|
||||
const oversizedKey = 'k'.repeat(300);
|
||||
|
||||
const objectOut = summarizeParams({ [oversizedKey]: 'value' });
|
||||
const primitiveOut = summarizeParams('x'.repeat(300));
|
||||
|
||||
expect(objectOut).toHaveLength(200);
|
||||
expect(objectOut.endsWith('...')).toBe(true);
|
||||
expect(primitiveOut).toHaveLength(200);
|
||||
expect(primitiveOut.endsWith('...')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('redactLogMessage', () => {
|
||||
it('redacts explicit authentication assignments without changing prose', () => {
|
||||
const out = redactLogMessage(
|
||||
'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required',
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
'password=*** Authorization: *** cookie=*** password change required',
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts quoted object keys, Basic auth, and complete Cookie values', () => {
|
||||
const out = redactLogMessage(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
const expires = redactLogMessage(
|
||||
'Cookie=session=expires-secret; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Path=/; HttpOnly safe=visible',
|
||||
);
|
||||
|
||||
expect(out).toContain('json={"authorization":***}');
|
||||
expect(out).toContain("object={ 'api-key': *** }");
|
||||
expect(out).toContain('Authorization: *** Cookie=***');
|
||||
expect(expires).toBe('Cookie=*** safe=visible');
|
||||
expect(out).not.toMatch(/json-auth|api-secret|header-auth|cookie-secret|Path=|HttpOnly/);
|
||||
expect(expires).not.toMatch(/expires-secret|Expires|21 Oct|Path=|HttpOnly/);
|
||||
});
|
||||
|
||||
it('redacts complete multi-parameter Authorization values', () => {
|
||||
const out = redactLogMessage(
|
||||
'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n'
|
||||
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, '
|
||||
+ 'SignedHeaders=host;x-date, Signature=aws-secret\n'
|
||||
+ 'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/',
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
'Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***',
|
||||
);
|
||||
expect(out).not.toMatch(
|
||||
/alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/,
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts camelCase authentication keys without matching larger words', () => {
|
||||
const out = redactLogMessage(
|
||||
`authToken=auth-secret idToken=id-secret clientSecret=client-secret {"userPassword":"password-secret"}`,
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
`authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`,
|
||||
);
|
||||
expect(out).not.toMatch(
|
||||
/auth-secret|id-secret|client-secret|password-secret/,
|
||||
);
|
||||
expect(redactLogMessage(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
)).toBe('retoken=value cookietown=value myauthorization=value');
|
||||
});
|
||||
|
||||
it('redacts leading separator and numeric authentication keys without matching larger words', () => {
|
||||
expect(redactLogMessage(
|
||||
'_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible',
|
||||
)).toBe('_token=*** --password=*** 2faToken=*** retoken=visible');
|
||||
});
|
||||
|
||||
it('redacts nested assignments inside non-sensitive wrapper values', () => {
|
||||
expect(redactLogMessage(
|
||||
'params=authToken=auth-secret params=cookie="cookie-secret"',
|
||||
)).toBe('params=authToken=*** params=cookie=***');
|
||||
});
|
||||
|
||||
it('redacts the entire Authorization value when it starts with a marker', () => {
|
||||
expect(redactLogMessage('Authorization: *** secret-value'))
|
||||
.toBe('Authorization: ***');
|
||||
});
|
||||
|
||||
it('redacts property paths and URL query authentication values', () => {
|
||||
const out = redactLogMessage(
|
||||
'headers.authorization=Basic dXNlcjpwYXNz '
|
||||
+ 'request.token=plain-token '
|
||||
+ 'GET /callback?access_token=query-secret&x=1 '
|
||||
+ 'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
|
||||
expect(out).toContain('headers.authorization=***');
|
||||
expect(out).toContain('request.token=***');
|
||||
expect(out).toContain('/callback?access_token=***&x=1');
|
||||
expect(out).toContain('https://host/?api_key=***');
|
||||
expect(out).not.toMatch(/dXNlcjpwYXNz|plain-token|query-secret|url-secret/);
|
||||
});
|
||||
|
||||
it('redacts prefixed authentication keys without matching larger words', () => {
|
||||
const redacted = redactLogMessage(
|
||||
'x-api-key=api-secret user_password=password-secret '
|
||||
+ 'headers.authorization=Basic auth-secret '
|
||||
+ 'x-cookie="session=cookie-secret"; Path=/; HttpOnly',
|
||||
);
|
||||
|
||||
expect(redacted).toContain('x-api-key=***');
|
||||
expect(redacted).toContain('user_password=***');
|
||||
expect(redacted).toContain('headers.authorization=***');
|
||||
expect(redacted).toContain('x-cookie=***');
|
||||
expect(redacted).not.toMatch(/api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/);
|
||||
expect(redactLogMessage(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
)).toBe('retoken=value cookietown=value myauthorization=value');
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderParamsVerbose', () => {
|
||||
it('keeps authentication fields unredacted for complete TRACE diagnostics', () => {
|
||||
const out = renderParamsVerbose({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
});
|
||||
|
||||
expect(out).toContain('token:"token-value"');
|
||||
expect(out).toContain('Cookie:"cookie-value"');
|
||||
expect(out).toContain('password:"password-value"');
|
||||
expect(out).toContain('apiKey:"key-value"');
|
||||
expect(out).not.toContain('"***"');
|
||||
});
|
||||
|
||||
it('does not truncate TRACE values or their enclosing object', () => {
|
||||
const unicodeValue = '雪'.repeat(800);
|
||||
const out = renderParamsVerbose({ blob: unicodeValue, tail: 'complete' });
|
||||
|
||||
expect(out).toContain(`blob:${JSON.stringify(unicodeValue)}`);
|
||||
expect(out).toContain('tail:"complete"');
|
||||
expect(out).not.toMatch(/…<\d+B>|\.\.\./);
|
||||
});
|
||||
|
||||
it('guards against circular references', () => {
|
||||
const o: Record<string, unknown> = { a: 1 };
|
||||
o.self = o;
|
||||
expect(renderParamsVerbose(o)).toContain('"[circular]"');
|
||||
});
|
||||
|
||||
it('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}}');
|
||||
});
|
||||
|
||||
it('renders nested structure with primitives intact', () => {
|
||||
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
|
||||
});
|
||||
});
|
||||
@@ -1,313 +0,0 @@
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { externalFileLevel, externalLogLevel, fileWriteSpy } = vi.hoisted(() => {
|
||||
const savedFileLevel = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
return {
|
||||
externalFileLevel: savedFileLevel,
|
||||
externalLogLevel: savedLogLevel,
|
||||
fileWriteSpy: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
// Capture file transport writes via a spy so tests can assert on what reaches
|
||||
// the file.
|
||||
vi.mock('../src/log-file-transport', () => ({
|
||||
getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }),
|
||||
}));
|
||||
|
||||
import {
|
||||
createLogger,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '../src/logger';
|
||||
|
||||
// Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp
|
||||
// shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored
|
||||
// render path did `' '.repeat(slot - tagLen)` → RangeError: Invalid count value
|
||||
// → uncaughtException. The padding must clamp at zero.
|
||||
describe('logger UIN slot padding', () => {
|
||||
let prevTTY: boolean | undefined;
|
||||
let prevNoColor: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
prevTTY = process.stdout.isTTY;
|
||||
prevNoColor = process.env.NO_COLOR;
|
||||
// Force the colored render path (the only one that used .repeat()).
|
||||
(process.stdout as unknown as { isTTY: boolean }).isTTY = true;
|
||||
delete process.env.NO_COLOR;
|
||||
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
|
||||
if (prevNoColor === undefined) delete process.env.NO_COLOR;
|
||||
else process.env.NO_COLOR = prevNoColor;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('does not throw when the UIN tag exceeds the slot width', () => {
|
||||
const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars
|
||||
expect(() => log.info('phantom account line')).not.toThrow();
|
||||
expect(() => log.error('phantom error line')).not.toThrow();
|
||||
});
|
||||
|
||||
it('still renders a normal-width UIN and a no-UIN logger', () => {
|
||||
expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow();
|
||||
expect(() => createLogger('Test').info('no uin')).not.toThrow();
|
||||
});
|
||||
|
||||
it('keeps structured subscriber lines plain while terminal output stays colored', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => captured.push(entry));
|
||||
|
||||
createLogger('WebUI.Export').info('download me');
|
||||
unsubscribe();
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(captured[0]!.line).toMatch(/INFO\s+\[WebUI\.Export\] download me$/);
|
||||
expect(process.stdout.write).toHaveBeenCalledWith(expect.stringContaining('\x1b['));
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Independent file-level filtering ─────────────────────────────────────
|
||||
|
||||
const SAVED_FILE_LEVEL = externalFileLevel;
|
||||
|
||||
async function loadLoggerForFileLevel(level?: string) {
|
||||
if (level === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_FILE_LEVEL = level;
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
return import('../src/logger');
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
});
|
||||
|
||||
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;
|
||||
});
|
||||
|
||||
describe('file output gating', () => {
|
||||
const cases = [
|
||||
{ level: undefined, expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'debug', expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'info', expected: ['info', 'success', 'warn', 'error'] },
|
||||
{ level: 'success', expected: ['success', 'warn', 'error'] },
|
||||
{ level: 'warn', expected: ['warn', 'error'] },
|
||||
{ level: 'error', expected: ['error'] },
|
||||
] as const;
|
||||
|
||||
for (const testCase of cases) {
|
||||
it(`writes exactly the enabled levels for ${testCase.level ?? 'the default'}`, async () => {
|
||||
const fresh = await loadLoggerForFileLevel(testCase.level);
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
fresh.setLogLevel('trace');
|
||||
log.trace('trace');
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
log.success('success');
|
||||
log.warn('warn');
|
||||
log.error('error');
|
||||
|
||||
const messages = fileWriteSpy.mock.calls.map(([line]) => String(line).split('] ').at(-1));
|
||||
expect(messages).toEqual(testCase.expected);
|
||||
});
|
||||
}
|
||||
|
||||
it('accepts surrounding whitespace and mixed case', async () => {
|
||||
const fresh = await loadLoggerForFileLevel(' INFO ');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(expect.stringContaining('info'), undefined);
|
||||
});
|
||||
|
||||
it.each(['trace', 'verbose', 'erorr'])(
|
||||
'rejects unsupported file level %s at startup',
|
||||
async (level) => {
|
||||
await expect(loadLoggerForFileLevel(level)).rejects.toThrow(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('does not let the runtime console level change file output', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('info');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
fresh.setLogLevel('error');
|
||||
log.info('persisted-info');
|
||||
fresh.setLogLevel('trace');
|
||||
log.debug('filtered-debug');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('persisted-info'),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('skips rendering when both console and file filters reject a record', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('error');
|
||||
fresh.setLogLevel('error');
|
||||
const rendered = vi.fn(() => 'expensive');
|
||||
const value = { [Symbol.toPrimitive]: rendered };
|
||||
|
||||
fresh.createLogger('Test').debug('value=%s', value);
|
||||
|
||||
expect(rendered).not.toHaveBeenCalled();
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps trace out of files in an explicit file-threshold check', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
fresh.createLogger('Test').trace('full chain');
|
||||
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redacts authentication assignments from ordinary logs but not TRACE', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.info(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s safe=%s',
|
||||
'ordinary-password',
|
||||
'ordinary-authorization',
|
||||
'ordinary-cookie',
|
||||
'ordinary-token',
|
||||
'visible',
|
||||
);
|
||||
log.trace(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s',
|
||||
'trace-password',
|
||||
'trace-authorization',
|
||||
'trace-cookie',
|
||||
'trace-token',
|
||||
);
|
||||
log.info(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
log.info(
|
||||
'headers.authorization=Basic dotted-auth request.token=dotted-token '
|
||||
+ 'GET /callback?access_token=query-secret&x=1 '
|
||||
+ 'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
log.info(
|
||||
'Authorization: Digest username="alice", response="digest-secret"\n'
|
||||
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret',
|
||||
);
|
||||
log.info(
|
||||
'authToken=camel-auth idToken=camel-id clientSecret=camel-client '
|
||||
+ `json={"userPassword":"camel-password"}`,
|
||||
);
|
||||
log.info('_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret');
|
||||
log.info('Authorization: *** marker-secret');
|
||||
log.trace(
|
||||
`json={"authorization":"Basic trace-json-auth"} Authorization: Basic trace-header-auth Cookie=session=trace-cookie; Path=/`,
|
||||
);
|
||||
unsubscribe();
|
||||
|
||||
const ordinaryEntries = entries.filter((entry) => entry.level === 'info');
|
||||
const ordinary = ordinaryEntries.map((entry) => entry.message).join('\n');
|
||||
expect(ordinary).toContain('password=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('Cookie=***');
|
||||
expect(ordinary).toContain('token=***');
|
||||
expect(ordinary).toContain('headers.authorization=***');
|
||||
expect(ordinary).toContain('request.token=***');
|
||||
expect(ordinary).toContain('/callback?access_token=***&x=1');
|
||||
expect(ordinary).toContain('https://host/?api_key=***');
|
||||
expect(ordinary).toContain('Authorization: ***\nauthorization=***');
|
||||
expect(ordinary).toContain('authToken=***');
|
||||
expect(ordinary).toContain('idToken=***');
|
||||
expect(ordinary).toContain('clientSecret=***');
|
||||
expect(ordinary).toContain(`json={"userPassword":***}`);
|
||||
expect(ordinary).toContain('_token=***');
|
||||
expect(ordinary).toContain('--password=***');
|
||||
expect(ordinary).toContain('2faToken=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('safe=visible');
|
||||
expect(ordinary).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|camel-auth|camel-id|camel-client|camel-password|underscore-secret|cli-secret|two-factor-secret|marker-secret/,
|
||||
);
|
||||
|
||||
const trace = entries.filter((entry) => entry.level === 'trace')
|
||||
.map((entry) => entry.message)
|
||||
.join('\n');
|
||||
expect(trace).toContain('trace-password');
|
||||
expect(trace).toContain('trace-authorization');
|
||||
expect(trace).toContain('trace-cookie');
|
||||
expect(trace).toContain('trace-token');
|
||||
expect(trace).toContain('trace-json-auth');
|
||||
expect(trace).toContain('trace-header-auth');
|
||||
|
||||
const persisted = fileWriteSpy.mock.calls.map(([line]) => String(line)).join('\n');
|
||||
expect(persisted).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|trace-password|trace-json-auth/,
|
||||
);
|
||||
});
|
||||
|
||||
it('returns the complete retained normal and TRACE snapshot in record order', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
const log = fresh.createLogger('Export');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
log.info('normal-before');
|
||||
log.trace('trace-hex=001122aabbcc');
|
||||
log.warn('normal-after');
|
||||
|
||||
expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual([
|
||||
'normal-after',
|
||||
]);
|
||||
expect(fresh.getLogSnapshot().map((entry) => entry.message)).toEqual([
|
||||
'normal-before',
|
||||
'trace-hex=001122aabbcc',
|
||||
'normal-after',
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps bootstrap notices visible and persisted above configured thresholds', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('error');
|
||||
fresh.setLogLevel('error');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
|
||||
fresh.logInitialWebuiCredentials('secret');
|
||||
unsubscribe();
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
level: 'info',
|
||||
scope: 'WebUI',
|
||||
message: 'initial credentials: user=admin password=secret',
|
||||
});
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('initial credentials: user=admin password=secret'),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,34 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { currentRequestId, nextRequestId, runWithRequestId } from '../src/request-context';
|
||||
|
||||
describe('request-context', () => {
|
||||
it('nextRequestId increments monotonically and stays a positive integer', () => {
|
||||
const a = nextRequestId();
|
||||
const b = nextRequestId();
|
||||
expect(a).toBeGreaterThan(0);
|
||||
expect(b).toBe(a + 1);
|
||||
});
|
||||
|
||||
it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
|
||||
runWithRequestId(42, () => {
|
||||
expect(currentRequestId()).toBe(42);
|
||||
runWithRequestId(99, () => {
|
||||
expect(currentRequestId()).toBe(99);
|
||||
});
|
||||
expect(currentRequestId()).toBe(42); // outer scope restored after the nested one
|
||||
});
|
||||
|
||||
expect(currentRequestId()).toBeUndefined(); // cleared outside any scope
|
||||
|
||||
await runWithRequestId(7, async () => {
|
||||
await Promise.resolve();
|
||||
expect(currentRequestId()).toBe(7); // survives awaits in the same async chain
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the callback result', () => {
|
||||
expect(runWithRequestId(1, () => 'value')).toBe('value');
|
||||
});
|
||||
});
|
||||
@@ -1,191 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime';
|
||||
|
||||
describe('normalizeRuntimeConfig', () => {
|
||||
it('applies all defaults for an empty object', () => {
|
||||
expect(normalizeRuntimeConfig({})).toEqual({
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
webuiHost: '0.0.0.0',
|
||||
webuiTls: { enabled: false },
|
||||
trustProxy: '',
|
||||
logMaxTotalMb: 1024,
|
||||
logRetainDays: 7,
|
||||
logPerUin: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('passes through valid values', () => {
|
||||
expect(normalizeRuntimeConfig({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
})).toEqual({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back on invalid types', () => {
|
||||
const out = normalizeRuntimeConfig({
|
||||
webuiPort: 0, // out of range → default
|
||||
webuiHost: 123, // non-string → default
|
||||
webuiTls: 'yes', // non-object → default
|
||||
trustProxy: 5, // non-string → default
|
||||
});
|
||||
expect(out.webuiPort).toBe(5099);
|
||||
expect(out.webuiHost).toBe('0.0.0.0');
|
||||
expect(out.webuiTls).toEqual({ enabled: false });
|
||||
expect(out.trustProxy).toBe('');
|
||||
});
|
||||
|
||||
it('fails fast on invalid persisted log settings', () => {
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 }))
|
||||
.toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: -1 }))
|
||||
.toThrow(/logRetainDays/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' }))
|
||||
.toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: '' }))
|
||||
.toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER }))
|
||||
.toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER }))
|
||||
.toThrow(/logRetainDays/);
|
||||
});
|
||||
|
||||
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
|
||||
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true });
|
||||
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0');
|
||||
});
|
||||
|
||||
it('rejects a non-object input back to full defaults', () => {
|
||||
expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099);
|
||||
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('0.0.0.0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveRuntimeEnvOverrides', () => {
|
||||
it('returns empty when no SNOWLUMA_* vars are set', () => {
|
||||
expect(resolveRuntimeEnvOverrides({})).toEqual({});
|
||||
});
|
||||
|
||||
it('parses port / host / trustProxy from env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_WEBUI_PORT: '6700',
|
||||
SNOWLUMA_WEBUI_HOST: '127.0.0.1',
|
||||
SNOWLUMA_WEBUI_TRUST_PROXY: '1',
|
||||
})).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
|
||||
});
|
||||
|
||||
it('parses log storage overrides including retainDays=0', () => {
|
||||
expect(resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '4096',
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '0',
|
||||
SNOWLUMA_LOG_PER_UIN: '1',
|
||||
})).toEqual({
|
||||
logMaxTotalMb: 4096,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('fails fast on invalid log storage overrides', () => {
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '0',
|
||||
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '-1',
|
||||
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_PER_UIN: 'maybe',
|
||||
})).toThrow(/SNOWLUMA_LOG_PER_UIN/);
|
||||
});
|
||||
|
||||
it('fails fast when converted log storage overrides would be unsafe', () => {
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER),
|
||||
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER),
|
||||
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
});
|
||||
|
||||
it('ignores an out-of-range / non-numeric port env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
|
||||
});
|
||||
|
||||
it('treats trustProxy="0"/"off" as a real override (not absent)', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateRuntimeConfig (fs)', () => {
|
||||
let prevCwd: string;
|
||||
let dir: string;
|
||||
let prevPortEnv: string | undefined;
|
||||
beforeEach(async () => {
|
||||
const fs = await import('fs'); const os = await import('os'); const path = await import('path');
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-'));
|
||||
prevCwd = process.cwd();
|
||||
process.chdir(dir);
|
||||
prevPortEnv = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
});
|
||||
afterEach(async () => {
|
||||
process.chdir(prevCwd);
|
||||
if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('merges a patch over on-disk values and persists normalized', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } });
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: true });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiHost).toBe('127.0.0.1');
|
||||
expect(onDisk.webuiTls).toEqual({ enabled: true });
|
||||
});
|
||||
|
||||
it('does NOT bake an env-overridden port into the persisted file', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
process.env.SNOWLUMA_WEBUI_PORT = '9999';
|
||||
updateRuntimeConfig({ webuiHost: '127.0.0.1' });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999
|
||||
});
|
||||
|
||||
it('keeps the previous runtime file intact when atomic replacement fails', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
updateRuntimeConfig({ logRetainDays: 7 });
|
||||
const runtimePath = path.join('config', 'runtime.json');
|
||||
const before = fs.readFileSync(runtimePath, 'utf8');
|
||||
vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
|
||||
throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' });
|
||||
});
|
||||
|
||||
expect(() => updateRuntimeConfig({ logRetainDays: 0 }))
|
||||
.toThrow(/disk replacement failed/);
|
||||
expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before);
|
||||
expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,131 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { createSingleFlightCache } from '../src/single-flight-cache';
|
||||
|
||||
/** A promise whose resolve/reject is exposed, for driving single-flight races. */
|
||||
function deferred<T>() {
|
||||
let resolve!: (v: T) => void;
|
||||
let reject!: (e: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
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 });
|
||||
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
clock = 1050; // still fresh (< 100)
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
clock = 1101; // 101ms since store → expired
|
||||
expect(await cache.get('a')).toBe('a@1101');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('de-dupes concurrent callers onto a single load (single-flight)', async () => {
|
||||
const d = deferred<string>();
|
||||
const load = vi.fn(() => d.promise);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
|
||||
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
const p3 = cache.get('k');
|
||||
expect(load).toHaveBeenCalledTimes(1); // only one load in flight
|
||||
|
||||
d.resolve('v');
|
||||
expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keys independently — different keys load separately', async () => {
|
||||
const load = vi.fn(async (k: number) => k * 2);
|
||||
const cache = createSingleFlightCache<number, number>({ ttlMs: 1000, load });
|
||||
expect(await cache.get(1)).toBe(2);
|
||||
expect(await cache.get(2)).toBe(4);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('force bypasses the freshness check but still joins an in-flight load', async () => {
|
||||
let clock = 0;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load, now: () => clock });
|
||||
|
||||
expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh
|
||||
clock = 5; // still fresh
|
||||
expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// force still single-flights: two concurrent forced gets share one load.
|
||||
const d = deferred<string>();
|
||||
load.mockImplementationOnce(() => d.promise);
|
||||
const p1 = cache.get('a', { force: true });
|
||||
const p2 = cache.get('a', { force: true });
|
||||
expect(load).toHaveBeenCalledTimes(3); // not 4
|
||||
d.resolve('shared');
|
||||
expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']);
|
||||
});
|
||||
|
||||
it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => {
|
||||
let n = 0;
|
||||
const load = vi.fn(async () => ({ error: true as boolean, n: ++n }));
|
||||
const cache = createSingleFlightCache({ ttlMs: 10_000, load, shouldCache: (v) => !v.error });
|
||||
|
||||
// concurrent callers still share one load...
|
||||
const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]);
|
||||
expect(a).toEqual({ error: true, n: 1 });
|
||||
expect(b).toEqual({ error: true, n: 1 });
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
// ...but nothing was cached, so the next call reloads.
|
||||
expect(await cache.get('k')).toEqual({ error: true, n: 2 });
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// a good result IS cached.
|
||||
load.mockImplementationOnce(async () => ({ error: false, n: ++n }));
|
||||
const good = await cache.get('k');
|
||||
expect(good).toEqual({ error: false, n: 3 });
|
||||
expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => {
|
||||
let attempt = 0;
|
||||
const load = vi.fn(async () => {
|
||||
attempt++;
|
||||
if (attempt === 1) throw new Error('boom');
|
||||
return 'ok';
|
||||
});
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
await expect(p1).rejects.toThrow('boom');
|
||||
await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
// in-flight cleared + not cached → next call retries and succeeds.
|
||||
expect(await cache.get('k')).toBe('ok');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('invalidate drops a cached entry; clear drops all', async () => {
|
||||
const load = vi.fn(async (k: string) => k.toUpperCase());
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
cache.invalidate('a');
|
||||
await cache.get('a'); // reloads
|
||||
await cache.get('b'); // still cached
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
|
||||
cache.clear();
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
});
|
||||
@@ -1,117 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
createLogger,
|
||||
currentRequestId,
|
||||
getLogLevel,
|
||||
nextRequestId,
|
||||
renderTraceBytes,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
runWithTraceRequest,
|
||||
setLogLevel,
|
||||
} from '../src/logger';
|
||||
|
||||
const originalLevel = getLogLevel();
|
||||
|
||||
afterEach(() => {
|
||||
setLogLevel(originalLevel);
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
|
||||
it('renders only the addressed Uint8Array view', () => {
|
||||
const backing = new Uint8Array([0xaa, 0x00, 0x0f, 0xff, 0xbb]);
|
||||
|
||||
expect(renderTraceBytes(backing.subarray(1, 4))).toBe('000fff');
|
||||
expect(renderTraceBytes(Buffer.from(backing.buffer).subarray(2, 4))).toBe('0fff');
|
||||
});
|
||||
|
||||
it('does not render bytes while TRACE is disabled', () => {
|
||||
setLogLevel('info');
|
||||
let rendered = false;
|
||||
|
||||
createLogger('Trace.Contract').trace(() => {
|
||||
rendered = true;
|
||||
return ['body=%s', renderTraceBytes(new Uint8Array([0xff]))];
|
||||
});
|
||||
|
||||
expect(rendered).toBe(false);
|
||||
});
|
||||
|
||||
it('creates distinct request contexts that survive asynchronous work', async () => {
|
||||
setLogLevel('info');
|
||||
const beforeDisabled = nextRequestId();
|
||||
expect(runWithTraceRequest(() => currentRequestId())).toBeUndefined();
|
||||
const afterDisabled = nextRequestId();
|
||||
expect(afterDisabled).toBe(beforeDisabled + 1);
|
||||
|
||||
setLogLevel('trace');
|
||||
const observeContext = () => runWithTraceRequest(async () => {
|
||||
const before = currentRequestId();
|
||||
await Promise.resolve();
|
||||
const after = currentRequestId();
|
||||
expect(after).toBe(before);
|
||||
return after;
|
||||
});
|
||||
|
||||
const first = await observeContext();
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
const second = await observeContext();
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
|
||||
expect(first).toEqual(expect.any(Number));
|
||||
expect(first).toBeGreaterThan(0);
|
||||
expect(second).toEqual(expect.any(Number));
|
||||
expect(second).toBeGreaterThan(0);
|
||||
expect(second).not.toBe(first);
|
||||
});
|
||||
|
||||
it('allocates once for nested TRACE contexts and reuses the request id', () => {
|
||||
setLogLevel('trace');
|
||||
const before = nextRequestId();
|
||||
|
||||
const observed = runWithTraceRequest(() => {
|
||||
const outer = currentRequestId();
|
||||
const inner = runWithTraceRequest(() => currentRequestId());
|
||||
return { outer, inner };
|
||||
});
|
||||
|
||||
const after = nextRequestId();
|
||||
expect(observed.outer).toEqual(expect.any(Number));
|
||||
expect(observed.inner).toBe(observed.outer);
|
||||
expect(observed.outer).toBe(before + 1);
|
||||
expect(after).toBe(before + 2);
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('detaches long-lived resources from the current request context', async () => {
|
||||
await runWithRequestId(4243, async () => {
|
||||
expect(currentRequestId()).toBe(4243);
|
||||
const detached = await runWithoutRequestContext(async () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
await Promise.resolve();
|
||||
return currentRequestId();
|
||||
});
|
||||
expect(detached).toBeUndefined();
|
||||
expect(currentRequestId()).toBe(4243);
|
||||
});
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reuses an existing request context even while TRACE is disabled', async () => {
|
||||
setLogLevel('info');
|
||||
|
||||
await runWithRequestId(4242, async () => {
|
||||
const observed = await runWithTraceRequest(async () => {
|
||||
await Promise.resolve();
|
||||
return currentRequestId();
|
||||
});
|
||||
expect(observed).toBe(4242);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isRealUin } from '../src/uin';
|
||||
|
||||
describe('isRealUin', () => {
|
||||
it('accepts real QQ UINs (5..10 digits)', () => {
|
||||
expect(isRealUin('10001')).toBe(true); // 5-digit floor
|
||||
expect(isRealUin('123456789')).toBe(true);
|
||||
expect(isRealUin('4294967295')).toBe(true); // uint32 max, 10 digits
|
||||
});
|
||||
|
||||
it('rejects the empty string and "0"', () => {
|
||||
expect(isRealUin('')).toBe(false);
|
||||
expect(isRealUin('0')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects too-short UINs (< 5 digits)', () => {
|
||||
expect(isRealUin('1')).toBe(false);
|
||||
expect(isRealUin('1234')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects the garbage timestamp-shaped UINs from issue #162 (11+ digits)', () => {
|
||||
expect(isRealUin('1701414379536')).toBe(false); // 13-digit ms timestamp
|
||||
expect(isRealUin('1614019567632')).toBe(false);
|
||||
expect(isRealUin('2014024115056')).toBe(false);
|
||||
expect(isRealUin('12345678901')).toBe(false); // 11 digits — first rejected width
|
||||
});
|
||||
|
||||
it('rejects non-digit strings (path traversal / injection guards)', () => {
|
||||
expect(isRealUin('12345a')).toBe(false);
|
||||
expect(isRealUin('12 345')).toBe(false);
|
||||
expect(isRealUin('../etc')).toBe(false);
|
||||
expect(isRealUin('123456\n')).toBe(false);
|
||||
});
|
||||
|
||||
it('guarantees a BigInt-safe pure-digit string on accept', () => {
|
||||
const uin = '123456789';
|
||||
expect(isRealUin(uin)).toBe(true);
|
||||
expect(() => BigInt(uin)).not.toThrow();
|
||||
});
|
||||
});
|
||||
16
packages/core/config/.gitignore
vendored
16
packages/core/config/.gitignore
vendored
@@ -1,16 +0,0 @@
|
||||
# Per-instance runtime state written by the dev server / production daemon.
|
||||
# `runtime.json` is the only tracked file (the deploy-time overrides for
|
||||
# webuiPort, hookAutoLoad, etc); everything else here is operator-private:
|
||||
# * webui.json — admin password hash + rotation state
|
||||
# * consent.json — EULA/PRIVACY acceptance per agreement version
|
||||
# * notifications.json — per-account webhook destinations
|
||||
# * onebot_<uin>.json — per-uin OneBot transport binding (HTTP/WS ports etc)
|
||||
# * ui.json — WebUI panel layout per operator
|
||||
#
|
||||
# Without this ignore file, every `pnpm dev:mode` / `node dist/index.mjs`
|
||||
# leaves a 5-file untracked surface in `packages/core/config/` that pollutes
|
||||
# `git status` and would accidentally commit local creds if `git add -A` is used.
|
||||
|
||||
*
|
||||
!.gitignore
|
||||
!runtime.json
|
||||
@@ -1,7 +1,6 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.13.0",
|
||||
"version": "1.9.2",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -11,25 +10,25 @@
|
||||
"types": "./src/index.ts",
|
||||
"default": "../../dist/index.mjs"
|
||||
},
|
||||
"./bridge": {
|
||||
"types": "./src/bridge/bridge.ts",
|
||||
"default": "./src/bridge/bridge.ts"
|
||||
"./core": {
|
||||
"types": "./src/core.ts",
|
||||
"default": "./src/core.ts"
|
||||
},
|
||||
"./bridge-interface": {
|
||||
"types": "./src/bridge/bridge-interface.ts",
|
||||
"default": "./src/bridge/bridge-interface.ts"
|
||||
"./core-context": {
|
||||
"types": "./src/core-context.ts",
|
||||
"default": "./src/core-context.ts"
|
||||
},
|
||||
"./bridge-context": {
|
||||
"types": "./src/bridge/bridge-context.ts",
|
||||
"default": "./src/bridge/bridge-context.ts"
|
||||
"./core-ctx": {
|
||||
"types": "./src/core-ctx.ts",
|
||||
"default": "./src/core-ctx.ts"
|
||||
},
|
||||
"./manager": {
|
||||
"types": "./src/bridge/manager.ts",
|
||||
"default": "./src/bridge/manager.ts"
|
||||
"./hub": {
|
||||
"types": "./src/hub.ts",
|
||||
"default": "./src/hub.ts"
|
||||
},
|
||||
"./apis": {
|
||||
"types": "./src/bridge/apis/index.ts",
|
||||
"default": "./src/bridge/apis/index.ts"
|
||||
"types": "./src/apis/index.ts",
|
||||
"default": "./src/apis/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
@@ -41,7 +40,9 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/bridge": "workspace:*",
|
||||
"@snowluma/channel": "workspace:*",
|
||||
"@snowluma/channel-hook": "workspace:*",
|
||||
"@snowluma/channel-socket": "workspace:*",
|
||||
"@snowluma/common": "workspace:*",
|
||||
"@snowluma/onebot": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
@@ -52,9 +53,9 @@
|
||||
"devDependencies": {
|
||||
"@hono/node-server": "^1.19.14",
|
||||
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||
"@types/node": "catalog:",
|
||||
"@types/node": "^24.12.2",
|
||||
"cross-env": "^10.1.0",
|
||||
"hono": "^4.12.25",
|
||||
"hono": "^4.12.18",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user