Compare commits
180 Commits
native/aut
...
v1.11.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18d8273f5c | ||
|
|
0e6e2ec51d | ||
|
|
007dfaf6e2 | ||
|
|
8dde7ef8e2 | ||
|
|
5f90cc9b6e | ||
|
|
a4ab4e92b5 | ||
|
|
1b968b9126 | ||
|
|
e83eb80f2c | ||
|
|
0e4d958b5f | ||
|
|
631cc982a0 | ||
|
|
7b91903f80 | ||
|
|
5324e2f014 | ||
|
|
c236bc86ee | ||
|
|
9a6c17cb27 | ||
|
|
efac547d6a | ||
|
|
770b224d58 | ||
|
|
0d03b00643 | ||
|
|
d3eb3bae14 | ||
|
|
5f01c6ab5f | ||
|
|
6cb7f2c6d0 | ||
|
|
07c08ed74d | ||
|
|
b20ed12761 | ||
|
|
c027161a64 | ||
|
|
95b5878456 | ||
|
|
f127e3dc59 | ||
|
|
7b93eb2716 | ||
|
|
abef7973d9 | ||
|
|
7744e24af2 | ||
|
|
884db940df | ||
|
|
3e99d3bb5a | ||
|
|
b5ede95772 | ||
|
|
1f2bf4d3f2 | ||
|
|
c85c510c0b | ||
|
|
99547e847e | ||
|
|
d17381a221 | ||
|
|
a11c684dfd | ||
|
|
72aedbc612 | ||
|
|
63ab7a1846 | ||
|
|
3932958c39 | ||
|
|
ade76d3d2f | ||
|
|
c822c5dab6 | ||
|
|
a8f24b8f13 | ||
|
|
f111ba7129 | ||
|
|
3db89d0bd0 | ||
|
|
298d174640 | ||
|
|
29a792cfdf | ||
|
|
c1d27c5055 | ||
|
|
85ca207279 | ||
|
|
d89b095af5 | ||
|
|
15a6fe3785 | ||
|
|
ae17bc0cf5 | ||
|
|
891a197335 | ||
|
|
b6cde5101d | ||
|
|
9d67630396 | ||
|
|
6f6f372337 | ||
|
|
5be852f394 | ||
|
|
ab45667fdf | ||
|
|
ab40f086ee | ||
|
|
8e173cf7d7 | ||
|
|
f4170b014a | ||
|
|
f424454422 | ||
|
|
5d6ce86b66 | ||
|
|
9ca64bed10 | ||
|
|
2f374ea8c9 | ||
|
|
c90a3954e4 | ||
|
|
397087dc74 | ||
|
|
b807825a09 | ||
|
|
48e2777bc3 | ||
|
|
a8307891fa | ||
|
|
b6c476390f | ||
|
|
fc4d3a9c5d | ||
|
|
1f23e6e9f0 | ||
|
|
0cf9cdd0d7 | ||
|
|
90456def2e | ||
|
|
8fc5917b3b | ||
|
|
65195abbe0 | ||
|
|
d5fbd6fa06 | ||
|
|
383ddb0a5d | ||
|
|
11866caa2f | ||
|
|
c5611ed622 | ||
|
|
a7667f1cd5 | ||
|
|
c839121fdb | ||
|
|
f9900053b0 | ||
|
|
14a61f4ce8 | ||
|
|
7285db1e37 | ||
|
|
369dea582c | ||
|
|
4f0a0f89ae | ||
|
|
01ef98abb6 | ||
|
|
62eb8fd763 | ||
|
|
547640bbfd | ||
|
|
f8caa92333 | ||
|
|
57ff0e69d8 | ||
|
|
053137669a | ||
|
|
37f768dd33 | ||
|
|
5dc3ec88d4 | ||
|
|
688402814c | ||
|
|
7ec74f2928 | ||
|
|
2b15bc6710 | ||
|
|
196f98e97c | ||
|
|
ea1c5ff9eb | ||
|
|
659970077a | ||
|
|
5d39cf5782 | ||
|
|
12b01907bc | ||
|
|
219d60410a | ||
|
|
182df4b0e2 | ||
|
|
6c2a3fc325 | ||
|
|
5eaac0870c | ||
|
|
04591517fa | ||
|
|
e1f5267764 | ||
|
|
85182795b5 | ||
|
|
70fd40e34c | ||
|
|
0e8a194d4f | ||
|
|
d2490787ae | ||
|
|
0163af979a | ||
|
|
75f14540c8 | ||
|
|
5e0d2db8b2 | ||
|
|
18014fb3c5 | ||
|
|
355cce1e52 | ||
|
|
04a9016a7d | ||
|
|
cf7de9f7bd | ||
|
|
a60385c376 | ||
|
|
351db573d8 | ||
|
|
3b023b3275 | ||
|
|
319c7d607d | ||
|
|
9de12db447 | ||
|
|
ecea72df40 | ||
|
|
214287da28 | ||
|
|
81969a4590 | ||
|
|
860848a310 | ||
|
|
39338c3f1d | ||
|
|
02de2acea4 | ||
|
|
3eba2a677c | ||
|
|
78b0e1a124 | ||
|
|
feaa94bec7 | ||
|
|
67f8bf3941 | ||
|
|
7343ae6372 | ||
|
|
41bad7f24c | ||
|
|
19c03eb0ba | ||
|
|
fbc5a3c981 | ||
|
|
1ce7385d1e | ||
|
|
3a4af38842 | ||
|
|
e11601bfec | ||
|
|
a305afbc76 | ||
|
|
84cdd99868 | ||
|
|
bae9f8edb0 | ||
|
|
f9ce49ac7e | ||
|
|
bb752b13a1 | ||
|
|
a9f5f277f1 | ||
|
|
de3bb4817d | ||
|
|
a7522deb82 | ||
|
|
53f68b3945 | ||
|
|
5302341dfc | ||
|
|
fb7675f3cb | ||
|
|
1d2a56bcdb | ||
|
|
74c7e086c7 | ||
|
|
9ad37d4ada | ||
|
|
1bdb8a40c4 | ||
|
|
4e0ec92c23 | ||
|
|
2b3d1c67c2 | ||
|
|
b918450483 | ||
|
|
157cc90397 | ||
|
|
1bd126562f | ||
|
|
e160837f8b | ||
|
|
4593ba3340 | ||
|
|
45aae92af5 | ||
|
|
839de51519 | ||
|
|
11e7584d1c | ||
|
|
f470b7a10c | ||
|
|
8b87f80951 | ||
|
|
b135752577 | ||
|
|
fd2345b772 | ||
|
|
7f391e065e | ||
|
|
261d6596dc | ||
|
|
5d08fc8471 | ||
|
|
e5e6d50f2f | ||
|
|
7d90820e19 | ||
|
|
69195ced93 | ||
|
|
d2c56d565b | ||
|
|
cc27cd1f43 | ||
|
|
40c65c87bd |
33
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
33
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -18,13 +18,15 @@ 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.8.5"
|
||||
placeholder: "例如 1.10.2"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
@@ -53,6 +55,19 @@ 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:
|
||||
@@ -106,11 +121,21 @@ body:
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: 相关日志 / 错误堆栈
|
||||
label: TRACE 日志 / 错误堆栈
|
||||
description: |
|
||||
粘贴控制台日志、SSE 实时日志或错误堆栈。
|
||||
请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。
|
||||
**必须提供 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] ...
|
||||
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,11 +66,13 @@ body:
|
||||
- OneBot v11 规范: https://github.com/botuniverse/onebot-11/...
|
||||
- 相关讨论: #xxx
|
||||
|
||||
- type: checkboxes
|
||||
- type: dropdown
|
||||
id: willingness
|
||||
attributes:
|
||||
label: 您是否愿意提交 PR 来实现这个功能?
|
||||
options:
|
||||
- label: 愿意,且需要维护者讨论方案后再动手
|
||||
- label: 愿意,已有大致实现思路
|
||||
- label: 暂时只提建议
|
||||
- 愿意,但需要维护者讨论方案后再动手
|
||||
- 愿意,已有大致实现思路
|
||||
- 暂时只提建议
|
||||
validations:
|
||||
required: true
|
||||
|
||||
17
.github/pull_request_template.md
vendored
Normal file
17
.github/pull_request_template.md
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
<!-- 感谢贡献。请填写以下内容,方便评审。 -->
|
||||
|
||||
## 关联 Issue
|
||||
|
||||
<!-- 例如 Closes #123。若无关联 issue,请说明这个 PR 解决什么问题、为何现在做。 -->
|
||||
|
||||
## 变更说明
|
||||
|
||||
<!-- 简述本 PR 做了什么、为什么这样做。 -->
|
||||
|
||||
## 提交前检查
|
||||
|
||||
- [ ] 本 PR 聚焦单一目标,未夹带无关改动
|
||||
- [ ] 已通过 `pnpm lint` 与 `pnpm typecheck`
|
||||
- [ ] 已补充/更新相关测试,且 `pnpm test` 通过
|
||||
- [ ] 文件行尾为 LF(未引入 CRLF)
|
||||
- [ ] PR 描述与实际实现一致
|
||||
10
.github/workflows/ci.yml
vendored
10
.github/workflows/ci.yml
vendored
@@ -41,3 +41,13 @@ jobs:
|
||||
|
||||
- name: Run all package tests
|
||||
run: pnpm -r --no-bail --if-present 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: |
|
||||
if ! git diff --exit-code -- packages/mcp/src/generated; then
|
||||
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
153
.github/workflows/dev-build.yml
vendored
153
.github/workflows/dev-build.yml
vendored
@@ -7,6 +7,15 @@ 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
|
||||
@@ -14,10 +23,20 @@ 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({
|
||||
@@ -27,16 +46,20 @@ jobs:
|
||||
page,
|
||||
});
|
||||
if (artifacts.length === 0) break;
|
||||
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}`);
|
||||
}
|
||||
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)
|
||||
}
|
||||
await github.rest.actions.deleteArtifact({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
artifact_id: artifact.id,
|
||||
});
|
||||
console.log(`Deleted artifact: ${artifact.name}`);
|
||||
}
|
||||
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -110,6 +133,13 @@ jobs:
|
||||
SNOWLUMA_TARGET: ${{ matrix.target }}
|
||||
run: pnpm run build:all
|
||||
|
||||
# Bundle production node_modules into dist/ before packaging — mirrors
|
||||
# release.yml. Without this the `-lite` tarball has no runtime deps and the
|
||||
# Docker image (which bakes the lite tarball) can't start.
|
||||
- name: Bundle runtime dependencies
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
@@ -140,3 +170,110 @@ 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
Normal file
94
.github/workflows/issue-require-logs.yml
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
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
Normal file
65
.github/workflows/issue-template-guard.yml
vendored
Normal file
@@ -0,0 +1,65 @@
|
||||
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)`);
|
||||
34
.github/workflows/stale-needs-logs.yml
vendored
Normal file
34
.github/workflows/stale-needs-logs.yml
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
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
Normal file
114
.github/workflows/sync-docs-catalog.yml
vendored
Normal file
@@ -0,0 +1,114 @@
|
||||
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: '22'
|
||||
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
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -11,7 +11,13 @@ 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/
|
||||
|
||||
11
package.json
11
package.json
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.10.0",
|
||||
"version": "1.11.3",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -16,6 +16,9 @@
|
||||
"dev:web": "pnpm --filter webui dev",
|
||||
"test": "pnpm --filter @snowluma/core test",
|
||||
"test:watch": "pnpm --filter @snowluma/core test:watch",
|
||||
"test:common": "pnpm --filter @snowluma/common test",
|
||||
"test:all": "pnpm -r --if-present test",
|
||||
"coverage": "pnpm --filter @snowluma/common test -- --coverage",
|
||||
"typecheck": "pnpm -r --if-present typecheck",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
@@ -44,7 +47,11 @@
|
||||
},
|
||||
"onlyBuiltDependencies": [
|
||||
"better-sqlite3"
|
||||
]
|
||||
],
|
||||
"overrides": {
|
||||
"esbuild@<0.28.1": "^0.28.1",
|
||||
"@babel/core@<7.29.6": "^7.29.6"
|
||||
}
|
||||
},
|
||||
"packageManager": "pnpm@10.28.0",
|
||||
"engines": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.10.0",
|
||||
"version": "1.11.3",
|
||||
"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).",
|
||||
|
||||
@@ -6,10 +6,12 @@ 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';
|
||||
@@ -49,6 +51,13 @@ export type HookManagerDeps = {
|
||||
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
|
||||
* Failed loads are logged and leave the session in the 'error' state. */
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -74,8 +83,15 @@ export class HookManager {
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly pipeWatcher: PipeWatcher;
|
||||
private readonly ownsPipeWatcher: boolean;
|
||||
private readonly listProcessesNative: () => HookProcessBaseInfo[];
|
||||
/** 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 startPromise: Promise<void>;
|
||||
@@ -85,6 +101,7 @@ export class HookManager {
|
||||
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 ?? {
|
||||
@@ -95,15 +112,38 @@ export class HookManager {
|
||||
},
|
||||
};
|
||||
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
|
||||
this.listProcessesNative = deps.listProcesses ?? listHookProcesses;
|
||||
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.listProcessesNative,
|
||||
listProcesses: this.enumerate,
|
||||
listLivePipes: () => QqHookClient.listLivePipes(),
|
||||
intervalMs: deps.watcherIntervalMs,
|
||||
log: this.log,
|
||||
@@ -119,12 +159,13 @@ export class 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 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) {
|
||||
@@ -172,6 +213,7 @@ export class HookManager {
|
||||
session.dispose();
|
||||
}
|
||||
this.sessions.clear();
|
||||
this.enumerator?.dispose();
|
||||
if (this.ownsPipeWatcher) {
|
||||
this.pipeWatcher.dispose();
|
||||
}
|
||||
@@ -193,11 +235,13 @@ export class HookManager {
|
||||
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
|
||||
});
|
||||
}
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
this.pipeWatcher.on('process-gone', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.notifyProcessGone();
|
||||
this.notifySessionsChanged();
|
||||
});
|
||||
this.pipeWatcher.on('pipe-up', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
@@ -253,6 +297,12 @@ export class HookManager {
|
||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
});
|
||||
// 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);
|
||||
});
|
||||
@@ -261,6 +311,19 @@ export class HookManager {
|
||||
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');
|
||||
}
|
||||
|
||||
@@ -1,17 +1,29 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
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;
|
||||
|
||||
export type HookSessionDeps = {
|
||||
injector: {
|
||||
inject: (pid: number) => 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
|
||||
@@ -49,6 +61,7 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly probeLogin: (pid: number) => Promise<QqPortLoginInfo | null>;
|
||||
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
|
||||
private readonly onPacket: PacketSink | null;
|
||||
private readonly log: Logger;
|
||||
@@ -69,12 +82,15 @@ export class HookSession extends EventEmitter {
|
||||
private bound = false;
|
||||
private opChain: Promise<unknown> = Promise.resolve();
|
||||
private disposed = false;
|
||||
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private probing = false;
|
||||
|
||||
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');
|
||||
@@ -131,17 +147,7 @@ export class HookSession extends EventEmitter {
|
||||
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', '');
|
||||
}
|
||||
await this.reconcilePipeUp();
|
||||
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
@@ -149,18 +155,7 @@ export class HookSession extends EventEmitter {
|
||||
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);
|
||||
this.reconcilePipeDown();
|
||||
}).catch(err => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
@@ -227,10 +222,7 @@ export class HookSession extends EventEmitter {
|
||||
this._method = this.injectResult.method;
|
||||
}
|
||||
}
|
||||
this.setStatus(
|
||||
this.connected ? (this.loggedIn ? 'online' : 'loaded') : 'connecting',
|
||||
'',
|
||||
);
|
||||
this.applyStatus();
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this.setStatus('error', this._error);
|
||||
@@ -281,24 +273,14 @@ export class HookSession extends EventEmitter {
|
||||
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', '');
|
||||
}
|
||||
// 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 {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
this.setStatus(this.injected ? 'disconnected' : 'available', '');
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
this.reconcilePipeDown();
|
||||
}
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
@@ -308,6 +290,55 @@ export class HookSession extends EventEmitter {
|
||||
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;
|
||||
}
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
this.applyStatus(wasLoggedIn);
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
}
|
||||
|
||||
// ─────────────── client plumbing ───────────────
|
||||
|
||||
private async attemptConnect(): Promise<void> {
|
||||
@@ -327,15 +358,26 @@ export class HookSession extends EventEmitter {
|
||||
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);
|
||||
// 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.
|
||||
this.startLoginReconcile();
|
||||
}
|
||||
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.
|
||||
// A failed connect was never logged in → 'connecting' (or 'available').
|
||||
this.tearDownClient();
|
||||
this.setStatus(this.injected ? 'connecting' : 'available', this._error);
|
||||
this.applyStatus(false, this._error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,21 +397,13 @@ export class HookSession extends EventEmitter {
|
||||
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);
|
||||
this.reconcilePipeDown();
|
||||
}).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
});
|
||||
}
|
||||
|
||||
private tearDownClient(): void {
|
||||
this.stopLoginReconcile();
|
||||
const client = this.client;
|
||||
if (client) {
|
||||
client.removeAllListeners();
|
||||
@@ -387,11 +421,18 @@ export class HookSession extends EventEmitter {
|
||||
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();
|
||||
|
||||
if (this.loggedIn) {
|
||||
this.setStatus('online', '');
|
||||
} else if (this.connected) {
|
||||
this.setStatus('loaded', this._error);
|
||||
// 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;
|
||||
@@ -401,6 +442,55 @@ export class HookSession extends EventEmitter {
|
||||
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
|
||||
}
|
||||
|
||||
// ─────────────── 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).
|
||||
this.handleLoginState({ 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;
|
||||
@@ -429,11 +519,6 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
31
packages/bridge/src/hook-status.ts
Normal file
31
packages/bridge/src/hook-status.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
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';
|
||||
}
|
||||
@@ -2,6 +2,8 @@ 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 {
|
||||
@@ -98,6 +100,17 @@ 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())]
|
||||
|
||||
@@ -6,8 +6,11 @@ const DEFAULT_INTERVAL_MS = 1500;
|
||||
const MIN_INTERVAL_MS = 250;
|
||||
|
||||
export type PipeWatcherDeps = {
|
||||
/** Native: list QQ.exe processes currently running. */
|
||||
listProcesses: () => HookProcessBaseInfo[];
|
||||
/** Native: list QQ.exe processes currently running. May be async and may
|
||||
* return `null` (UNKNOWN) when enumeration timed out / failed — in which
|
||||
* case this tick keeps the prior process+pipe state instead of treating the
|
||||
* missing data as "everything disappeared" (issue #158). */
|
||||
listProcesses: () => HookProcessBaseInfo[] | null | Promise<HookProcessBaseInfo[] | null>;
|
||||
/** Native: PIDs that currently have a live SnowLuma named pipe. */
|
||||
listLivePipes: () => Promise<Set<number>>;
|
||||
/** Polling interval in ms. Defaults to 1500, floored to 250. */
|
||||
@@ -138,12 +141,22 @@ export class PipeWatcher extends EventEmitter {
|
||||
}
|
||||
this.ticking = true;
|
||||
try {
|
||||
let processes: HookProcessBaseInfo[];
|
||||
let processes: HookProcessBaseInfo[] | null;
|
||||
try {
|
||||
processes = this.listProcesses();
|
||||
processes = await this.listProcesses();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
processes = [];
|
||||
processes = null;
|
||||
}
|
||||
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
|
||||
// Treating missing data as "everything disappeared" would fire
|
||||
// process-gone for every live PID and dispose healthy sessions — the
|
||||
// freeze-then-teardown footgun behind issue #158. Still emit 'tick' so
|
||||
// the manager's per-tick reconnect retries keep running off last-known
|
||||
// live pipes.
|
||||
if (processes === null) {
|
||||
this.emit('tick');
|
||||
return;
|
||||
}
|
||||
let livePipes: Set<number>;
|
||||
try {
|
||||
|
||||
238
packages/bridge/src/process-enumerator.ts
Normal file
238
packages/bridge/src/process-enumerator.ts
Normal file
@@ -0,0 +1,238 @@
|
||||
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,5 +1,5 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { promises as fs } from 'fs';
|
||||
import { readdirSync, promises as fs } from 'fs';
|
||||
import net from 'net';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
@@ -85,12 +85,59 @@ 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;
|
||||
// Mirrors hook_stub.cpp runtime_dir() fallback.
|
||||
// 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.
|
||||
// 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}`;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { exec } from 'child_process';
|
||||
import net from 'net';
|
||||
import http from 'http';
|
||||
import https from 'https';
|
||||
import { promisify } from 'util';
|
||||
|
||||
@@ -126,51 +127,61 @@ interface PtloginUin {
|
||||
nickname?: string;
|
||||
}
|
||||
|
||||
async function fetchPtlogin(port: number): Promise<PtloginUin[]> {
|
||||
/**
|
||||
* 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 url = `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
|
||||
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 req = https.get(
|
||||
url,
|
||||
{
|
||||
headers: {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
},
|
||||
rejectUnauthorized: false, // 忽略本地自签证书报错
|
||||
timeout: CONNECTION_TIMEOUT_MS,
|
||||
},
|
||||
(res) => {
|
||||
let text = '';
|
||||
res.on('data', (chunk) => { text += chunk.toString(); });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
// 100% 复刻 Python 切片逻辑:获取两个方括号中间的字符串,再包装成数组
|
||||
const inner = text.split('[')[1].split(']')[0];
|
||||
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
|
||||
resolve(data);
|
||||
} catch {
|
||||
resolve([]);
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
const headers = {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
};
|
||||
|
||||
req.on('error', () => resolve([]));
|
||||
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([]);
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
|
||||
// 抽象的 QQNT
|
||||
const res1 = await fetchPtlogin(port);
|
||||
const res2 = await fetchPtlogin(port);
|
||||
const useHttps = port % 2 !== 0;
|
||||
|
||||
const target = res1.length < res2.length ? res1 : res2;
|
||||
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];
|
||||
@@ -182,8 +193,6 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
|
||||
};
|
||||
}
|
||||
|
||||
// Any non-1 result — the 2+0 alternation, both-2, both-empty, etc. — is
|
||||
// inconclusive; hand off to the deep-link / process-count fallback.
|
||||
return 'fallback';
|
||||
}
|
||||
|
||||
@@ -250,12 +259,21 @@ export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | n
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
|
||||
|
||||
const PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const matchedPtPorts = ports.filter(p => PT_PORTS.includes(p));
|
||||
const matchedOddPorts = ports.filter(p => ODD_PT_PORTS.includes(p));
|
||||
const matchedEvenPorts = ports.filter(p => EVEN_PT_PORTS.includes(p));
|
||||
|
||||
if (matchedPtPorts.length > 0) {
|
||||
for (const port of matchedPtPorts) {
|
||||
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;
|
||||
|
||||
173
packages/bridge/tests/hook-manager-state-notify.test.ts
Normal file
173
packages/bridge/tests/hook-manager-state-notify.test.ts
Normal file
@@ -0,0 +1,173 @@
|
||||
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;
|
||||
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(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
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,
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ 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 { QqPortLoginInfo } from '../src/qq-port-probe';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
@@ -42,6 +43,7 @@ function makeSession(opts: {
|
||||
pipeLive?: boolean;
|
||||
clientFailsConnect?: boolean;
|
||||
onPacket?: PacketSink;
|
||||
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
|
||||
} = {}) {
|
||||
const pid = opts.pid ?? 1234;
|
||||
let pipeLive = opts.pipeLive ?? false;
|
||||
@@ -50,6 +52,9 @@ function makeSession(opts: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
};
|
||||
// Default probe reports "not logged in" so the reconcile safety net is inert
|
||||
// unless a test opts into a logged-in probe (never hits the real port scan).
|
||||
const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', loggedIn: false }));
|
||||
|
||||
const session = new HookSession(pid, {
|
||||
injector,
|
||||
@@ -60,6 +65,7 @@ function makeSession(opts: {
|
||||
// Cast: FakeClient mirrors only the surface HookSession touches.
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
probeLogin,
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
onPacket: opts.onPacket,
|
||||
});
|
||||
@@ -347,6 +353,95 @@ describe('HookSession — process gone', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — refresh drift fix', () => {
|
||||
// refresh while the pipe is down on a connected-but-never-logged-in
|
||||
// session now reports 'connecting' (matching what onPipeDown gives for the
|
||||
// same state), not the old spurious 'disconnected'. Pre-refactor, refresh's
|
||||
// down branch ignored wasLoggedIn and always reported 'disconnected'.
|
||||
|
||||
it('refresh-while-down + never logged in → connecting (not disconnected), no disconnect emit', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
expect(ctx.session.status).toBe('loaded'); // connected, never logged in
|
||||
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
ctx.setPipeLive(false);
|
||||
|
||||
const info = await ctx.session.refresh();
|
||||
|
||||
expect(info.status).toBe('connecting'); // drift fix: was 'disconnected'
|
||||
expect(discSpy).not.toHaveBeenCalled(); // never logged in ⇒ nothing owed
|
||||
});
|
||||
|
||||
it('refresh-while-down after login still → disconnected + emits disconnected(true)', async () => {
|
||||
// The flip is scoped to the never-logged-in case; a real session that
|
||||
// had reached login must still settle to 'disconnected' and notify.
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
expect(ctx.session.status).toBe('online');
|
||||
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
ctx.setPipeLive(false);
|
||||
|
||||
const info = await ctx.session.refresh();
|
||||
|
||||
expect(info.status).toBe('disconnected');
|
||||
expect(discSpy).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — pipe-down must not clobber a settled error', () => {
|
||||
// Regression net for the phase-2 reconcilePipeDown !connected short-circuit:
|
||||
// a pipe-down tick on a session that never reached a live connection must
|
||||
// not wipe a diagnostic error or emit a spurious status-changed.
|
||||
|
||||
it('onPipeDown after a failed connect keeps the error and does not re-emit', 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');
|
||||
|
||||
const statusSpy = vi.fn();
|
||||
ctx.session.on('status-changed', statusSpy);
|
||||
ctx.session.onPipeDown();
|
||||
await flush();
|
||||
|
||||
expect(ctx.session.status).toBe('connecting');
|
||||
expect(ctx.session.error).toBe('connect failed'); // not wiped to ''
|
||||
expect(statusSpy).not.toHaveBeenCalled(); // no spurious emit
|
||||
});
|
||||
|
||||
it('onPipeDown after a failed load leaves the error status intact', 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 },
|
||||
});
|
||||
await session.load();
|
||||
expect(session.status).toBe('error');
|
||||
expect(session.error).toBe('inject boom');
|
||||
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
|
||||
expect(session.status).toBe('error'); // not flipped to 'available'
|
||||
expect(session.error).toBe('inject boom'); // not wiped
|
||||
});
|
||||
});
|
||||
|
||||
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
|
||||
@@ -444,3 +539,136 @@ describe('HookSession — packet forwarding', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
|
||||
it('reconciles login via the active probe when the pushed frame is missed', async () => {
|
||||
// Probe reports logged-in; the FakeClient never fires a loginState frame
|
||||
// (the missed-edge Docker case). The immediate reconcile probe must detect
|
||||
// it and emit "login".
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); // connect (not logged in via frame) → starts reconcile
|
||||
await flush(); // immediate probe resolves → handleLoginState
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
expect(loginSpy.mock.calls[0]![0]).toBe('10001');
|
||||
expect(ctx.session.status).toBe('online');
|
||||
expect(ctx.session.uin).toBe('10001');
|
||||
});
|
||||
|
||||
it('does not log in when the probe reports not-logged-in', async () => {
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 0, uin: '', loggedIn: false }),
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); await flush();
|
||||
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
});
|
||||
|
||||
it('ignores a probe with a non-real uin (0)', async () => {
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '0', loggedIn: true }),
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); await flush();
|
||||
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('tolerates a throwing probe (best-effort, no crash/login)', async () => {
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => { throw new Error('port scan failed'); },
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); await flush();
|
||||
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
});
|
||||
|
||||
it('detects a login that lands on a LATER interval probe', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let loggedIn = false;
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn }),
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet)
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
|
||||
loggedIn = true; // QQ finishes auto-login
|
||||
await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
expect(ctx.session.status).toBe('online');
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not double-emit when the pushed frame logs in first', async () => {
|
||||
// Pushed-frame login wins; a subsequent probe with the same uin must not
|
||||
// re-emit (handleLoginState dedups), and the reconcile timer is stopped.
|
||||
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', loggedIn: true }));
|
||||
const ctx = makeSession({ pipeLive: true, probeLogin });
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001'); // pushed-frame login first
|
||||
await flush();
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
expect(ctx.session.status).toBe('online');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — login reconcile does not stack concurrent probes', () => {
|
||||
it('skips overlapping ticks while a slow probe is in flight', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
// A probe that never resolves — simulates a slow port scan spanning
|
||||
// multiple intervals. The in-flight guard must call it only once.
|
||||
const probeLogin = vi.fn(() => new Promise<never>(() => { /* pending */ }));
|
||||
const ctx = makeSession({ pipeLive: true, probeLogin });
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (starts, stays pending)
|
||||
await vi.advanceTimersByTimeAsync(9000); // 3 more interval ticks
|
||||
|
||||
expect(probeLogin).toHaveBeenCalledTimes(1); // not stacked
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
56
packages/bridge/tests/hook-status.test.ts
Normal file
56
packages/bridge/tests/hook-status.test.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -192,4 +192,40 @@ 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();
|
||||
});
|
||||
});
|
||||
|
||||
55
packages/bridge/tests/process-enumerator.test.ts
Normal file
55
packages/bridge/tests/process-enumerator.test.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
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,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.10.0",
|
||||
"version": "1.11.3",
|
||||
"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,6 +16,18 @@
|
||||
"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"
|
||||
@@ -43,6 +55,10 @@
|
||||
"./runtime": {
|
||||
"types": "./src/runtime.ts",
|
||||
"default": "./src/runtime.ts"
|
||||
},
|
||||
"./uin": {
|
||||
"types": "./src/uin.ts",
|
||||
"default": "./src/uin.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
30
packages/common/src/coerce.ts
Normal file
30
packages/common/src/coerce.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
// 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));
|
||||
}
|
||||
27
packages/common/src/concurrency.ts
Normal file
27
packages/common/src/concurrency.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
@@ -175,7 +175,7 @@ function render(level: LogLevel, options: LogOptions, args: unknown[], 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(UIN_SLOT_WIDTH - uinTag.length)
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
|
||||
93
packages/common/src/single-flight-cache.ts
Normal file
93
packages/common/src/single-flight-cache.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
11
packages/common/src/uin.ts
Normal file
11
packages/common/src/uin.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
// 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);
|
||||
}
|
||||
78
packages/common/tests/coerce.test.ts
Normal file
78
packages/common/tests/coerce.test.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
68
packages/common/tests/concurrency.test.ts
Normal file
68
packages/common/tests/concurrency.test.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
26
packages/common/tests/hex.test.ts
Normal file
26
packages/common/tests/hex.test.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
61
packages/common/tests/log-summary.test.ts
Normal file
61
packages/common/tests/log-summary.test.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { 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('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);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderParamsVerbose', () => {
|
||||
it('redacts token / password / secret keys at any depth', () => {
|
||||
const out = renderParamsVerbose({ token: 'abc', password: 'p', nested: { secret: 's' }, ok: 'v' });
|
||||
expect(out).toContain('token:"***"');
|
||||
expect(out).toContain('password:"***"');
|
||||
expect(out).toContain('secret:"***"');
|
||||
expect(out).toContain('ok:"v"');
|
||||
});
|
||||
|
||||
it('truncates long strings with a Unicode ellipsis + byte count (not ASCII dots)', () => {
|
||||
// The reported change-request: the marker is `…<N B>` (U+2026), not `...<N B>`.
|
||||
const out = renderParamsVerbose({ blob: 'a'.repeat(500) });
|
||||
expect(out).toContain('…<500B>');
|
||||
expect(out).not.toContain('...<500B>');
|
||||
});
|
||||
|
||||
it('guards against circular references', () => {
|
||||
const o: Record<string, unknown> = { a: 1 };
|
||||
o.self = o;
|
||||
expect(renderParamsVerbose(o)).toContain('"[circular]"');
|
||||
});
|
||||
|
||||
it('renders nested structure with primitives intact', () => {
|
||||
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
|
||||
});
|
||||
});
|
||||
45
packages/common/tests/logger.test.ts
Normal file
45
packages/common/tests/logger.test.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// The file transport writes to disk; stub it so the test has no side effects.
|
||||
vi.mock('../src/log-file-transport', () => ({
|
||||
getFileTransport: () => ({ write: () => {} }),
|
||||
}));
|
||||
|
||||
import { createLogger } 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();
|
||||
});
|
||||
});
|
||||
34
packages/common/tests/request-context.test.ts
Normal file
34
packages/common/tests/request-context.test.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
131
packages/common/tests/single-flight-cache.test.ts
Normal file
131
packages/common/tests/single-flight-cache.test.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
40
packages/common/tests/uin.test.ts
Normal file
40
packages/common/tests/uin.test.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
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
Normal file
16
packages/core/config/.gitignore
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
# 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,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.10.0",
|
||||
"version": "1.11.3",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -54,7 +54,7 @@
|
||||
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||
"@types/node": "^24.12.2",
|
||||
"cross-env": "^10.1.0",
|
||||
"hono": "^4.12.21",
|
||||
"hono": "^4.12.25",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
|
||||
@@ -8,6 +8,7 @@ import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetc
|
||||
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
|
||||
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
|
||||
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
|
||||
import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache';
|
||||
import type {
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
@@ -55,16 +56,19 @@ const MEMBER_LIST_TTL_MS = 60_000;
|
||||
|
||||
export class ContactsApi {
|
||||
/**
|
||||
* Per-group inflight + last-fetch cache for `fetchGroupMemberList`.
|
||||
* Keyed by groupId, lives for the lifetime of the Bridge.
|
||||
* Per-group TTL + single-flight cache for `fetchGroupMemberList`, keyed by
|
||||
* groupId, living for the lifetime of the Bridge.
|
||||
*
|
||||
* Without this, a busy OneBot client (e.g. MaiBot calling
|
||||
* `get_group_member_info` once per inbound message) triggers one
|
||||
* OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips
|
||||
* Tencent risk-control and gets the account banned for 7 days.
|
||||
*/
|
||||
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
|
||||
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
|
||||
private readonly memberListCache: SingleFlightCache<number, GroupMemberInfo[]> =
|
||||
createSingleFlightCache({
|
||||
ttlMs: MEMBER_LIST_TTL_MS,
|
||||
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
|
||||
});
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
@@ -111,6 +115,10 @@ export class ContactsApi {
|
||||
memberCount: raw.info?.memberCount ?? 0,
|
||||
memberMax: raw.info?.memberMax ?? 0,
|
||||
members: new Map(),
|
||||
// #197: the list already carries these — no extra fetch needed. `level`
|
||||
// is not in the list (0x88D_0 detail only), so it stays undefined here.
|
||||
createTime: raw.info?.createdTime ?? 0,
|
||||
memo: raw.info?.announcement || raw.info?.description || '',
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroups(groups);
|
||||
@@ -136,31 +144,19 @@ export class ContactsApi {
|
||||
memberCount: Number(r.memberCount ?? 0n),
|
||||
memberMax: Number(r.maxMemberCount ?? 0n),
|
||||
members: new Map(),
|
||||
// #197: the detail is the only source of `level`; it also carries
|
||||
// createTime + the notice preview (memo).
|
||||
createTime: Number(r.createTime ?? 0n),
|
||||
level: Number(r.level ?? 0n),
|
||||
memo: r.noticePreview ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
async fetchGroupMemberList(
|
||||
fetchGroupMemberList(
|
||||
groupId: number,
|
||||
options: { force?: boolean } = {},
|
||||
): Promise<GroupMemberInfo[]> {
|
||||
const now = Date.now();
|
||||
const last = this.memberListLastFetch.get(groupId);
|
||||
if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) {
|
||||
return last.data;
|
||||
}
|
||||
const inflight = this.memberListInflight.get(groupId);
|
||||
if (inflight) return inflight;
|
||||
const task = (async () => {
|
||||
try {
|
||||
const data = await this.fetchGroupMemberListUncached(groupId);
|
||||
this.memberListLastFetch.set(groupId, { at: Date.now(), data });
|
||||
return data;
|
||||
} finally {
|
||||
this.memberListInflight.delete(groupId);
|
||||
}
|
||||
})();
|
||||
this.memberListInflight.set(groupId, task);
|
||||
return task;
|
||||
return this.memberListCache.get(groupId, { force: options.force });
|
||||
}
|
||||
|
||||
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
|
||||
@@ -232,6 +228,13 @@ export class ContactsApi {
|
||||
return requests;
|
||||
}
|
||||
|
||||
/** The approval msgseq captured from a private "qun.invite" card for this
|
||||
* group, or undefined if none was seen. `set_group_add_request` uses it to
|
||||
* approve a bot self-invite via 0x10c8 (eventType=2). See issue #125. */
|
||||
getGroupInviteCardSequence(groupId: number): number | undefined {
|
||||
return this.ctx.identity.getGroupInviteCardSequence(groupId);
|
||||
}
|
||||
|
||||
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
|
||||
const resp = await FetchDownloadRkeys.invoke(this.ctx);
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@ import {
|
||||
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
|
||||
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
|
||||
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
@@ -28,15 +31,6 @@ export interface PttTransInput {
|
||||
fileId?: number;
|
||||
}
|
||||
|
||||
function hexToBytes(hex: string): Uint8Array {
|
||||
const s = (hex || '').trim();
|
||||
if (!s) return new Uint8Array(0);
|
||||
const len = s.length >> 1;
|
||||
const out = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) out[i] = parseInt(s.substr(i * 2, 2), 16);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ─────────────── public types (re-exported from bridge.ts as before) ───
|
||||
|
||||
export type StrangerStatus = NamespaceStrangerStatus;
|
||||
@@ -55,6 +49,8 @@ export interface AiVoiceItem {
|
||||
voiceExampleUrl: string;
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge.Extras');
|
||||
|
||||
export class ExtrasApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
@@ -126,10 +122,13 @@ export class ExtrasApi {
|
||||
* already-transcribed case). For a freshly-received voice the response is an
|
||||
* empty ack and the text is delivered later via the async Event 0x210
|
||||
* subType-61 push — callers should treat `''` as "pending" and wait for the
|
||||
* `ptt_trans_result` event (correlated by msgId). Live-verified end to end.
|
||||
* `ptt_trans_result` event (correlated by msgId).
|
||||
*/
|
||||
async translatePttToText(input: PttTransInput): Promise<string> {
|
||||
const md5 = hexToBytes(input.md5Hex);
|
||||
// QQ NT sends the md5 as a 32-char lowercase HEX STRING, not the raw 16
|
||||
// bytes (RE'd from wrapper.linux.node EncodeTroopPtt/EncodeC2CPtt: the md5
|
||||
// field goes through a bytes→hex helper). Sending raw bytes → errCode -1079.
|
||||
const md5 = input.md5Hex.toLowerCase();
|
||||
const req: PttTransReq = input.isGroup
|
||||
? {
|
||||
type: 1,
|
||||
@@ -154,7 +153,32 @@ export class ExtrasApi {
|
||||
}
|
||||
const resp = protobuf_decode<PttTransResp>(result.responseData);
|
||||
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
|
||||
if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`);
|
||||
if (item?.errCode) {
|
||||
// Diagnostic (#165 备选): correlate QQ's errCode with the request fields we
|
||||
// sourced from cache, to tell a server-side ASR failure apart from our own
|
||||
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
|
||||
log.warn(
|
||||
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
|
||||
item.errCode, input.isGroup,
|
||||
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
|
||||
input.format, input.uuid ? 'set' : 'EMPTY', input.duration, input.size,
|
||||
);
|
||||
throw new Error(`ptt translate failed: error=${item.errCode}`);
|
||||
}
|
||||
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
|
||||
}
|
||||
|
||||
/**
|
||||
* Transcode a voice record (`get_record out_format`, #165). `source` is a
|
||||
* URL / local path / `base64://…` (the record's download URL in practice);
|
||||
* it is loaded then transcoded to `format` via the bundled SILK-capable
|
||||
* ffmpeg addon. Returns base64 + size. Throws on unsupported format or a
|
||||
* failed conversion.
|
||||
*/
|
||||
async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> {
|
||||
// Voices are tiny — cap the download well below loadBinarySource's 1 GiB
|
||||
// default so a tampered/oversized source can't be pulled in.
|
||||
const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024);
|
||||
return convertAudioBytes(bytes, format);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// 复用 OIDB 基础设施(invokeOidb),协议层在 @snowluma/protocol/oidb-services/flash-transfer/。
|
||||
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { resolveSelfUid } from './shared';
|
||||
import type { FlashFileEntry } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
|
||||
import { GetFilesetDetail } from '@snowluma/protocol/oidb-services/flash-transfer/get-fileset-detail';
|
||||
import { ListFilesets } from '@snowluma/protocol/oidb-services/flash-transfer/list-filesets';
|
||||
@@ -276,7 +277,9 @@ export class FlashTransferApi {
|
||||
const uploader = {
|
||||
uin: this.ctx.identity.uin,
|
||||
nickname: this.ctx.identity.nickname,
|
||||
uid: this.ctx.identity.selfUid ?? '',
|
||||
// Resolve our own uid rather than ship an empty one — a blank uploader
|
||||
// uid drops the fileset if this runs before warmup populated selfUid.
|
||||
uid: await resolveSelfUid(this.ctx),
|
||||
};
|
||||
// 读取所有文件,每个分配 fileUuid + 序号 + formatCode
|
||||
const items: { bytes: Uint8Array; fileName: string; fileUuid: string; fileIndex: number; formatCode: number }[] = [];
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import type {
|
||||
LongMsgResult,
|
||||
RecvLongMsgReq,
|
||||
@@ -14,7 +15,7 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { gunzipSync, gzipSync } from 'zlib';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
|
||||
import { resolveSelfUid, toInt } from './shared';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
@@ -24,6 +25,17 @@ function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge;
|
||||
// resolve a forward immediately after receiving the parent message.
|
||||
const forwardResCache = new Map<string, ForwardNodePayload[]>();
|
||||
|
||||
/** QQ's placeholder when it doesn't hand back a real sender name — treated as
|
||||
* "missing" so #174's enrichment resolves the real nickname. */
|
||||
const FORWARD_NAME_PLACEHOLDER = 'QQ用户';
|
||||
|
||||
/** Bounds on the L4 (per-uin profile) fallback when enriching forward senders.
|
||||
* Profile lookups are un-cached single-point OIDB calls Tencent rate-limits
|
||||
* aggressively, so cap how many distinct uins one forward resolves and how
|
||||
* many run at once — the rest keep the placeholder. */
|
||||
const FORWARD_PROFILE_MAX = 20;
|
||||
const FORWARD_PROFILE_CONCURRENCY = 4;
|
||||
|
||||
// Per-layer piggyback entry. Each level of a nested forward attaches
|
||||
// its own msgBody under a uuid `actionCommand`, so when the receiver
|
||||
// fetches the outermost res_id it gets every layer in one shot
|
||||
@@ -139,7 +151,9 @@ async function buildForwardPushBody(
|
||||
return {
|
||||
responseHead: {
|
||||
fromUin,
|
||||
toUid: bridge.identity.selfUid ?? '',
|
||||
// Resolve our own uid rather than ship an empty one — a blank toUid is a
|
||||
// broken packet if this runs before warmup populated selfUid.
|
||||
toUid: await resolveSelfUid(bridge),
|
||||
forward: {
|
||||
friendName: nickname,
|
||||
},
|
||||
@@ -202,6 +216,46 @@ function previewFromElements(elements: MessageElement[]): string {
|
||||
return '';
|
||||
}
|
||||
|
||||
function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload {
|
||||
return {
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements,
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
innerForward: node.innerForward,
|
||||
};
|
||||
}
|
||||
|
||||
function stripFileSource(element: MessageElement): MessageElement {
|
||||
const next: MessageElement = { ...element };
|
||||
delete next.url;
|
||||
return next;
|
||||
}
|
||||
|
||||
function isCachedFileUsableInTarget(
|
||||
cached: UploadedFileMeta | undefined,
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): boolean {
|
||||
if (!cached) return true;
|
||||
if (groupId !== undefined) {
|
||||
return cached.scope === 'group' && cached.groupId === groupId;
|
||||
}
|
||||
if (userId !== undefined) {
|
||||
return cached.scope === 'private' && cached.userId === userId;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function fileNameForUpload(element: MessageElement, cached?: UploadedFileMeta): string {
|
||||
return (element.fileName ?? cached?.fileName ?? '').trim();
|
||||
}
|
||||
|
||||
export class ForwardApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
@@ -210,6 +264,101 @@ export class ForwardApi {
|
||||
return resId;
|
||||
}
|
||||
|
||||
private async downloadSourceFromCachedFile(cached: UploadedFileMeta): Promise<string> {
|
||||
if (cached.scope === 'group' && cached.groupId !== undefined) {
|
||||
return this.ctx.apis.groupFile.getUrl(cached.groupId, cached.fileId);
|
||||
}
|
||||
if (cached.scope === 'private' && cached.userId !== undefined && cached.fileHash) {
|
||||
return this.ctx.apis.groupFile.getPrivateUrl(cached.userId, cached.fileId, cached.fileHash);
|
||||
}
|
||||
throw new Error('forward file_id belongs to another scope; pass file/base64/url so SnowLuma can re-upload it');
|
||||
}
|
||||
|
||||
private async uploadForwardFileSource(
|
||||
source: string,
|
||||
name: string,
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<MessageElement> {
|
||||
if (groupId !== undefined) {
|
||||
const uploaded = await this.ctx.apis.groupFile.upload(groupId, source, name, '/', true, false);
|
||||
if (!uploaded.fileId) throw new Error('forward group file upload returned no file_id');
|
||||
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
|
||||
const element: MessageElement = {
|
||||
type: 'file',
|
||||
fileId: uploaded.fileId,
|
||||
};
|
||||
const fileName = cached?.fileName || name;
|
||||
if (fileName) element.fileName = fileName;
|
||||
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
|
||||
return element;
|
||||
}
|
||||
if (userId !== undefined) {
|
||||
const uploaded = await this.ctx.apis.groupFile.uploadPrivate(userId, source, name, true, false);
|
||||
if (!uploaded.fileId) throw new Error('forward private file upload returned no file_id');
|
||||
const cached = this.ctx.recallUploadedFile(uploaded.fileId);
|
||||
const element: MessageElement = {
|
||||
type: 'file',
|
||||
fileId: uploaded.fileId,
|
||||
};
|
||||
const fileName = cached?.fileName || name;
|
||||
const fileHash = uploaded.fileHash ?? cached?.fileHash ?? '';
|
||||
if (fileName) element.fileName = fileName;
|
||||
if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize;
|
||||
if (fileHash) element.fileHash = fileHash;
|
||||
return element;
|
||||
}
|
||||
throw new Error('forward file source requires group_id or user_id');
|
||||
}
|
||||
|
||||
private async prepareForwardFileElement(
|
||||
element: MessageElement,
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<MessageElement> {
|
||||
if (element.type !== 'file') return element;
|
||||
|
||||
const source = (element.url ?? '').trim();
|
||||
if (source && !element.fileId) {
|
||||
const uploaded = await this.uploadForwardFileSource(source, fileNameForUpload(element), groupId, userId);
|
||||
return {
|
||||
...stripFileSource(element),
|
||||
...uploaded,
|
||||
};
|
||||
}
|
||||
|
||||
if (element.fileId) {
|
||||
const cached = this.ctx.recallUploadedFile(element.fileId);
|
||||
if (isCachedFileUsableInTarget(cached, groupId, userId)) return element;
|
||||
const sourceFromCache = await this.downloadSourceFromCachedFile(cached!);
|
||||
const uploaded = await this.uploadForwardFileSource(
|
||||
sourceFromCache,
|
||||
fileNameForUpload(element, cached),
|
||||
groupId,
|
||||
userId,
|
||||
);
|
||||
return {
|
||||
...stripFileSource(element),
|
||||
...uploaded,
|
||||
};
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
private async prepareForwardFiles(
|
||||
nodes: ForwardNodePayload[],
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<ForwardNodePayload[]> {
|
||||
return Promise.all(nodes.map(async (node) => {
|
||||
const elements = await Promise.all(node.elements.map(
|
||||
element => this.prepareForwardFileElement(element, groupId, userId),
|
||||
));
|
||||
return cloneNodeWithElements(node, elements);
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive upload with NapCat-style piggyback. Each invocation:
|
||||
* 1. Walks `nodes`. For any node whose `innerForward` is set,
|
||||
@@ -304,8 +453,10 @@ export class ForwardApi {
|
||||
}
|
||||
}
|
||||
|
||||
const uploadReadyNodes = await this.prepareForwardFiles(processedNodes, groupId, userId);
|
||||
|
||||
// Encode this level's msgBody.
|
||||
const msgBody = await Promise.all(processedNodes.map(
|
||||
const msgBody = await Promise.all(uploadReadyNodes.map(
|
||||
node => buildForwardPushBody(bridge, node, groupId, userUid),
|
||||
));
|
||||
|
||||
@@ -349,7 +500,7 @@ export class ForwardApi {
|
||||
throw new Error('upload forward message response missing res_id');
|
||||
}
|
||||
|
||||
forwardResCache.set(resId, processedNodes.map(node => ({
|
||||
forwardResCache.set(resId, uploadReadyNodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
@@ -381,7 +532,7 @@ export class ForwardApi {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cached = forwardResCache.get(resId);
|
||||
if (cached) {
|
||||
return cached.map(node => ({
|
||||
const nodes = cached.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
@@ -392,6 +543,10 @@ export class ForwardApi {
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
}));
|
||||
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
|
||||
// on read (a no-op once names are present) and persist so later hits skip.
|
||||
if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes));
|
||||
return nodes;
|
||||
}
|
||||
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
@@ -451,12 +606,94 @@ export class ForwardApi {
|
||||
this.consumePiggybacks(nodes, piggybackByUuid);
|
||||
}
|
||||
|
||||
// Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty
|
||||
// or stamped with the "QQ用户" placeholder (#174) — the long-msg member name
|
||||
// isn't always populated, and the sync decode only consults the L1 cache.
|
||||
await this.enrichSenders(nodes);
|
||||
|
||||
if (nodes.length > 0) {
|
||||
forwardResCache.set(resId, cloneNodes(nodes));
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/** A node whose display name the server didn't give us (empty or the QQ
|
||||
* placeholder) and that we can resolve (has a uin). */
|
||||
private needsName(n: ForwardNodePayload): boolean {
|
||||
return !!n.userUin && (!n.nickname || n.nickname === FORWARD_NAME_PLACEHOLDER);
|
||||
}
|
||||
|
||||
/** Backfill sender nickname/card on forward nodes the long-msg payload left
|
||||
* nameless. Resolves group senders via one member-list fetch per group (L3,
|
||||
* inflight+TTL cached in ContactsApi), then any residue + private nodes via
|
||||
* the user-profile lookup (L4). Best-effort: a failed lookup keeps the
|
||||
* placeholder rather than failing the whole forward. Returns true if any
|
||||
* node was changed (so callers can persist the enriched cache). */
|
||||
private async enrichSenders(nodes: ForwardNodePayload[]): Promise<boolean> {
|
||||
const pending = nodes.filter(n => this.needsName(n));
|
||||
if (pending.length === 0) return false;
|
||||
let changed = false;
|
||||
|
||||
// L3 — group member lists (one fetch resolves every sender from that group).
|
||||
const byGroup = new Map<number, ForwardNodePayload[]>();
|
||||
const residue: ForwardNodePayload[] = [];
|
||||
for (const n of pending) {
|
||||
if (n.messageType === 'group' && n.groupId) {
|
||||
const arr = byGroup.get(n.groupId) ?? [];
|
||||
arr.push(n);
|
||||
byGroup.set(n.groupId, arr);
|
||||
} else {
|
||||
residue.push(n);
|
||||
}
|
||||
}
|
||||
for (const [groupId, groupNodes] of byGroup) {
|
||||
let byUin: Map<number, { nickname: string; card: string }>;
|
||||
try {
|
||||
const members = await this.ctx.apis.contacts.fetchGroupMemberList(groupId);
|
||||
byUin = new Map(members.map(m => [m.uin, { nickname: m.nickname, card: m.card }]));
|
||||
} catch {
|
||||
// Member list (one cheap, cached call) failed — keep the placeholder
|
||||
// rather than fanning the whole group out to per-uin profile lookups.
|
||||
// That error path is exactly what would amplify into a rate-limit ban.
|
||||
continue;
|
||||
}
|
||||
for (const n of groupNodes) {
|
||||
const m = byUin.get(n.userUin);
|
||||
const name = m?.card || m?.nickname;
|
||||
if (name) {
|
||||
n.senderCard = m!.card || n.senderCard || '';
|
||||
n.nickname = name;
|
||||
changed = true;
|
||||
} else {
|
||||
residue.push(n); // in-group sender that left the group → profile fallback
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// L4 — user profile for the residue (members who left the group, private
|
||||
// nodes). fetchUserProfile is an un-cached single-point OIDB 0xFE1_2, and
|
||||
// Tencent rate-limits these hard (see ContactsApi's member-list note), so:
|
||||
// dedupe by uin, CAP the count (drop the rest to placeholder), and resolve
|
||||
// in small concurrency-limited batches. Best-effort.
|
||||
const uins = [...new Set(residue.filter(n => this.needsName(n)).map(n => n.userUin))]
|
||||
.slice(0, FORWARD_PROFILE_MAX);
|
||||
if (uins.length > 0) {
|
||||
const byUin = new Map<number, string>();
|
||||
const results = await mapWithConcurrency(uins, FORWARD_PROFILE_CONCURRENCY,
|
||||
async (uin): Promise<readonly [number, string]> => {
|
||||
try { return [uin, (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname] as const; }
|
||||
catch { return [uin, ''] as const; }
|
||||
});
|
||||
for (const [uin, nick] of results) byUin.set(uin, nick);
|
||||
for (const n of residue) {
|
||||
if (!this.needsName(n)) continue;
|
||||
const nick = byUin.get(n.userUin);
|
||||
if (nick) { n.nickname = nick; changed = true; }
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** Walk a list of PushMsgBody, run each through the regular msg-push
|
||||
* pipeline, and shape the result into ForwardNodePayloads. Extracted
|
||||
* so both the outer + piggyback decode paths share one implementation. */
|
||||
@@ -479,6 +716,9 @@ export class ForwardApi {
|
||||
if (!event) continue;
|
||||
|
||||
if (event.kind === 'group_message') {
|
||||
// [#201] The merged-forward sender name now comes through the group
|
||||
// decoder (event.senderNick), which reads grp.memberCard (field 4) when
|
||||
// there's no member cache — exactly the forward-node case.
|
||||
out.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderCard || event.senderNick,
|
||||
|
||||
@@ -35,8 +35,8 @@ export class GroupAdminApi {
|
||||
return SetAddOption.invoke(this.ctx, { groupId, addType });
|
||||
}
|
||||
|
||||
setSearch(groupId: number): Promise<void> {
|
||||
return SetSearch.invoke(this.ctx, { groupId });
|
||||
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
|
||||
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
|
||||
}
|
||||
|
||||
setAddRequest(
|
||||
@@ -54,8 +54,26 @@ export class GroupAdminApi {
|
||||
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
|
||||
}
|
||||
|
||||
leave(groupId: number): Promise<void> {
|
||||
return LeaveGroup.invoke(this.ctx, { groupId });
|
||||
async leave(groupId: number): Promise<void> {
|
||||
await LeaveGroup.invoke(this.ctx, { groupId });
|
||||
// The server doesn't push a member-decrease back to the member who left of
|
||||
// its own accord, so synthesize the self group_member_leave here — otherwise
|
||||
// downstream never sees notice.group_decrease and keeps a "zombie" group in
|
||||
// its cache (#133). Also drop the group from our own roster.
|
||||
const selfUin = Number(this.ctx.identity.uin) || 0;
|
||||
const selfUid = this.ctx.identity.selfUid ?? '';
|
||||
await this.ctx.events.emit({
|
||||
kind: 'group_member_leave',
|
||||
time: Math.floor(Date.now() / 1000),
|
||||
selfUin,
|
||||
groupId,
|
||||
userUin: selfUin,
|
||||
operatorUin: selfUin,
|
||||
userUid: selfUid,
|
||||
operatorUid: selfUid,
|
||||
leaveType: 'leave',
|
||||
});
|
||||
this.ctx.identity.forgetGroup(groupId);
|
||||
}
|
||||
|
||||
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { toHexUpper } from '@snowluma/common/hex';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { FileChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { FILE_UPLOAD_MAX_BYTES } from '@snowluma/protocol/highway/utils';
|
||||
import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
|
||||
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { promises as fsp } from 'fs';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
|
||||
@@ -12,6 +15,7 @@ import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/c
|
||||
import { DeleteGroupFile } from '@snowluma/protocol/oidb-services/group-file/delete-group-file';
|
||||
import { DeleteGroupFolder } from '@snowluma/protocol/oidb-services/group-file/delete-group-folder';
|
||||
import { GetGroupFileCount } from '@snowluma/protocol/oidb-services/group-file/get-group-file-count';
|
||||
import { GetGroupFileSpace } from '@snowluma/protocol/oidb-services/group-file/get-group-file-space';
|
||||
import { GetGroupFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-file-url';
|
||||
import { GetGroupPttUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-ptt-url';
|
||||
import { GetGroupVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-video-url';
|
||||
@@ -23,6 +27,7 @@ import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-
|
||||
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
|
||||
import { RenameGroupFile } from '@snowluma/protocol/oidb-services/group-file/rename-group-file';
|
||||
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
|
||||
import { TransGroupFile, type TransGroupFileResult } from '@snowluma/protocol/oidb-services/group-file/trans-group-file';
|
||||
import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request';
|
||||
import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request';
|
||||
import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
|
||||
@@ -100,9 +105,20 @@ function normalizeUploadFileName(name: string, fallback: string): string {
|
||||
return safeFallback || 'file.bin';
|
||||
}
|
||||
|
||||
function md5First10MB(bytes: Uint8Array): Uint8Array {
|
||||
const limit = Math.min(bytes.length, 10 * 1024 * 1024);
|
||||
return computeMd5(bytes.subarray(0, limit));
|
||||
// QQ's "first 10 MB" checksum uses the magic limit 0x98A000 (10002432) —
|
||||
// NOT 10*1024*1024 and not 10^7. Using the wrong limit makes the server's
|
||||
// first-block verification fail for files larger than 0x98A000, so the
|
||||
// offline file uploads but never finalises as downloadable (#157).
|
||||
const MD5_HEAD_LIMIT = 10002432;
|
||||
|
||||
/** Fail cleanly if the staged file changed since the streaming hash pass (a
|
||||
* local source mutated mid-send). The server's per-chunk md5 during the PUT is
|
||||
* the backstop; this is the cheap early check. */
|
||||
async function assertUnchanged(filePath: string, baseline: { size: number; mtimeMs: number }): Promise<void> {
|
||||
const now = await fsp.stat(filePath);
|
||||
if (now.size !== baseline.size || now.mtimeMs !== baseline.mtimeMs) {
|
||||
throw new Error('file source changed during send (mutated between hashing and upload)');
|
||||
}
|
||||
}
|
||||
|
||||
function buildGroupFileUploadExt(
|
||||
@@ -177,7 +193,12 @@ function buildPrivateFileUploadExt(
|
||||
unknown2: 1,
|
||||
entry: {
|
||||
busiBuff: {
|
||||
busId: 102,
|
||||
// #157: NapCat/Lagrange (and the QQ client, confirmed by packet
|
||||
// capture) emit a busiBuff with ONLY senderUin — no busId. A stale
|
||||
// busId:102 here made the offline-file server accept the highway
|
||||
// upload but never finalise it as downloadable once the file got
|
||||
// big (>5 MiB): the receiver saw the file but every download failed.
|
||||
// (The other half of that bug was the wrong md5-head limit above.)
|
||||
senderUin: BigInt(senderUin),
|
||||
receiverUin: 0n,
|
||||
groupCode: 0n,
|
||||
@@ -227,12 +248,21 @@ export class GroupFileApi {
|
||||
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
}
|
||||
|
||||
trans(groupId: number, fileId: string): Promise<TransGroupFileResult> {
|
||||
if (!fileId) throw new Error('trans requires fileId');
|
||||
return TransGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
}
|
||||
|
||||
// ─────────────── count ───────────────
|
||||
|
||||
getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> {
|
||||
return GetGroupFileCount.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
getSpace(groupId: number): Promise<{ usedSpace: number; totalSpace: number }> {
|
||||
return GetGroupFileSpace.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
// ─────────────── upload (3-stage: OIDB preflight → highway → publish) ───────────────
|
||||
|
||||
async upload(
|
||||
@@ -241,99 +271,113 @@ export class GroupFileApi {
|
||||
name = '',
|
||||
folderId = '/',
|
||||
uploadFile = true,
|
||||
publishFile = uploadFile,
|
||||
): Promise<UploadFileResult> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
|
||||
// so override the default 1 GiB cap with the protocol ceiling.
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('group file is empty');
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
|
||||
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
|
||||
// local disk path and stream-hash it — the (up to 4 GiB) file is never
|
||||
// buffered in RAM.
|
||||
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
|
||||
try {
|
||||
if (staged.fileSize === 0) throw new Error('group file is empty');
|
||||
|
||||
const fileName = normalizeUploadFileName(name, loaded.fileName);
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const fileName = normalizeUploadFileName(name, staged.fileName);
|
||||
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
|
||||
const hashes = await hashFileStreaming(staged.filePath);
|
||||
|
||||
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
|
||||
groupId,
|
||||
fileName,
|
||||
folderId: normalizeDirectory(folderId),
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
});
|
||||
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
|
||||
|
||||
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||
if (!fileId) throw new Error('group file upload response missing file_id');
|
||||
|
||||
// Remember the upload so a later `send_group_msg` carrying just the
|
||||
// file_id can route via `publish` without forcing the OneBot caller
|
||||
// to thread fileName/size/md5 separately. For groups the wire
|
||||
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
|
||||
// mainly for log-line correctness; the c2c counterpart in
|
||||
// `uploadPrivate` is where the cache is actually load-bearing.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
scope: 'group',
|
||||
groupId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
|
||||
|
||||
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|
||||
|| '';
|
||||
const uploadPort = toInt(upload.uploadPort);
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
throw new Error('group file upload host is invalid');
|
||||
}
|
||||
|
||||
const ext = buildGroupFileUploadExt(
|
||||
senderUin,
|
||||
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
|
||||
groupId,
|
||||
fileName,
|
||||
loaded.bytes.length,
|
||||
hashes.md5,
|
||||
folderId: normalizeDirectory(folderId),
|
||||
fileSize: staged.fileSize,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
});
|
||||
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
|
||||
|
||||
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||
if (!fileId) throw new Error('group file upload response missing file_id');
|
||||
|
||||
// Remember the upload so a later `send_group_msg` carrying just the
|
||||
// file_id can route via `publish` without forcing the OneBot caller
|
||||
// to thread fileName/size/md5 separately. For groups the wire
|
||||
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
|
||||
// mainly for log-line correctness; the c2c counterpart in
|
||||
// `uploadPrivate` is where the cache is actually load-bearing.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
|
||||
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
|
||||
uploadHost,
|
||||
uploadPort,
|
||||
);
|
||||
scope: 'group',
|
||||
groupId,
|
||||
fileName,
|
||||
fileSize: staged.fileSize,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
|
||||
}
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
|
||||
|
||||
// Stage 3: file is on the server, now publish it as a chat message.
|
||||
//
|
||||
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
|
||||
// the chat shows nothing. The publish step goes via a dedicated OIDB
|
||||
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
|
||||
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
|
||||
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the
|
||||
// caller opts out via `uploadFile=false` (treat that as "I only
|
||||
// wanted the slot allocated, hold the chat post"). Routes through
|
||||
// `this.publish` so tests can mock at the same Api boundary.
|
||||
if (uploadFile) {
|
||||
try {
|
||||
await this.publish(groupId, fileId);
|
||||
} catch (err) {
|
||||
// The bytes are already on the server and the fileId is valid —
|
||||
// fail loud but don't lose the upload result the action handler
|
||||
// committed to returning. Callers can still resolve the file by
|
||||
// id; they'll just have to re-publish it themselves.
|
||||
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId, err instanceof Error ? err.message : String(err));
|
||||
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|
||||
|| '';
|
||||
const uploadPort = toInt(upload.uploadPort);
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
throw new Error('group file upload host is invalid');
|
||||
}
|
||||
|
||||
const ext = buildGroupFileUploadExt(
|
||||
senderUin,
|
||||
groupId,
|
||||
fileName,
|
||||
staged.fileSize,
|
||||
hashes.md5,
|
||||
fileId,
|
||||
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
|
||||
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
|
||||
uploadHost,
|
||||
uploadPort,
|
||||
);
|
||||
|
||||
// Fail cleanly if the source changed since hashing, then stream the PUT
|
||||
// from disk. Fetch the session BEFORE opening the handle so
|
||||
// uploadHighwayHttp (the handle's owner) is the next call and always
|
||||
// closes it.
|
||||
await assertUnchanged(staged.filePath, guardStat);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize);
|
||||
await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext);
|
||||
}
|
||||
}
|
||||
|
||||
return { fileId };
|
||||
// Stage 3: file is on the server, now publish it as a chat message.
|
||||
//
|
||||
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
|
||||
// the chat shows nothing. The publish step goes via a dedicated OIDB
|
||||
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
|
||||
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
|
||||
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when a
|
||||
// caller only needs a valid file_id embedded elsewhere, e.g. a
|
||||
// forward-message long-msg payload. Routes through `this.publish` so
|
||||
// tests can mock at the same Api boundary.
|
||||
if (publishFile) {
|
||||
try {
|
||||
await this.publish(groupId, fileId);
|
||||
} catch (err) {
|
||||
// The bytes are already on the server and the fileId is valid —
|
||||
// fail loud but don't lose the upload result the action handler
|
||||
// committed to returning. Callers can still resolve the file by
|
||||
// id; they'll just have to re-publish it themselves.
|
||||
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return { fileId };
|
||||
} finally {
|
||||
await staged.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
async uploadPrivate(
|
||||
@@ -341,35 +385,34 @@ export class GroupFileApi {
|
||||
source: string,
|
||||
name = '',
|
||||
uploadFile = true,
|
||||
publishFile = uploadFile,
|
||||
): Promise<UploadFileResult> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('private file is empty');
|
||||
// Stage onto a local disk path + stream-hash — the (up to 4 GiB) file is
|
||||
// never buffered in RAM. headLimit = MD5_HEAD_LIMIT yields the offline-file
|
||||
// md510MCheckSum in the same single pass.
|
||||
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
|
||||
try {
|
||||
if (staged.fileSize === 0) throw new Error('private file is empty');
|
||||
|
||||
const targetUid = await this.ctx.resolveUserUid(userId);
|
||||
let selfUid = this.ctx.identity.selfUid;
|
||||
if (!selfUid) {
|
||||
const selfUin = toInt(this.ctx.identity.uin);
|
||||
if (selfUin > 0) {
|
||||
selfUid = await this.ctx.resolveUserUid(selfUin);
|
||||
}
|
||||
}
|
||||
if (!selfUid) throw new Error('self uid is unavailable');
|
||||
const selfUid = await resolveSelfUid(this.ctx);
|
||||
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
|
||||
|
||||
const fileName = normalizeUploadFileName(name, loaded.fileName);
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const fileName = normalizeUploadFileName(name, staged.fileName);
|
||||
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
|
||||
const hashes = await hashFileStreaming(staged.filePath, { headLimit: MD5_HEAD_LIMIT });
|
||||
|
||||
const upload = await UploadPrivateFileRequest.invoke(this.ctx, {
|
||||
senderUid: selfUid,
|
||||
receiverUid: targetUid,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSize: staged.fileSize,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
md510MCheckSum: md5First10MB(loaded.bytes),
|
||||
md510MCheckSum: hashes.headMd5!,
|
||||
});
|
||||
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
|
||||
|
||||
@@ -387,7 +430,7 @@ export class GroupFileApi {
|
||||
scope: 'private',
|
||||
userId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSize: staged.fileSize,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
fileHash: fileHash ?? '',
|
||||
@@ -461,7 +504,7 @@ export class GroupFileApi {
|
||||
const ext = buildPrivateFileUploadExt(
|
||||
senderUin,
|
||||
fileName,
|
||||
loaded.bytes.length,
|
||||
staged.fileSize,
|
||||
hashes.md5,
|
||||
hashes.sha1,
|
||||
fileId,
|
||||
@@ -472,8 +515,13 @@ export class GroupFileApi {
|
||||
uploadPort,
|
||||
);
|
||||
|
||||
// Fail cleanly if the source changed since hashing, then stream the PUT
|
||||
// from disk. Session BEFORE opening the handle so uploadHighwayHttp (the
|
||||
// handle's owner) is the next call and always closes it.
|
||||
await assertUnchanged(staged.filePath, guardStat);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
|
||||
const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize);
|
||||
await uploadHighwayHttp(bridge, session, 95, chunkSource, hashes.md5, ext);
|
||||
}
|
||||
|
||||
// Stage 3: publish the file as a c2c chat message. C2C files use
|
||||
@@ -482,12 +530,12 @@ export class GroupFileApi {
|
||||
// which only knows about elems[]. NapCat does the same atomic
|
||||
// upload+send dance — without it the file sits on the server and
|
||||
// the recipient sees nothing.
|
||||
if (uploadFile) {
|
||||
if (publishFile) {
|
||||
try {
|
||||
await this.ctx.apis.message.sendC2cFile(userId, targetUid, {
|
||||
fileId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSize: staged.fileSize,
|
||||
fileMd5: hashes.md5,
|
||||
fileHash: fileHash ?? '',
|
||||
});
|
||||
@@ -498,6 +546,9 @@ export class GroupFileApi {
|
||||
}
|
||||
|
||||
return { fileId, fileHash };
|
||||
} finally {
|
||||
await staged.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── list (paginated loop) ───────────────
|
||||
@@ -611,7 +662,7 @@ export class GroupFileApi {
|
||||
|
||||
// ─────────────── folders ───────────────
|
||||
|
||||
createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
|
||||
createFolder(groupId: number, name: string, parentId = '/'): Promise<CreateGroupFolder.Result> {
|
||||
return CreateGroupFolder.invoke(this.ctx, {
|
||||
groupId, parentId: normalizeDirectory(parentId), folderName: name,
|
||||
});
|
||||
|
||||
@@ -9,10 +9,13 @@ import type {
|
||||
SsoReadedReportReq,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
|
||||
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { resolveSelfUid } from './shared';
|
||||
// `Bridge` is imported as a type only so we can narrow `ctx` back to
|
||||
// the concrete Bridge instance when passing it to `buildSendElems`
|
||||
// (which still takes `Bridge` because the highway upload helpers it
|
||||
@@ -25,6 +28,8 @@ import type { Bridge, SendMessageReceipt } from '../bridge';
|
||||
|
||||
const SEND_MSG_CMD = 'MessageSvc.PbSendMsg';
|
||||
|
||||
const log = createLogger('Bridge.Message');
|
||||
|
||||
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
|
||||
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
|
||||
|
||||
@@ -238,6 +243,12 @@ export class MessageApi {
|
||||
* - `subcmd: 1` — c2c file send command code
|
||||
* - `dangerEvel: 0` — virus-scan severity, always 0 client-side
|
||||
* - `expireTime` — 7 days from now (Lagrange convention)
|
||||
*
|
||||
* `FileExtra.file` alone makes the file downloadable (verified on a live
|
||||
* account). We ALSO attach `FileExtra.field6` — extra server-issued download
|
||||
* routing from a best-effort 0xE37_800 finalize that mirrors NapCat and may
|
||||
* help some receiver clients. The finalize is non-fatal: if it fails we send
|
||||
* without field6 rather than failing the send (issue #157).
|
||||
*/
|
||||
async sendC2cFile(
|
||||
userUin: number,
|
||||
@@ -247,9 +258,35 @@ export class MessageApi {
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
|
||||
// Resolve our own uid — needed both for the 0xE37_800 finalize and the
|
||||
// `field6` download-routing the receiver reads.
|
||||
const selfUid = await resolveSelfUid(this.ctx);
|
||||
|
||||
// The file is already downloadable from the `NotOnlineFile` reference
|
||||
// alone — verified on a live account: a plain c2c file send (no field6)
|
||||
// downloads fine. `field6` is EXTRA server-issued download routing (from
|
||||
// the 0xE37_800 finalize) that mirrors NapCat and may help some receiver
|
||||
// clients. So fetch it BEST-EFFORT: if the finalize fails, send without
|
||||
// field6 rather than failing the whole send. (issue #157 — the finalize
|
||||
// was originally fatal, which could regress a send that would otherwise
|
||||
// succeed.)
|
||||
const fileHash = info.fileHash ?? '';
|
||||
let meta: Awaited<ReturnType<typeof FinalizeOfflineFile.invoke>> | null = null;
|
||||
try {
|
||||
meta = await FinalizeOfflineFile.invoke(this.ctx, {
|
||||
senderUid: selfUid,
|
||||
receiverUid: userUid,
|
||||
fileUuid: info.fileId,
|
||||
fileHash,
|
||||
});
|
||||
} catch (err) {
|
||||
log.warn('c2c file finalize (0xE37_800) failed, sending without field6: %s',
|
||||
err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const sevenDaysSec = 7 * 24 * 60 * 60;
|
||||
const fileExtraBytes = protobuf_encode<FileExtra>({
|
||||
const fileExtra: FileExtra = {
|
||||
file: {
|
||||
fileType: 0,
|
||||
fileUuid: info.fileId,
|
||||
@@ -259,9 +296,26 @@ export class MessageApi {
|
||||
subcmd: 1,
|
||||
dangerEvel: 0,
|
||||
expireTime: nowSec + sevenDaysSec,
|
||||
fileHash: info.fileHash ?? '',
|
||||
fileHash,
|
||||
},
|
||||
});
|
||||
};
|
||||
if (meta) {
|
||||
fileExtra.field6 = {
|
||||
field2: {
|
||||
field1: meta.field110,
|
||||
fileUuid: info.fileId,
|
||||
fileName: info.fileName,
|
||||
field6: meta.field3,
|
||||
field7: meta.field101,
|
||||
field8: meta.field100,
|
||||
timestamp1: meta.timestamp1,
|
||||
fileHash,
|
||||
selfUid,
|
||||
destUid: userUid,
|
||||
},
|
||||
};
|
||||
}
|
||||
const fileExtraBytes = protobuf_encode<FileExtra>(fileExtra);
|
||||
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
routingHead: {
|
||||
|
||||
@@ -10,7 +10,7 @@ import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/d
|
||||
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
|
||||
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
|
||||
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
|
||||
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
|
||||
@@ -93,7 +93,7 @@ export class ProfileApi {
|
||||
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0));
|
||||
await uploadHighwayHttp(bridge, session, 90, new BufferChunkSource(loaded.bytes), hashes.md5, new Uint8Array(0));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -120,7 +120,7 @@ export class ProfileApi {
|
||||
field5: 3,
|
||||
field6: 1,
|
||||
});
|
||||
await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra);
|
||||
await uploadHighwayHttp(bridge, session, 3000, new BufferChunkSource(loaded.bytes), hashes.md5, extra);
|
||||
}
|
||||
|
||||
// ─────────────── queries on me / my contacts ───────────────
|
||||
|
||||
@@ -4,19 +4,24 @@ import {
|
||||
getQzoneFeeds,
|
||||
getQzoneMsgList,
|
||||
publishQzoneMsg,
|
||||
setQzoneBlack,
|
||||
setQzoneLike,
|
||||
updateQzoneMsgRight,
|
||||
uploadQzoneImageFromSource,
|
||||
type QzoneCommentResult,
|
||||
type QzoneFeedsResult,
|
||||
type QzoneMsgListResult,
|
||||
type QzonePublishResult,
|
||||
type QzoneUpdateRightResult,
|
||||
type QzoneUploadImageResult,
|
||||
} from '@snowluma/protocol/web/qzone';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
/**
|
||||
* Personal QQ-Zone (个人空间) web API: 说说 (feed) read/write, likes,
|
||||
* comments — all over the cookie-backed qzone.qq.com CGIs, reusing the same
|
||||
* `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi. Distinct from the
|
||||
* group-album surface, which lives on GroupAlbumApi.
|
||||
* comments, image upload — all over the cookie-backed qzone.qq.com CGIs,
|
||||
* reusing the same `getCookies('qzone.qq.com')` plumbing as GroupAlbumApi.
|
||||
* Distinct from the group-album surface, which lives on GroupAlbumApi.
|
||||
*/
|
||||
export class QzoneApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
@@ -40,10 +45,30 @@ export class QzoneApi {
|
||||
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
|
||||
}
|
||||
|
||||
/** 发表一条纯文字说说,返回新说说的 tid。始终发到机器人自己的空间。 */
|
||||
async publish(content: string): Promise<QzonePublishResult> {
|
||||
/**
|
||||
* 从来源上传图片到 QQ 空间。
|
||||
* `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据
|
||||
*/
|
||||
async uploadImageFromSource(source: string): Promise<QzoneUploadImageResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content);
|
||||
return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发表说说,返回新说说的 tid。始终发到机器人自己的空间。
|
||||
* `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串
|
||||
* (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。
|
||||
* `ugcRight` / `targetUins`: 查看权限及其作用名单(ugcRight=16/128 时必填)。
|
||||
*/
|
||||
async publish(
|
||||
content: string,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
ugcRight = 1,
|
||||
targetUins?: string,
|
||||
): Promise<QzonePublishResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval, ugcRight, targetUins);
|
||||
}
|
||||
|
||||
/** 删除机器人自己空间的一条说说(按 tid)。 */
|
||||
@@ -52,6 +77,15 @@ export class QzoneApi {
|
||||
await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改机器人自己空间一条已发说说的查看权限(按 tid)。
|
||||
* `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。
|
||||
*/
|
||||
async updateRight(tid: string, ugcRight: number, targetUins?: string): Promise<QzoneUpdateRightResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins);
|
||||
}
|
||||
|
||||
/**
|
||||
* 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说;
|
||||
* 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。
|
||||
@@ -66,11 +100,29 @@ export class QzoneApi {
|
||||
/**
|
||||
* 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间);
|
||||
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
|
||||
* `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL
|
||||
* (从 uploadImageFromSource 的 url 字段获取)。
|
||||
*/
|
||||
async comment(tid: string, content: string, targetUin: number | undefined): Promise<QzoneCommentResult> {
|
||||
async comment(
|
||||
tid: string,
|
||||
content: string,
|
||||
targetUin: number | undefined,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
): Promise<QzoneCommentResult> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content);
|
||||
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉黑或解除拉黑某人(修改机器人自身 QQ 空间黑名单)。
|
||||
* `ban=true` 拉黑,`ban=false` 解除拉黑。
|
||||
*/
|
||||
async setBlack(targetUin: number, ban: boolean): Promise<void> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await setQzoneBlack(cookieObject, selfUin, targetUin.toString(), ban);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { Bridge } from '../bridge';
|
||||
|
||||
export function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'bigint') {
|
||||
@@ -26,22 +24,10 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown
|
||||
throw new Error(`${operation} failed: code=${retCode} msg=${text}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the bot's own UID. Cached on Identity once warmup populates
|
||||
* `selfProfile`; forward/profile actions need this fast path before
|
||||
* warmup completes.
|
||||
*/
|
||||
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
|
||||
let selfUid = bridge.identity.selfUid;
|
||||
if (selfUid) return selfUid;
|
||||
|
||||
const selfUin = toInt(bridge.identity.uin);
|
||||
if (selfUin <= 0) {
|
||||
throw new Error('self uid is unavailable');
|
||||
}
|
||||
selfUid = await bridge.resolveUserUid(selfUin);
|
||||
return selfUid;
|
||||
}
|
||||
// The bot's-own-UID resolver is the single source of truth in @snowluma/protocol
|
||||
// (a Bridge satisfies its BridgeContext slice). Re-exported here so the existing
|
||||
// `resolveSelfUid(bridge)` call sites in this package keep importing from shared.
|
||||
export { resolveSelfUid } from '@snowluma/protocol/self-uid';
|
||||
|
||||
/**
|
||||
* Index describing a server-side rich-media object (image / video /
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sen
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
|
||||
import { MSG_PUSH_CMD, parseMsgPush, SysMsgDedup } from '@snowluma/protocol/msg-push';
|
||||
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
|
||||
import { buildApiHub, type ApiHub } from './apis';
|
||||
import {
|
||||
@@ -26,6 +26,8 @@ export class Bridge implements BridgeInterface {
|
||||
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
|
||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||
private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0;
|
||||
// Per-account dedup for QQ NT's already-deduped system pushes (#137).
|
||||
private readonly sysMsgDedup_ = new SysMsgDedup();
|
||||
|
||||
constructor(identity: IdentityService) {
|
||||
this.identity = identity;
|
||||
@@ -62,7 +64,7 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
},
|
||||
});
|
||||
this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
|
||||
this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) => parseMsgPush(pkt, identity, this.sysMsgDedup_));
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { Bridge } from './bridge';
|
||||
|
||||
@@ -72,13 +73,8 @@ export class BridgeManager {
|
||||
}
|
||||
}
|
||||
|
||||
private static isRealUin(uin: string): boolean {
|
||||
if (!uin || uin === '0') return false;
|
||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||
}
|
||||
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||
if (!BridgeManager.isRealUin(uin)) return;
|
||||
if (!isRealUin(uin)) return;
|
||||
|
||||
this.pidPacketClients_.set(pid, packetClient);
|
||||
|
||||
@@ -94,7 +90,7 @@ export class BridgeManager {
|
||||
}
|
||||
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
|
||||
if (!pkt.uin || !isRealUin(pkt.uin)) return;
|
||||
const uin = pkt.uin;
|
||||
|
||||
// Ensure session exists
|
||||
|
||||
@@ -2,8 +2,11 @@ import { HookManager } from '@snowluma/bridge';
|
||||
import { closeLogger, createLogger } from '@snowluma/common/logger';
|
||||
import { loadRuntimeConfig } from '@snowluma/common/runtime';
|
||||
import { OneBotManager } from '@snowluma/onebot/manager';
|
||||
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
|
||||
import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config';
|
||||
import { BridgeManager } from './bridge/manager';
|
||||
import { createNotificationManager } from './notifications/manager';
|
||||
import { createStateWiring } from './webui/state-wiring';
|
||||
|
||||
const runtimeConfig = loadRuntimeConfig();
|
||||
const log = createLogger('App');
|
||||
@@ -27,15 +30,33 @@ process.on('uncaughtException', (error) => {
|
||||
async function main() {
|
||||
log.info('SnowLuma starting');
|
||||
|
||||
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
|
||||
// any session (and thus any per-UIN config rewrite) can drop it.
|
||||
migrateGlobalSettings();
|
||||
|
||||
// One-shot: purge any persisted phantom accounts (onebot_<garbage>.json) the
|
||||
// native hook may have created with a timestamp-shaped UIN (issue #162).
|
||||
cleanupInvalidPerUinConfigs();
|
||||
|
||||
const bridgeManager = new BridgeManager();
|
||||
const oneBotManager = new OneBotManager();
|
||||
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
||||
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
|
||||
|
||||
// WebUI state-push wiring: HookManager + BridgeManager edges publish
|
||||
// `processes` / `qq-list` / `connections` invalidations into a bus the
|
||||
// /api/state/stream SSE handler subscribes to (no REST polling required).
|
||||
const stateWiring = createStateWiring();
|
||||
const hookManager = new HookManager({
|
||||
bridgeManager,
|
||||
autoLoadOnDiscovery,
|
||||
onSessionsChanged: stateWiring.onSessionsChanged,
|
||||
});
|
||||
if (autoLoadOnDiscovery) {
|
||||
log.info('hook auto-load enabled: every discovered QQ process will be injected');
|
||||
}
|
||||
|
||||
oneBotManager.bind(bridgeManager);
|
||||
stateWiring.bindBridgeManager(bridgeManager);
|
||||
|
||||
// Global notification subsystem (account up/down → webhook). Bound AFTER
|
||||
// OneBotManager so the nickname fallback is already populated when it observes.
|
||||
@@ -52,6 +73,7 @@ async function main() {
|
||||
host: runtimeConfig.webuiHost,
|
||||
tlsEnabled: runtimeConfig.webuiTls?.enabled,
|
||||
trustProxy: runtimeConfig.trustProxy,
|
||||
stateBus: stateWiring.bus,
|
||||
});
|
||||
} catch (err) {
|
||||
log.error('Failed to start WebUI: ', err);
|
||||
@@ -65,6 +87,7 @@ async function main() {
|
||||
oneBotManager.dispose();
|
||||
notificationManager.dispose();
|
||||
hookManager.dispose();
|
||||
stateWiring.dispose();
|
||||
await closeLogger();
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//
|
||||
// Channels are GLOBAL (defined once here); each UIN opts into a subset via
|
||||
// `OneBotConfig.notifications.channelIds` (see packages/onebot/src/config.ts).
|
||||
import { boolOr, clampInt, isObject } from '@snowluma/common/coerce';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
@@ -92,21 +93,9 @@ export function renderTemplate(template: string, vars: Record<string, string>):
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Normalization helpers (replicated from ui-config conventions) ──────────
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function boolOr(value: unknown, fallback: boolean): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
function clampInt(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.trunc(Math.min(max, Math.max(min, n)));
|
||||
}
|
||||
// ─── Normalization helpers ──────────────────────────────────────────────────
|
||||
// isObject / boolOr / clampInt come from @snowluma/common/coerce. strOr is
|
||||
// notifications-only (string truncation to maxLen), so it stays here.
|
||||
|
||||
function strOr(value: unknown, fallback: string, maxLen: number): string {
|
||||
return typeof value === 'string' ? value.slice(0, maxLen) : fallback;
|
||||
|
||||
@@ -28,6 +28,9 @@ export const BACKUP_FILES: readonly BackupFileSpec[] = [
|
||||
{ name: 'runtime.json', binary: false, credential: false },
|
||||
{ name: 'ui.json', binary: false, credential: false },
|
||||
{ name: 'notifications.json', binary: false, credential: false },
|
||||
// Global all-accounts SnowLuma settings (rkey fallback servers, …). Same
|
||||
// class as notifications.json: global, opt-in, non-credential.
|
||||
{ name: 'snowluma.json', binary: false, credential: false },
|
||||
{ name: 'cert.pem', binary: false, credential: false },
|
||||
{ name: 'ui-assets/background', binary: true, credential: false },
|
||||
{ name: 'webui.json', binary: false, credential: true },
|
||||
|
||||
104
packages/core/src/webui/connection-diff-loop.ts
Normal file
104
packages/core/src/webui/connection-diff-loop.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Connection-status diff loop. OneBot adapters don't have an internal
|
||||
* event-emitter for connection state (listening / connected / client-count
|
||||
* changes), so this loop polls `getConnectionStatuses()` and publishes
|
||||
* `connections` to the StateBus when the JSON-serialised snapshot changes
|
||||
* vs the previous tick.
|
||||
*
|
||||
* Cheap (500ms default cadence, 1-3 accounts, ~hundreds of bytes), only
|
||||
* fires the StateBus when state actually moves — so the SSE handler only
|
||||
* pushes a fresh `connections` frame when the user would actually see
|
||||
* something update.
|
||||
*/
|
||||
|
||||
import type { StateBus } from './state-bus';
|
||||
|
||||
export interface ConnectionDiffLoopOptions {
|
||||
bus: StateBus;
|
||||
/** Read the current adapter-status snapshot for every live UIN. */
|
||||
getSnapshot: () => unknown;
|
||||
/** Optional projector — return the "comparable" subset of the snapshot.
|
||||
* The full snapshot is what the SSE handler ships to the WebUI; this
|
||||
* projection is what the diff loop compares between ticks. Use it to
|
||||
* strip volatile fields (e.g. HH:MM:SS timestamps embedded in adapter
|
||||
* `detail` strings) that would otherwise produce a publish every tick
|
||||
* under any active webhook — defeating the loop's whole purpose.
|
||||
* Default: identity. */
|
||||
pickComparable?: (snapshot: unknown) => unknown;
|
||||
/** Poll cadence in milliseconds; default 500. */
|
||||
intervalMs?: number;
|
||||
}
|
||||
|
||||
export interface ConnectionDiffLoopHandle {
|
||||
/** Stop the loop. Subsequent snapshot mutations produce nothing. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle {
|
||||
const intervalMs = opts.intervalMs ?? 500;
|
||||
let lastSerialized = '';
|
||||
let haveBaseline = false;
|
||||
let disposed = false;
|
||||
// One-shot diagnostic latch: a projector that starts throwing only after
|
||||
// a shape regression would otherwise wedge the baseline silently — no
|
||||
// publishes, no log, no symptom besides "the dashboard's connections
|
||||
// card stops updating". Surface it ONCE so the failure is visible.
|
||||
let warnedProjectorThrew = false;
|
||||
|
||||
const tick = (): void => {
|
||||
if (disposed) return;
|
||||
let snap: unknown;
|
||||
try {
|
||||
snap = opts.getSnapshot();
|
||||
} catch {
|
||||
// Snapshot read failed (e.g. mid-shutdown). Skip this tick; the
|
||||
// next one will retry. Don't reset the baseline so we don't
|
||||
// spuriously republish when the snapshot starts working again.
|
||||
return;
|
||||
}
|
||||
let comparable: unknown;
|
||||
try {
|
||||
comparable = opts.pickComparable ? opts.pickComparable(snap) : snap;
|
||||
} catch (err) {
|
||||
// A buggy projector must not crash the diff loop or wedge baseline.
|
||||
// But silent wedge is its own bug class — log the FIRST occurrence
|
||||
// so an operator can find it without re-running the loop locally.
|
||||
if (!warnedProjectorThrew) {
|
||||
warnedProjectorThrew = true;
|
||||
// Static logger import avoided to keep the loop self-contained;
|
||||
// stderr is good enough for a once-per-process latch.
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('[connection-diff-loop] pickComparable threw — connections SSE diff will wedge until restart:', err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const serialized = JSON.stringify(comparable);
|
||||
if (!haveBaseline) {
|
||||
// First successful observation. The SSE handler's sendAllInitial
|
||||
// already shipped a `connections` frame to every connected client
|
||||
// on connect, so the baseline is what they already have — emitting
|
||||
// it again would be a duplicate. Just store it.
|
||||
lastSerialized = serialized;
|
||||
haveBaseline = true;
|
||||
return;
|
||||
}
|
||||
if (serialized === lastSerialized) return;
|
||||
lastSerialized = serialized;
|
||||
opts.bus.publish('connections');
|
||||
};
|
||||
|
||||
const timer = setInterval(tick, intervalMs);
|
||||
// Don't pin the Node event loop: the loop is permanent for the server
|
||||
// lifetime by design, but tests / a future hot-reload scenario must be
|
||||
// able to exit cleanly without an outstanding interval ref. Mirrors the
|
||||
// tokenJanitor pattern in server.ts.
|
||||
timer.unref?.();
|
||||
|
||||
return {
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
197
packages/core/src/webui/debug-tools.ts
Normal file
197
packages/core/src/webui/debug-tools.ts
Normal file
@@ -0,0 +1,197 @@
|
||||
// debug-tools — backend for the debug console's two heavier endpoints
|
||||
// (Phase 2 of the debug-console expansion):
|
||||
//
|
||||
// • POST /api/debug/invoke-stream — drive a Stream API action and relay every
|
||||
// frame to the browser over an SSE body. Unlike the live-activity stream
|
||||
// (debug-stream.ts), this MUST NOT drop frames: a file transfer that loses a
|
||||
// chunk is corrupt. So backpressure is handled by *waiting* for the consumer
|
||||
// to drain, never by dropping.
|
||||
// • POST /api/debug/upload — stream a browser-selected file to a temp path on
|
||||
// the SERVER (the bot runs on the server, not the user's machine), so the
|
||||
// returned path can be fed to a send action. Streamed straight to disk with a
|
||||
// byte cap — never buffered whole, so large videos don't blow up memory.
|
||||
//
|
||||
// The pure pieces live here (path sanitisation, the size-capped disk sink, the
|
||||
// stream-invoke Response builder) so they are unit-testable away from Hono.
|
||||
|
||||
import { createWriteStream } from 'fs';
|
||||
import { mkdir, readdir, rm, stat } from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
|
||||
/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but
|
||||
* kept distinct so the two cleanup stories don't entangle. */
|
||||
export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'snowluma-debug-upload');
|
||||
|
||||
/** Hard ceiling on a single upload. Mirrors the Stream API's upload cap. */
|
||||
export const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
|
||||
|
||||
/** Uploads older than this are swept on the next upload (best-effort). */
|
||||
const UPLOAD_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/** Reduce a client-supplied filename to a safe basename (extension preserved),
|
||||
* with no path separators or traversal. The client path is NEVER trusted for
|
||||
* placement — this is only used to keep the stored name human-readable. */
|
||||
export function safeUploadName(raw: string | undefined): string {
|
||||
// Treat both separators as path delimiters, then take the basename so any
|
||||
// `../` / absolute prefix is discarded regardless of host platform.
|
||||
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'));
|
||||
const cleaned = base
|
||||
.replace(/[^\w.\-]+/g, '_') // collapse anything exotic to underscore
|
||||
.replace(/^\.+/, '') // no leading dots (no hidden / '..' names)
|
||||
.slice(0, 120);
|
||||
return cleaned || 'file';
|
||||
}
|
||||
|
||||
/** Unguessable destination path under DEBUG_UPLOAD_DIR for a sanitised name.
|
||||
* Throws if the composed path would escape the dir (defence in depth — it
|
||||
* can't, given the random id + basename, but we assert anyway). */
|
||||
export function uploadDestPath(safeName: string): string {
|
||||
const id = randomBytes(12).toString('hex');
|
||||
const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`);
|
||||
const rel = path.relative(DEBUG_UPLOAD_DIR, dest);
|
||||
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
|
||||
throw new Error('invalid upload path');
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
|
||||
/** Stream raw request-body bytes to a temp file under DEBUG_UPLOAD_DIR, enforcing
|
||||
* a byte cap. Returns the final server path + byte size. On overflow or any
|
||||
* error the partial file is removed and the call rejects. Never buffers the
|
||||
* whole body. */
|
||||
export async function streamUploadToDisk(
|
||||
body: ReadableStream<Uint8Array> | null,
|
||||
filename: string | undefined,
|
||||
opts: { maxBytes?: number } = {},
|
||||
): Promise<{ path: string; size: number }> {
|
||||
if (!body) throw new Error('empty body');
|
||||
const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES;
|
||||
await mkdir(DEBUG_UPLOAD_DIR, { recursive: true });
|
||||
void sweepOldUploads(); // fire-and-forget TTL cleanup
|
||||
|
||||
const dest = uploadDestPath(safeUploadName(filename));
|
||||
const out = createWriteStream(dest, { mode: 0o600 });
|
||||
// A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a
|
||||
// background flush — typically while we're parked at reader.read() or waiting
|
||||
// on 'drain'. An unhandled 'error' event would crash the whole process, and a
|
||||
// backpressured error would leave 'drain' to never fire (a forever-hung await
|
||||
// + leaked fd). So turn it into a rejection and race it into every await; the
|
||||
// catch below then destroys + unlinks the partial.
|
||||
const errored = new Promise<never>((_, rej) => out.once('error', rej));
|
||||
errored.catch(() => { /* swallow a late error after success (still raced below) */ });
|
||||
let size = 0;
|
||||
try {
|
||||
const reader = body.getReader();
|
||||
for (;;) {
|
||||
const { done, value } = await Promise.race([errored, reader.read()]);
|
||||
if (done) break;
|
||||
if (!value || value.byteLength === 0) continue;
|
||||
size += value.byteLength;
|
||||
if (size > maxBytes) throw new Error('上传超出大小上限');
|
||||
// Respect the write stream's backpressure (but never hang on an error).
|
||||
if (!out.write(value)) {
|
||||
await Promise.race([errored, new Promise<void>((res) => out.once('drain', res))]);
|
||||
}
|
||||
}
|
||||
await Promise.race([errored, new Promise<void>((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())))]);
|
||||
if (size === 0) throw new Error('empty body');
|
||||
return { path: dest, size };
|
||||
} catch (err) {
|
||||
// Wait for the stream to fully close BEFORE unlinking: createWriteStream
|
||||
// opens the fd asynchronously, so a fast failure can reach `rm` before the
|
||||
// file even exists on disk — then the late open would re-create it and leak
|
||||
// the partial. 'close' guarantees the fd is settled and no more writes land.
|
||||
out.destroy();
|
||||
if (!out.closed) await new Promise<void>((res) => out.once('close', () => res()));
|
||||
await rm(dest, { force: true }).catch(() => { /* best-effort */ });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove upload temp files older than the TTL. Best-effort; never throws. */
|
||||
export async function sweepOldUploads(now: number = Date.now()): Promise<number> {
|
||||
let removed = 0;
|
||||
try {
|
||||
const names = await readdir(DEBUG_UPLOAD_DIR);
|
||||
await Promise.all(
|
||||
names.map(async (n) => {
|
||||
const p = path.join(DEBUG_UPLOAD_DIR, n);
|
||||
try {
|
||||
const s = await stat(p);
|
||||
if (now - s.mtimeMs > UPLOAD_TTL_MS) {
|
||||
await rm(p, { force: true, recursive: true });
|
||||
removed += 1;
|
||||
}
|
||||
} catch { /* racing cleanup / vanished file */ }
|
||||
}),
|
||||
);
|
||||
} catch { /* dir absent yet */ }
|
||||
return removed;
|
||||
}
|
||||
|
||||
/** Drives a stream-capable action and relays its frames. The driver is the
|
||||
* instance's `invokeStream` (which itself handles non-stream actions by emitting
|
||||
* a single frame). */
|
||||
export type StreamInvokeDriver = (
|
||||
rawRequest: string,
|
||||
emit: (json: string) => Promise<void>,
|
||||
isAlive: () => boolean,
|
||||
) => Promise<void>;
|
||||
|
||||
/** How long emit() will wait for a backed-up consumer to drain before it gives
|
||||
* up waiting and enqueues anyway (the request abort / action idle-watchdog are
|
||||
* the real stall guards). */
|
||||
const DRAIN_WAIT_MS = 20;
|
||||
const DRAIN_MAX_SPINS = 3000; // 3000 * 20ms ≈ 60s
|
||||
|
||||
/** Build the SSE `Response` for `/api/debug/invoke-stream`: each relayed frame
|
||||
* is one `data: <json>\n\n` event; no frame is ever dropped. A driver error
|
||||
* becomes a terminal `failed` frame. Closing the request (signal abort) stops
|
||||
* delivery. `delay` is injectable for tests. */
|
||||
export function buildStreamInvokeResponse(
|
||||
driver: StreamInvokeDriver,
|
||||
rawRequest: string,
|
||||
signal: AbortSignal,
|
||||
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
|
||||
): Response {
|
||||
const encoder = new TextEncoder();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
let closed = false;
|
||||
const onAbort = () => { closed = true; };
|
||||
signal.addEventListener('abort', onAbort);
|
||||
const isAlive = () => !closed && !signal.aborted;
|
||||
|
||||
const emit = async (json: string): Promise<void> => {
|
||||
if (!isAlive()) throw new Error('stream transport closed');
|
||||
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
|
||||
let spins = 0;
|
||||
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
|
||||
await delay(DRAIN_WAIT_MS);
|
||||
spins += 1;
|
||||
}
|
||||
if (!isAlive()) throw new Error('stream transport closed');
|
||||
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
||||
};
|
||||
|
||||
try {
|
||||
await driver(rawRequest, emit, isAlive);
|
||||
} catch (err) {
|
||||
if (isAlive()) {
|
||||
const msg = err instanceof Error ? err.message : 'stream error';
|
||||
try {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`));
|
||||
} catch { /* controller already torn down */ }
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
try { controller.close(); } catch { /* already closed */ }
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
|
||||
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
|
||||
import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config';
|
||||
import { loadGlobalSettings, saveGlobalSettings } from '@snowluma/onebot/global-config';
|
||||
import type { OneBotManager } from '@snowluma/onebot/manager';
|
||||
import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types';
|
||||
import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime';
|
||||
@@ -21,6 +22,11 @@ import { coerceSettingsPatch } from './system-settings';
|
||||
import { buildBackup, planRestore, validateBackup } from './backup';
|
||||
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
|
||||
import { createFramePusher } from './debug-stream';
|
||||
import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools';
|
||||
import { sseResponse } from './sse-response';
|
||||
import { bindStateStream } from './state-stream';
|
||||
import type { StateBus, StateResource } from './state-bus';
|
||||
import { startConnectionDiffLoop } from './connection-diff-loop';
|
||||
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
||||
import { findAvailablePort } from './port';
|
||||
import {
|
||||
@@ -80,18 +86,27 @@ const CONSENT_ALLOWLIST = new Set([
|
||||
'/api/logout',
|
||||
]);
|
||||
|
||||
// Endpoints that may authenticate via `?token=` query parameter. Only the
|
||||
// SSE log stream is here because EventSource cannot set custom headers; all
|
||||
// other endpoints MUST use the Authorization header so tokens never leak
|
||||
// into access logs / Referer / browser history.
|
||||
const TOKEN_QUERY_ALLOWLIST = new Set([
|
||||
// Endpoints that may authenticate via `?token=` query parameter. Reserved
|
||||
// for SSE streams: EventSource cannot set custom headers, so these MUST
|
||||
// accept the token via query. All other endpoints use the Authorization
|
||||
// header so tokens never leak into access logs / Referer / browser history.
|
||||
//
|
||||
// Exported so the regression test can lock the invariant — a missing entry
|
||||
// here silently 401s the EventSource and the whole push channel goes dark,
|
||||
// which has happened (see /api/state/stream's first cut).
|
||||
export const SSE_TOKEN_QUERY_PATHS: ReadonlySet<string> = new Set([
|
||||
'/api/logs/stream',
|
||||
'/api/debug/stream',
|
||||
'/api/state/stream',
|
||||
]);
|
||||
const TOKEN_QUERY_ALLOWLIST = SSE_TOKEN_QUERY_PATHS;
|
||||
|
||||
// uin = QQ number; 5–12 digits. Used to construct config file paths,
|
||||
// so we MUST refuse anything else (path traversal, NUL bytes, etc.).
|
||||
const UIN_REGEX = /^\d{5,12}$/;
|
||||
// uin = QQ number; 5–10 digits (real QQ UINs fit in uint32, max 4294967295).
|
||||
// Used to construct config file paths, so we MUST refuse anything else (path
|
||||
// traversal, NUL bytes, etc.) — and the 10-digit cap also rejects the garbage
|
||||
// timestamp-shaped UINs the native hook can emit (issue #162). Mirrors
|
||||
// isRealUin in @snowluma/common/uin.
|
||||
const UIN_REGEX = /^\d{5,10}$/;
|
||||
|
||||
const avatarCache = new Map<string, { body: Uint8Array; contentType: string; expiresAt: number }>();
|
||||
|
||||
@@ -313,7 +328,7 @@ export async function initWebUI(
|
||||
oneBotManager: OneBotManager,
|
||||
hookManager?: HookManager,
|
||||
notificationManager?: NotificationManager,
|
||||
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string } = {},
|
||||
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: StateBus } = {},
|
||||
): Promise<{ port: number }> {
|
||||
// Resolve the client IP for per-IP rate limiting from the configured
|
||||
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
|
||||
@@ -322,6 +337,54 @@ export async function initWebUI(
|
||||
const trustProxyMode = parseTrustProxy(listener.trustProxy);
|
||||
const getClientIp = makeClientIpResolver(trustProxyMode);
|
||||
|
||||
// Connection-status diff loop: OneBot adapters don't emit events for
|
||||
// listening/connected/client-count changes, so we poll the snapshot at
|
||||
// 500ms and publish 'connections' to the StateBus when it actually
|
||||
// moves. One loop per server lifetime, lives until process exit (the
|
||||
// setInterval is .unref'd inside the loop so it doesn't pin the event
|
||||
// loop on shutdown).
|
||||
//
|
||||
// `pickComparable` strips `adapter.detail` — that's a localised human
|
||||
// string assembled with HH:MM:SS timestamps from the last webhook
|
||||
// delivery; including it in the diff would make every webhook event
|
||||
// produce a publish (defeating the diff). We compare ONLY name + kind +
|
||||
// status, which captures every transition the dashboard actually
|
||||
// renders differently. The SSE handler still ships the FULL snapshot
|
||||
// (with `detail`) — it's only the diff key that's pruned.
|
||||
//
|
||||
// Trade-off: the rendered detail string (e.g. "3 个客户端", "上次推送
|
||||
// 14:53:01") only refreshes on the next SSE push or on the 30s REST
|
||||
// reconcile — not in real time. The user's original reported bugs were
|
||||
// about process / account edges (which DO push instantly); refreshing
|
||||
// adapter detail strings at sub-second cadence wasn't required. If it
|
||||
// becomes one, surface client-count as a structured field on
|
||||
// AdapterStatus and include it in the comparable.
|
||||
if (listener.stateBus) {
|
||||
// Handle deliberately discarded — initWebUI has no shutdown path; the
|
||||
// loop's setInterval is .unref'd so it doesn't pin the event loop.
|
||||
startConnectionDiffLoop({
|
||||
bus: listener.stateBus,
|
||||
getSnapshot: () => oneBotManager.getConnectionStatuses(),
|
||||
pickComparable: (snap) => {
|
||||
if (!Array.isArray(snap)) return snap;
|
||||
return (snap as Array<{ uin: string; nickname?: string; adapters?: unknown[] }>).map((acc) => ({
|
||||
uin: acc.uin,
|
||||
nickname: acc.nickname,
|
||||
// Empty fallback when `adapters` is not an array — never the
|
||||
// raw value, which could re-introduce volatile fields verbatim
|
||||
// if the snapshot shape ever drifts.
|
||||
adapters: Array.isArray(acc.adapters)
|
||||
? acc.adapters.map((a: unknown) => {
|
||||
const o = a as { name?: string; kind?: string; status?: string };
|
||||
return { name: o.name, kind: o.kind, status: o.status };
|
||||
})
|
||||
: [],
|
||||
}));
|
||||
},
|
||||
intervalMs: 500,
|
||||
});
|
||||
}
|
||||
|
||||
// Actual bound port (set just before serve; findAvailablePort may bump it).
|
||||
// Read by GET /api/system/settings so the panel shows what's really live.
|
||||
let boundPort = desiredPort;
|
||||
@@ -871,48 +934,60 @@ export async function initWebUI(
|
||||
return c.json(result);
|
||||
});
|
||||
|
||||
// Invoke a Stream API action (or any action) and relay every frame to the
|
||||
// browser over an SSE body. The frontend reads this with fetch()+a stream
|
||||
// reader (Bearer auth in the header), so — unlike /api/debug/stream — it does
|
||||
// NOT need a query-token allowlist entry. Frames are never dropped.
|
||||
app.post('/api/debug/invoke-stream', async (c) => {
|
||||
let body: unknown;
|
||||
try { body = await c.req.json(); } catch { return c.json({ status: 'failed', message: '请求格式错误' }, 400); }
|
||||
const { uin, action, params } = (body ?? {}) as { uin?: unknown; action?: unknown; params?: unknown };
|
||||
if (typeof uin !== 'string' || !UIN_REGEX.test(uin)) return c.json({ status: 'failed', message: '无效的账号' }, 400);
|
||||
if (typeof action !== 'string' || !action) return c.json({ status: 'failed', message: 'action 必填' }, 400);
|
||||
if (params !== undefined && (typeof params !== 'object' || params === null || Array.isArray(params))) {
|
||||
return c.json({ status: 'failed', message: 'params 必须是对象' }, 400);
|
||||
}
|
||||
const inst = oneBotManager.getInstance(uin);
|
||||
if (!inst) return c.json({ status: 'failed', message: '账号不在线' }, 404);
|
||||
const rawRequest = JSON.stringify({ action, params: params ?? {} });
|
||||
return buildStreamInvokeResponse(
|
||||
(rq, emit, alive) => inst.invokeStream(rq, emit, alive),
|
||||
rawRequest,
|
||||
c.req.raw.signal,
|
||||
);
|
||||
});
|
||||
|
||||
// Stream a browser-selected file to a temp path on THIS server (the bot runs
|
||||
// here, not on the operator's machine), so the returned path can be fed to a
|
||||
// send action's file/image/record/video param. Raw bytes in the body,
|
||||
// `?filename=` for a human-readable suffix; streamed to disk with a byte cap.
|
||||
app.post('/api/debug/upload', async (c) => {
|
||||
try {
|
||||
const result = await streamUploadToDisk(c.req.raw.body as ReadableStream<Uint8Array> | null, c.req.query('filename'));
|
||||
return c.json({ status: 'ok', path: result.path, size: result.size });
|
||||
} catch (err) {
|
||||
return c.json({ status: 'failed', message: err instanceof Error ? err.message : '上传失败' }, 400);
|
||||
}
|
||||
});
|
||||
|
||||
// Live merged SSE of OneBot events + action calls across all accounts. Taps
|
||||
// are attached only while a client is connected (on-demand). A slow client is
|
||||
// dropped (not back-pressured onto the bot) with a periodic drop marker.
|
||||
app.get('/api/debug/stream', (c) => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
const offs: Array<() => void> = [];
|
||||
let heartbeat: NodeJS.Timeout | undefined;
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
for (const off of offs) { try { off(); } catch { /* ignore */ } }
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const raw = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try { controller.enqueue(chunk); } catch { teardown(); }
|
||||
};
|
||||
// Drop-under-backpressure framing (unit-tested in debug-stream.ts).
|
||||
const pushFrame = createFramePusher({
|
||||
desiredSize: () => controller.desiredSize,
|
||||
enqueue: raw,
|
||||
encode: (s) => encoder.encode(s),
|
||||
});
|
||||
const send = (payload: unknown) => { if (!closed) pushFrame(payload); };
|
||||
send({ kind: 'ready' });
|
||||
for (const inst of oneBotManager.getInstances()) {
|
||||
const uin = inst.uin;
|
||||
offs.push(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event })));
|
||||
offs.push(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec })));
|
||||
}
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
app.get('/api/debug/stream', (c) => sseResponse(c, (ch) => {
|
||||
// Drop-under-backpressure framing (unit-tested in debug-stream.ts).
|
||||
const pushFrame = createFramePusher({
|
||||
desiredSize: ch.desiredSize,
|
||||
enqueue: ch.raw,
|
||||
encode: ch.encode,
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
});
|
||||
const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); };
|
||||
send({ kind: 'ready' });
|
||||
for (const inst of oneBotManager.getInstances()) {
|
||||
const uin = inst.uin;
|
||||
ch.onClose(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event })));
|
||||
ch.onClose(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec })));
|
||||
}
|
||||
}));
|
||||
|
||||
app.get('/api/qq-list', (c) => {
|
||||
const instances = oneBotManager.getInstances();
|
||||
@@ -926,6 +1001,55 @@ export async function initWebUI(
|
||||
return c.json({ list: oneBotManager.getConnectionStatuses() });
|
||||
});
|
||||
|
||||
// Combined SSE feed for the dashboard's three live resources — processes,
|
||||
// qq-list, connections. Replaces the 3s REST polling tick in
|
||||
// app-layout.tsx; the REST endpoints above stay for the initial fetch
|
||||
// before SSE connects and for the slow (30s) reconciliation fallback.
|
||||
//
|
||||
// On connect: one frame per resource with the current snapshot. After
|
||||
// that: a fresh snapshot per resource only when the StateBus signals a
|
||||
// change (HookSession status-changed, BridgeManager session edges, the
|
||||
// connection-status diff loop). 50ms per-resource debounce coalesces a
|
||||
// burst (e.g. multiple HookSessions flipping status simultaneously).
|
||||
const stateBus = listener.stateBus;
|
||||
app.get('/api/state/stream', (c) => {
|
||||
if (!stateBus) {
|
||||
// Build without state-wiring (e.g. a future headless mode) — clients
|
||||
// fall back to the REST endpoints. Treat as endpoint-not-here.
|
||||
return c.text('state stream not configured', 503);
|
||||
}
|
||||
const liveBus = stateBus;
|
||||
return sseResponse(c, (ch) => {
|
||||
const pushFrame = createFramePusher({
|
||||
desiredSize: ch.desiredSize,
|
||||
enqueue: ch.raw,
|
||||
encode: ch.encode,
|
||||
});
|
||||
const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); };
|
||||
send({ kind: 'ready' });
|
||||
|
||||
const handle = bindStateStream({
|
||||
bus: liveBus,
|
||||
snapshot: async (resource: StateResource): Promise<unknown> => {
|
||||
if (resource === 'processes') {
|
||||
if (!hookManager) return [];
|
||||
return hookManager.listProcesses();
|
||||
}
|
||||
if (resource === 'qq-list') {
|
||||
return oneBotManager.getInstances().map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
|
||||
}
|
||||
return oneBotManager.getConnectionStatuses();
|
||||
},
|
||||
send: (frame) => send(frame),
|
||||
debounceMs: 50,
|
||||
});
|
||||
ch.onClose(() => handle.dispose());
|
||||
// Prime with the initial snapshot; if the client never sees the
|
||||
// bus publish (idle system) it still has the current state.
|
||||
void handle.sendAllInitial();
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/logs', (c) => {
|
||||
const limit = Number(c.req.query('limit') ?? 300);
|
||||
return c.json({ list: getRecentLogs(limit) });
|
||||
@@ -945,49 +1069,10 @@ export async function initWebUI(
|
||||
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
|
||||
});
|
||||
|
||||
app.get('/api/logs/stream', (c) => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
let unsubscribe: (() => void) | undefined;
|
||||
let heartbeat: NodeJS.Timeout | undefined;
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
unsubscribe?.();
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const safeEnqueue = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try {
|
||||
controller.enqueue(chunk);
|
||||
} catch {
|
||||
// The peer dropped between abort and the next enqueue —
|
||||
// treat as end-of-stream so we don't leak listeners.
|
||||
teardown();
|
||||
}
|
||||
};
|
||||
const send = (event: unknown) => {
|
||||
safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
||||
};
|
||||
send({ type: 'ready' });
|
||||
unsubscribe = subscribeLogs((entry) => send(entry));
|
||||
heartbeat = setInterval(() => {
|
||||
safeEnqueue(encoder.encode(': heartbeat\n\n'));
|
||||
}, 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
Connection: 'keep-alive',
|
||||
},
|
||||
});
|
||||
});
|
||||
app.get('/api/logs/stream', (c) => sseResponse(c, (ch) => {
|
||||
ch.send({ type: 'ready' });
|
||||
ch.onClose(subscribeLogs((entry) => ch.send(entry)));
|
||||
}));
|
||||
|
||||
app.get('/api/processes', async (c) => {
|
||||
if (!hookManager) return c.json({ list: [] });
|
||||
@@ -1119,6 +1204,32 @@ export async function initWebUI(
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Global deployment config (config/snowluma.json) ─────────────────────
|
||||
// All-accounts SnowLuma knobs (rkey fallback servers + musicSignUrl). Saving
|
||||
// section-merges + normalizes server-side, then hot-reloads every instance.
|
||||
app.get('/api/global-config', (c) => c.json({ config: loadGlobalSettings() }));
|
||||
|
||||
app.post('/api/global-config', async (c) => {
|
||||
const declaredLen = Number(c.req.header('content-length'));
|
||||
if (Number.isFinite(declaredLen) && declaredLen > 512 * 1024) {
|
||||
return c.json({ success: false, message: '配置过大' }, 413);
|
||||
}
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
try {
|
||||
const config = saveGlobalSettings(body);
|
||||
oneBotManager.reloadGlobalSettings();
|
||||
return c.json({ success: true, config });
|
||||
} catch (err) {
|
||||
log.warn('save global config failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ─── WebUI customization config (config/ui.json) ─────────────────────────
|
||||
// Appearance (A) + layout (C). The full config is bearer-gated; only the
|
||||
// cosmetic appearance subset is exposed unauthenticated for the login page.
|
||||
|
||||
69
packages/core/src/webui/sse-response.ts
Normal file
69
packages/core/src/webui/sse-response.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { type Context } from 'hono';
|
||||
|
||||
/**
|
||||
* The per-connection channel handed to an SSE endpoint's `start` callback.
|
||||
* Everything the endpoint needs to talk to the client, without owning the
|
||||
* transport lifecycle (heartbeat / teardown / abort / headers).
|
||||
*/
|
||||
export interface SseChannel {
|
||||
/** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */
|
||||
raw(chunk: Uint8Array): void;
|
||||
/** Encode a string to bytes (shared TextEncoder). */
|
||||
encode(s: string): Uint8Array;
|
||||
/** Convenience: enqueue one `data: <json>\n\n` frame. */
|
||||
send(payload: unknown): void;
|
||||
/** Register a cleanup to run once on teardown (unsubscribe / dispose). */
|
||||
onClose(fn: () => void): void;
|
||||
/** True after teardown — guard sends from late subscription callbacks. */
|
||||
isClosed(): boolean;
|
||||
/** Underlying controller backpressure signal, for `createFramePusher`. */
|
||||
desiredSize(): number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The SSE HTTP transport shell shared by the WebUI's live endpoints. Owns the
|
||||
* TextEncoder, a `closed` guard, a 15s `: heartbeat` keep-alive, teardown
|
||||
* (clear heartbeat → run registered cleanups → close the controller), safe
|
||||
* enqueue (a throw means the peer dropped → teardown), the abort listener, and
|
||||
* the `text/event-stream` headers. `start` wires up the endpoint-specific
|
||||
* subscription + initial sends via the channel.
|
||||
*
|
||||
* Each of `/api/debug/stream`, `/api/state/stream`, `/api/logs/stream`
|
||||
* previously hand-copied this ~40-line skeleton; a heartbeat-interval /
|
||||
* teardown-order / header change had to be kept in sync across all three.
|
||||
*/
|
||||
export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response {
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
let heartbeat: ReturnType<typeof setInterval> | undefined;
|
||||
const cleanups: Array<() => void> = [];
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
for (const fn of cleanups) { try { fn(); } catch { /* ignore */ } }
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const raw = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try { controller.enqueue(chunk); } catch { teardown(); }
|
||||
};
|
||||
const ch: SseChannel = {
|
||||
raw,
|
||||
encode: (s) => encoder.encode(s),
|
||||
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
|
||||
onClose: (fn) => { cleanups.push(fn); },
|
||||
isClosed: () => closed,
|
||||
desiredSize: () => controller.desiredSize,
|
||||
};
|
||||
start(ch);
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
}
|
||||
67
packages/core/src/webui/state-bus.ts
Normal file
67
packages/core/src/webui/state-bus.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* StateBus — pure pub/sub for WebUI state-resource invalidations.
|
||||
*
|
||||
* Three resources are tracked: `processes`, `qq-list`, `connections`. A
|
||||
* publisher (HookSession status change, BridgeManager session start/close,
|
||||
* the connection-status diff loop) calls `publish(resource)` to signal "the
|
||||
* snapshot for THIS resource is stale; whoever cares should re-read". The
|
||||
* `/api/state/stream` SSE handler subscribes, debounces, and pushes fresh
|
||||
* snapshots to connected WebUI clients.
|
||||
*
|
||||
* Intentionally pure pub/sub (no debounce, no snapshot caching): debounce
|
||||
* and snapshot reads live with the subscriber so different consumers can
|
||||
* coalesce on different cadences. Snapshot semantics on fan-out: the
|
||||
* subscriber set is FROZEN at the start of each publish, so a listener
|
||||
* that subscribes during the fan-out only sees the FOLLOWING publish, and
|
||||
* a listener that unsubscribes mid-fan-out does not prevent its peers
|
||||
* from completing.
|
||||
*/
|
||||
|
||||
export type StateResource = 'processes' | 'qq-list' | 'connections';
|
||||
|
||||
export type StateListener = (resource: StateResource) => void;
|
||||
|
||||
export class StateBus {
|
||||
private readonly listeners = new Set<StateListener>();
|
||||
private disposed = false;
|
||||
|
||||
/** Subscribe to every publish; returns an unsubscribe handle. Calling
|
||||
* the handle more than once is a no-op. */
|
||||
subscribe(listener: StateListener): () => void {
|
||||
if (this.disposed) return () => undefined;
|
||||
this.listeners.add(listener);
|
||||
let active = true;
|
||||
return () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/** Notify every CURRENTLY-subscribed listener that `resource` is stale.
|
||||
* Iterates a frozen snapshot of the subscriber set so add/remove during
|
||||
* the emit don't change which listeners see THIS publish; subscriber
|
||||
* exceptions are isolated and do not abort the fan-out. */
|
||||
publish(resource: StateResource): void {
|
||||
if (this.disposed) return;
|
||||
// Snapshot the current subscribers — any subscribe()/unsubscribe()
|
||||
// called by a listener during the fan-out takes effect only for the
|
||||
// NEXT publish, not this one.
|
||||
const snapshot = [...this.listeners];
|
||||
for (const fn of snapshot) {
|
||||
try {
|
||||
fn(resource);
|
||||
} catch {
|
||||
// Subscriber-internal failure is its own problem. The bus's job
|
||||
// is to keep delivery moving — surfacing an error here would
|
||||
// partially abort the fan-out and create skip-the-listener bugs.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop every subscriber and refuse future subscribes / publishes. */
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
this.listeners.clear();
|
||||
}
|
||||
}
|
||||
128
packages/core/src/webui/state-stream.ts
Normal file
128
packages/core/src/webui/state-stream.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Bind a StateBus to an SSE-friendly `send` callback: every publish becomes
|
||||
* a debounced fresh-snapshot frame, and `sendAllInitial()` primes a new
|
||||
* connection with one frame per resource.
|
||||
*
|
||||
* Decoupled from the HTTP layer so the route handler in server.ts can drop
|
||||
* its responsibility down to "open a ReadableStream, hand its enqueue to
|
||||
* bindStateStream, abort tears it down". Pure logic = unit-testable with
|
||||
* fake timers; no Response/controller mocking needed.
|
||||
*
|
||||
* Per-resource debounce, not global: an 'qq-list' churn during a slow
|
||||
* 'processes' burst must not delay the qq-list frame, and a 'connections'
|
||||
* diff loop running at 500ms must not coalesce 10 unrelated processes
|
||||
* events into one. Each resource is its own timer.
|
||||
*/
|
||||
|
||||
import type { StateBus, StateResource } from './state-bus';
|
||||
|
||||
export interface StateStreamFrame {
|
||||
resource: StateResource;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
export interface BindStateStreamOptions {
|
||||
bus: StateBus;
|
||||
/** Read the current snapshot for one resource. May be sync or async. */
|
||||
snapshot: (resource: StateResource) => unknown | Promise<unknown>;
|
||||
/** Receive a fresh frame; called once per debounced publish.
|
||||
* Exceptions are caught — a dead controller must not abort the bus
|
||||
* subscription or break sibling resources. */
|
||||
send: (frame: StateStreamFrame) => void;
|
||||
/** Coalesce window in milliseconds; default 50. */
|
||||
debounceMs?: number;
|
||||
}
|
||||
|
||||
export interface StateStreamHandle {
|
||||
/** Emit one frame per resource using the current snapshot. Use on connect. */
|
||||
sendAllInitial(): Promise<void>;
|
||||
/** Stop subscribing + cancel pending timers. Subsequent bus publishes
|
||||
* produce nothing through this binding. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connections'];
|
||||
|
||||
export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle {
|
||||
const debounceMs = opts.debounceMs ?? 50;
|
||||
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
|
||||
// Single-flight per resource: at most one in-flight flush per resource so
|
||||
// an uneven snapshot latency cannot interleave sends out of order (a slow
|
||||
// earlier snapshot landing AFTER a later one, leaving the client's last
|
||||
// observed frame stale). Publishes arriving while a flush is in flight
|
||||
// mark `pending` and rearm the debounce timer once the flush completes.
|
||||
const inFlight = new Set<StateResource>();
|
||||
const pending = new Set<StateResource>();
|
||||
let disposed = false;
|
||||
|
||||
const flush = async (resource: StateResource): Promise<void> => {
|
||||
if (disposed) return;
|
||||
inFlight.add(resource);
|
||||
try {
|
||||
let data: unknown;
|
||||
try {
|
||||
data = await opts.snapshot(resource);
|
||||
} catch {
|
||||
// Per-resource snapshot failure (e.g. listProcesses threw): skip
|
||||
// this frame so siblings keep flowing. The next publish for the
|
||||
// same resource gets a fresh attempt.
|
||||
return;
|
||||
}
|
||||
if (disposed) return;
|
||||
try {
|
||||
opts.send({ resource, data });
|
||||
} catch {
|
||||
// Downstream consumer (e.g. closed SSE controller) — same isolation
|
||||
// contract as snapshot failures.
|
||||
}
|
||||
} finally {
|
||||
inFlight.delete(resource);
|
||||
// If a publish arrived during the in-flight window, schedule one
|
||||
// follow-up flush. Re-uses the debounce so a sustained publish
|
||||
// stream produces at most one frame per (debounceMs + flushLatency),
|
||||
// not back-to-back frames.
|
||||
if (!disposed && pending.has(resource)) {
|
||||
pending.delete(resource);
|
||||
schedule(resource);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const schedule = (resource: StateResource): void => {
|
||||
if (disposed) return;
|
||||
if (inFlight.has(resource)) {
|
||||
// Defer to the post-flush re-arm; no new timer until the in-flight
|
||||
// send completes. This is the load-bearing invariant for ordering.
|
||||
pending.add(resource);
|
||||
return;
|
||||
}
|
||||
const existing = timers.get(resource);
|
||||
if (existing) clearTimeout(existing);
|
||||
const t = setTimeout(() => {
|
||||
timers.delete(resource);
|
||||
void flush(resource);
|
||||
}, debounceMs);
|
||||
timers.set(resource, t);
|
||||
};
|
||||
|
||||
const unsubscribe = opts.bus.subscribe(schedule);
|
||||
|
||||
return {
|
||||
async sendAllInitial(): Promise<void> {
|
||||
if (disposed) return;
|
||||
// Fire all three in parallel. Each resource's snapshot is independent
|
||||
// so a slow listProcesses() doesn't gate qq-list/connections. Each
|
||||
// call goes through the single-flight gate so a concurrent bus
|
||||
// publish during this initial fan-out coalesces correctly.
|
||||
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
|
||||
},
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
unsubscribe();
|
||||
for (const t of timers.values()) clearTimeout(t);
|
||||
timers.clear();
|
||||
pending.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
73
packages/core/src/webui/state-wiring.ts
Normal file
73
packages/core/src/webui/state-wiring.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* State-wiring — couples the publisher edges (HookManager session events,
|
||||
* BridgeManager session-started / session-closed) to a fresh StateBus so the
|
||||
* `/api/state/stream` SSE handler can push snapshot invalidations to the
|
||||
* WebUI without REST polling.
|
||||
*
|
||||
* Decoupling rationale:
|
||||
* - HookManager owns the per-process state-machine; it knows when a
|
||||
* session's `listProcesses()` view changes. We feed it `onSessionsChanged`
|
||||
* (callable from outside the bridge package) so this file is the ONLY
|
||||
* place that imports both the bus and HookManager's dep shape.
|
||||
* - BridgeManager fires `session-started` / `session-closed` listeners on
|
||||
* account edges (the OneBot instance list mutates around these). We add
|
||||
* listeners directly so `qq-list` + `connections` invalidate at the right
|
||||
* moment without modifying BridgeManager.
|
||||
*
|
||||
* `dispose()` unwires everything so a test (or a future hot-reload) can
|
||||
* recreate the wiring without leaking listeners.
|
||||
*/
|
||||
|
||||
import { StateBus } from './state-bus';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
|
||||
export interface StateWiring {
|
||||
/** The bus the SSE handler subscribes to. */
|
||||
readonly bus: StateBus;
|
||||
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
|
||||
onSessionsChanged: () => void;
|
||||
/** Hook into a BridgeManager so its session edges publish 'qq-list' and
|
||||
* 'connections'. Can be called at most once per wiring (subsequent calls
|
||||
* add duplicate listeners). */
|
||||
bindBridgeManager(bm: BridgeManager): void;
|
||||
/** Drop every listener + neuter the bus so further publishes do nothing. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function createStateWiring(): StateWiring {
|
||||
const bus = new StateBus();
|
||||
let disposed = false;
|
||||
|
||||
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
|
||||
if (disposed) return;
|
||||
bus.publish(resource);
|
||||
};
|
||||
|
||||
return {
|
||||
bus,
|
||||
onSessionsChanged: () => publish('processes'),
|
||||
bindBridgeManager(bm: BridgeManager): void {
|
||||
// Account appeared: the qq-list response gains an entry and the
|
||||
// connections response gains the new account's adapter row. Two
|
||||
// distinct resource invalidations, in source-of-truth order
|
||||
// (account exists → only then can adapters be enumerated for it).
|
||||
bm.addSessionStartedListener(() => {
|
||||
publish('qq-list');
|
||||
publish('connections');
|
||||
});
|
||||
// Account disappeared: same two resources shrink, same order so a
|
||||
// racy WebUI receiving both events independently sees the qq-list
|
||||
// shrink before it tries to render connections for a uin that's
|
||||
// about to vanish.
|
||||
bm.addSessionClosedListener(() => {
|
||||
publish('qq-list');
|
||||
publish('connections');
|
||||
});
|
||||
},
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
bus.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { boolOr, clampInt, clampNum, isObject } from '@snowluma/common/coerce';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
@@ -308,10 +309,8 @@ function defaultPages(): UiPages {
|
||||
}
|
||||
|
||||
// ─── Normalization helpers ─────────────────────────────────────────────────
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
// isObject / boolOr / clampNum / clampInt come from @snowluma/common/coerce.
|
||||
// oneOf (enum), isFiniteNum, and hexOr (CSS color) are ui-specific and stay.
|
||||
|
||||
function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
|
||||
return typeof value === 'string' && (allowed as readonly string[]).includes(value)
|
||||
@@ -319,25 +318,11 @@ function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback
|
||||
: fallback;
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
function clampInt(value: unknown, min: number, max: number, fallback: number): number {
|
||||
return Math.trunc(clampNum(value, min, max, fallback));
|
||||
}
|
||||
|
||||
function isFiniteNum(value: unknown): boolean {
|
||||
if (typeof value === 'number') return Number.isFinite(value);
|
||||
return typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value));
|
||||
}
|
||||
|
||||
function boolOr(value: unknown, fallback: boolean): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
||||
function hexOr(value: unknown, fallback: string): string {
|
||||
return typeof value === 'string' && HEX_RE.test(value.trim()) ? value.trim() : fallback;
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
// "无法检查更新" rather than nagging).
|
||||
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
|
||||
|
||||
const log = createLogger('Update');
|
||||
|
||||
@@ -79,8 +80,22 @@ export function compareVersions(a: string, b: string): number {
|
||||
return pa.pre < pb.pre ? -1 : 1;
|
||||
}
|
||||
|
||||
let cache: UpdateCheckResult | null = null;
|
||||
let inflight: Promise<UpdateCheckResult> | null = null;
|
||||
// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's
|
||||
// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results
|
||||
// are intentionally not cached (shouldCache) so the next check retries.
|
||||
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
|
||||
ttlMs: CACHE_TTL_MS,
|
||||
shouldCache: (r) => !r.error,
|
||||
load: async (current) => {
|
||||
const result = await fetchLatest(current);
|
||||
if (result.error) {
|
||||
log.debug('update check failed: %s', result.error);
|
||||
} else if (result.hasUpdate) {
|
||||
log.info('a newer release is available: v%s (running v%s)', result.latest, current);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
});
|
||||
|
||||
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
const base: UpdateCheckResult = {
|
||||
@@ -133,21 +148,7 @@ export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
|
||||
if (!isEnabled()) {
|
||||
return { ...emptyResult(current), error: 'disabled' };
|
||||
}
|
||||
if (!force && cache && Date.now() - cache.checkedAt < CACHE_TTL_MS) return cache;
|
||||
if (inflight) return inflight;
|
||||
inflight = (async () => {
|
||||
const result = await fetchLatest(current);
|
||||
if (result.error) {
|
||||
log.debug('update check failed: %s', result.error);
|
||||
} else {
|
||||
cache = result; // only cache good results so transient errors retry
|
||||
if (result.hasUpdate) log.info('a newer release is available: v%s (running v%s)', result.latest, current);
|
||||
}
|
||||
return result;
|
||||
})().finally(() => {
|
||||
inflight = null;
|
||||
});
|
||||
return inflight;
|
||||
return updateCache.get(current, { force });
|
||||
}
|
||||
|
||||
function emptyResult(current: string): UpdateCheckResult {
|
||||
|
||||
@@ -65,6 +65,7 @@ export interface MockGroupFileApi {
|
||||
upload: ReturnType<typeof vi.fn>;
|
||||
uploadPrivate: ReturnType<typeof vi.fn>;
|
||||
publish: ReturnType<typeof vi.fn>;
|
||||
trans: ReturnType<typeof vi.fn>;
|
||||
getCount: ReturnType<typeof vi.fn>;
|
||||
list: ReturnType<typeof vi.fn>;
|
||||
getUrl: ReturnType<typeof vi.fn>;
|
||||
@@ -85,6 +86,7 @@ export function mockGroupFileApi(): MockGroupFileApi {
|
||||
upload: vi.fn(async () => ({ fileId: 'stub-fid' })),
|
||||
uploadPrivate: vi.fn(async () => ({ fileId: 'stub-pfid', fileHash: 'stub-hash' })),
|
||||
publish: vi.fn(async () => undefined),
|
||||
trans: vi.fn(async () => ({ saveBusId: 102, saveFilePath: '/stub-path' })),
|
||||
getCount: vi.fn(async () => ({ fileCount: 0, maxCount: 10000 })),
|
||||
list: vi.fn(async () => ({ files: [], folders: [] })),
|
||||
getUrl: vi.fn(async () => 'stub://url'),
|
||||
@@ -124,7 +126,9 @@ export interface MockBridge {
|
||||
findUidByUin: ReturnType<typeof vi.fn>;
|
||||
findUinByUid: ReturnType<typeof vi.fn>;
|
||||
findGroupMember: ReturnType<typeof vi.fn>;
|
||||
forgetGroup: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
events: { emit: ReturnType<typeof vi.fn> };
|
||||
apis: MockApiHub;
|
||||
sendRawPacket: ReturnType<typeof vi.fn>;
|
||||
fetchFriendList: ReturnType<typeof vi.fn>;
|
||||
@@ -154,8 +158,10 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
|
||||
findUidByUin: vi.fn(() => 'cached-uid'),
|
||||
findUinByUid: vi.fn(() => 0),
|
||||
findGroupMember: vi.fn(() => null),
|
||||
forgetGroup: vi.fn(),
|
||||
...(overrides.identity ?? {}),
|
||||
} as MockBridge['identity'],
|
||||
events: overrides.events ?? { emit: vi.fn(async () => undefined) },
|
||||
apis: overrides.apis ?? mockApiHub(),
|
||||
sendRawPacket: vi.fn(async () => defaultResp),
|
||||
fetchFriendList: vi.fn(async () => []),
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
// split.
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { gunzipSync } from 'zlib';
|
||||
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
@@ -44,8 +45,9 @@ vi.mock('@snowluma/protocol/element-builder', () => ({
|
||||
buildSendElems: buildSendElemsMock,
|
||||
}));
|
||||
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { LongMsgResult, SendLongMsgReq, SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
|
||||
import type { FileExtra } from '@snowluma/proto-defs/message';
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
@@ -60,6 +62,13 @@ function uploadResponseWithResId(resId: string) {
|
||||
};
|
||||
}
|
||||
|
||||
function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult {
|
||||
const env = protobuf_decode<SendLongMsgReq>(rawBytes);
|
||||
const payload = env.info?.payload;
|
||||
if (!(payload instanceof Uint8Array)) throw new Error('payload missing on SendLongMsgReq');
|
||||
return protobuf_decode<LongMsgResult>(gunzipSync(Buffer.from(payload)));
|
||||
}
|
||||
|
||||
describe('actions/forward — file segment inside forward node', () => {
|
||||
it('group forward sets forwardFake:true on the SendContext so transElem(24) is emitted', async () => {
|
||||
// Group case: the file element rides on elems[] as transElem(24).
|
||||
@@ -120,18 +129,19 @@ describe('actions/forward — file segment inside forward node', () => {
|
||||
expect(ctx).toMatchObject({ forwardFake: true });
|
||||
expect(ctx?.groupId).toBeUndefined();
|
||||
|
||||
// Spot-check that the upload body carries the file metadata. The
|
||||
// payload is gzipped + protobuf-wrapped, so we just verify the
|
||||
// raw filename string survived — that's enough to confirm the
|
||||
// FileExtra branch ran (a "missing file" regression would drop
|
||||
// these bytes entirely).
|
||||
expect(captured).toBeDefined();
|
||||
const flat = Buffer.from(captured!).toString('binary');
|
||||
// The filename gets gzipped, so we can't substring-search; instead
|
||||
// assert the body is large enough that the FileExtra wasn't elided.
|
||||
// (A name-only forward with no msgContent runs ~80-100 bytes; with
|
||||
// the FileExtra blob it's noticeably larger.)
|
||||
expect(flat.length).toBeGreaterThan(80);
|
||||
const longMsg = decodeLongMsgRequest(captured!);
|
||||
const body = longMsg.action?.[0]?.actionData?.msgBody?.[0]?.body;
|
||||
expect(body?.msgContent).toBeInstanceOf(Uint8Array);
|
||||
expect(body?.richText?.notOnlineFile ?? undefined).toBeUndefined();
|
||||
|
||||
const fileExtra = protobuf_decode<FileExtra>(body!.msgContent as Uint8Array);
|
||||
expect(fileExtra.file).toMatchObject({
|
||||
fileUuid: 'pfid-1',
|
||||
fileName: 'invoice.pdf',
|
||||
fileHash: 'srv-hash-abc',
|
||||
});
|
||||
expect(fileExtra.file?.fileSize).toBe(4096n);
|
||||
});
|
||||
|
||||
it('c2c forward falls back to the upload metadata cache when inline fields are missing', async () => {
|
||||
@@ -165,4 +175,190 @@ describe('actions/forward — file segment inside forward node', () => {
|
||||
|
||||
expect(recallUploadedFile).toHaveBeenCalledWith('pfid-cached');
|
||||
});
|
||||
|
||||
it('group forward pre-uploads file sources into the target group without publishing a separate file message', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
const upload = vi.fn(async () => ({ fileId: 'gfid-from-base64' }));
|
||||
const publish = vi.fn();
|
||||
const bridge = mockBridge({
|
||||
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-grp-source')) as any,
|
||||
apis: {
|
||||
...mockBridge().apis,
|
||||
groupFile: {
|
||||
...mockBridge().apis.groupFile,
|
||||
upload,
|
||||
publish,
|
||||
},
|
||||
},
|
||||
recallUploadedFile: vi.fn((id: string) => id === 'gfid-from-base64' ? {
|
||||
fileId: 'gfid-from-base64',
|
||||
scope: 'group' as const,
|
||||
groupId: 12345,
|
||||
fileName: 'note.txt',
|
||||
fileSize: 3,
|
||||
fileMd5: new Uint8Array(16),
|
||||
fileSha1: new Uint8Array(20),
|
||||
rememberedAt: 0,
|
||||
} : undefined),
|
||||
});
|
||||
|
||||
await new ForwardApi(bridge as any).upload([{
|
||||
userUin: 10001,
|
||||
nickname: 'alice',
|
||||
elements: [{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' } as any],
|
||||
}], 12345);
|
||||
|
||||
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false);
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
const [elements] = buildSendElemsMock.mock.calls[0]!;
|
||||
expect(elements).toEqual([expect.objectContaining({
|
||||
type: 'file',
|
||||
fileId: 'gfid-from-base64',
|
||||
fileName: 'note.txt',
|
||||
fileSize: 3,
|
||||
})]);
|
||||
});
|
||||
|
||||
it('private forward pre-uploads file sources without sending a standalone c2c file message', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
const uploadPrivate = vi.fn(async () => ({ fileId: 'pfid-from-base64', fileHash: 'phash' }));
|
||||
const sendC2cFile = vi.fn();
|
||||
const bridge = mockBridge({
|
||||
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-c2c-source')) as any,
|
||||
apis: {
|
||||
...mockBridge().apis,
|
||||
message: {
|
||||
...mockBridge().apis.message,
|
||||
sendC2cFile,
|
||||
},
|
||||
groupFile: {
|
||||
...mockBridge().apis.groupFile,
|
||||
uploadPrivate,
|
||||
},
|
||||
},
|
||||
recallUploadedFile: vi.fn((id: string) => id === 'pfid-from-base64' ? {
|
||||
fileId: 'pfid-from-base64',
|
||||
scope: 'private' as const,
|
||||
userId: 67890,
|
||||
fileName: 'note.txt',
|
||||
fileSize: 3,
|
||||
fileMd5: new Uint8Array(16),
|
||||
fileSha1: new Uint8Array(20),
|
||||
fileHash: 'phash',
|
||||
rememberedAt: 0,
|
||||
} : undefined),
|
||||
});
|
||||
|
||||
await new ForwardApi(bridge as any).upload([{
|
||||
userUin: 10001,
|
||||
nickname: 'alice',
|
||||
elements: [{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' } as any],
|
||||
}], undefined, 67890);
|
||||
|
||||
expect(uploadPrivate).toHaveBeenCalledWith(67890, 'base64://AQID', 'note.txt', true, false);
|
||||
expect(sendC2cFile).not.toHaveBeenCalled();
|
||||
const [elements] = buildSendElemsMock.mock.calls[0]!;
|
||||
expect(elements).toEqual([expect.objectContaining({
|
||||
type: 'file',
|
||||
fileId: 'pfid-from-base64',
|
||||
fileName: 'note.txt',
|
||||
fileSize: 3,
|
||||
fileHash: 'phash',
|
||||
})]);
|
||||
});
|
||||
|
||||
it('private file forward keeps the long-msg upload under the self uid namespace', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
let captured: Uint8Array | undefined;
|
||||
const bridge = mockBridge({
|
||||
sendRawPacket: vi.fn(async (_cmd: string, body: Uint8Array) => {
|
||||
captured = body;
|
||||
return uploadResponseWithResId('res-c2c-target-uid');
|
||||
}) as any,
|
||||
resolveUserUid: vi.fn(async () => 'target-uid'),
|
||||
recallUploadedFile: vi.fn((id: string) => id === 'pfid-1' ? {
|
||||
fileId: 'pfid-1',
|
||||
scope: 'private' as const,
|
||||
userId: 67890,
|
||||
fileName: 'invoice.pdf',
|
||||
fileSize: 4096,
|
||||
fileMd5: new Uint8Array(16),
|
||||
fileSha1: new Uint8Array(20),
|
||||
fileHash: 'srv-hash',
|
||||
rememberedAt: 0,
|
||||
} : undefined),
|
||||
});
|
||||
|
||||
await new ForwardApi(bridge as any).upload([{
|
||||
userUin: 10001,
|
||||
nickname: 'alice',
|
||||
elements: [{ type: 'file', fileId: 'pfid-1' } as any],
|
||||
}], undefined, 67890);
|
||||
|
||||
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
|
||||
expect(captured).toBeDefined();
|
||||
const request = protobuf_decode<SendLongMsgReq>(captured!);
|
||||
expect(request.info?.uid?.uid).toBe('self-uid');
|
||||
});
|
||||
|
||||
it('group forward re-uploads a cached private file_id into the target group scope', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
const getPrivateUrl = vi.fn(async () => 'https://download.test/private-file');
|
||||
const upload = vi.fn(async () => ({ fileId: 'gfid-reuploaded' }));
|
||||
const bridge = mockBridge({
|
||||
sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-cross-scope')) as any,
|
||||
apis: {
|
||||
...mockBridge().apis,
|
||||
groupFile: {
|
||||
...mockBridge().apis.groupFile,
|
||||
getPrivateUrl,
|
||||
upload,
|
||||
},
|
||||
},
|
||||
recallUploadedFile: vi.fn((id: string) => {
|
||||
if (id === 'pfid-cached') {
|
||||
return {
|
||||
fileId: 'pfid-cached',
|
||||
scope: 'private' as const,
|
||||
userId: 67890,
|
||||
fileName: 'cached.txt',
|
||||
fileSize: 5,
|
||||
fileMd5: new Uint8Array(16),
|
||||
fileSha1: new Uint8Array(20),
|
||||
fileHash: 'cached-hash',
|
||||
rememberedAt: 0,
|
||||
};
|
||||
}
|
||||
if (id === 'gfid-reuploaded') {
|
||||
return {
|
||||
fileId: 'gfid-reuploaded',
|
||||
scope: 'group' as const,
|
||||
groupId: 12345,
|
||||
fileName: 'cached.txt',
|
||||
fileSize: 5,
|
||||
fileMd5: new Uint8Array(16),
|
||||
fileSha1: new Uint8Array(20),
|
||||
rememberedAt: 1,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}),
|
||||
});
|
||||
|
||||
await new ForwardApi(bridge as any).upload([{
|
||||
userUin: 10001,
|
||||
nickname: 'alice',
|
||||
elements: [{ type: 'file', fileId: 'pfid-cached' } as any],
|
||||
}], 12345);
|
||||
|
||||
expect(getPrivateUrl).toHaveBeenCalledWith(67890, 'pfid-cached', 'cached-hash');
|
||||
expect(upload).toHaveBeenCalledWith(12345, 'https://download.test/private-file', 'cached.txt', '/', true, false);
|
||||
const [elements] = buildSendElemsMock.mock.calls[0]!;
|
||||
expect(elements).toEqual([expect.objectContaining({
|
||||
type: 'file',
|
||||
fileId: 'gfid-reuploaded',
|
||||
fileName: 'cached.txt',
|
||||
fileSize: 5,
|
||||
})]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,8 +14,10 @@ vi.mock('@snowluma/protocol/element-builder', () => ({
|
||||
buildSendElems: vi.fn(async () => []),
|
||||
}));
|
||||
|
||||
import { gzipSync } from 'zlib';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
|
||||
import type { SendLongMsgResp, LongMsgResult, RecvLongMsgResp } from '@snowluma/proto-defs/longmsg';
|
||||
import type { PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
@@ -30,6 +32,16 @@ function uploadResponseWithResId(resId: string) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Build an SsoRecvLongMsg response wrapping the given forward nodes. */
|
||||
function recvLongMsgResp(bodies: PushMsgBody[]) {
|
||||
const longMsg: LongMsgResult = {
|
||||
action: [{ actionCommand: 'MultiMsg', actionData: { msgBody: bodies } }],
|
||||
};
|
||||
const gz = gzipSync(Buffer.from(protobuf_encode<LongMsgResult>(longMsg)));
|
||||
const resp = protobuf_encode<RecvLongMsgResp>({ result: { payload: new Uint8Array(gz) } });
|
||||
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.from(resp) };
|
||||
}
|
||||
|
||||
describe('actions/forward', () => {
|
||||
it('uploadForwardNodes rejects empty arrays', async () => {
|
||||
const bridge = mockBridge();
|
||||
@@ -94,6 +106,26 @@ describe('actions/forward', () => {
|
||||
expect(sendRawPacket).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('[#201] fills a group forward node nickname from grp.groupName when memberName is empty', async () => {
|
||||
// Real merged-forward nodes leave grp.memberName (field 2) null and carry the
|
||||
// sender display name in grp.memberCard (field 4). Verified on-target: fromUin
|
||||
// 1787882683 ↔ grp.memberCard "墨梓柒". Before the fix the node nickname came
|
||||
// back "" and enrichSenders 0x899-AUTHORITY_FAIL'd on the placeholder group.
|
||||
const node: PushMsgBody = {
|
||||
responseHead: { fromUin: 1787882683, fromUid: 'u_x', grp: { groupUin: 284840486, memberCard: '墨梓柒' } },
|
||||
contentHead: { msgType: 82, sequence: 1, timestamp: 100 }, // 82 = PkgType.GroupMessage
|
||||
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
|
||||
};
|
||||
const bridge = mockBridge({ sendRawPacket: vi.fn(async () => recvLongMsgResp([node])) as any });
|
||||
const nodes = await new ForwardApi(bridge as any).fetch('res-201');
|
||||
expect(nodes).toHaveLength(1);
|
||||
expect(nodes[0]!.userUin).toBe(1787882683);
|
||||
expect(nodes[0]!.nickname).toBe('墨梓柒'); // was '' before the fix
|
||||
expect(nodes[0]!.groupId).toBe(284840486);
|
||||
// The nickname is present, so no group-member-list enrichment fetch fires.
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('fetchForwardNodes throws on transport failure when nothing is cached', async () => {
|
||||
const bridge = mockBridge({
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
@@ -151,3 +183,71 @@ describe('actions/forward', () => {
|
||||
expect(sendRawPacket).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe('actions/forward — sender name enrichment (#174)', () => {
|
||||
function apiWith(contacts: { fetchGroupMemberList: any; fetchUserProfile: any }) {
|
||||
return new ForwardApi({ apis: { contacts } } as any);
|
||||
}
|
||||
|
||||
it('fills empty / "QQ用户" names via the group member list (L3), card preferred', async () => {
|
||||
const fetchGroupMemberList = vi.fn(async () => [
|
||||
{ uin: 10001, nickname: 'AliceNick', card: 'AliceCard' },
|
||||
{ uin: 10002, nickname: 'BobNick', card: '' },
|
||||
]);
|
||||
const fetchUserProfile = vi.fn(async (uin: number) => ({ uin, nickname: 'Stranger' }));
|
||||
const api = apiWith({ fetchGroupMemberList, fetchUserProfile });
|
||||
|
||||
const nodes: any[] = [
|
||||
{ userUin: 10001, nickname: '', groupId: 700, messageType: 'group', elements: [] },
|
||||
{ userUin: 10002, nickname: 'QQ用户', groupId: 700, messageType: 'group', elements: [] },
|
||||
{ userUin: 10003, nickname: '', groupId: 700, messageType: 'group', elements: [] }, // not in list
|
||||
{ userUin: 10009, nickname: '', messageType: 'private', elements: [] }, // private
|
||||
{ userUin: 10005, nickname: 'KeepMe', groupId: 700, messageType: 'group', elements: [] },
|
||||
];
|
||||
const changed = await (api as any).enrichSenders(nodes);
|
||||
|
||||
expect(changed).toBe(true);
|
||||
expect(nodes[0].nickname).toBe('AliceCard'); // card preferred over nick
|
||||
expect(nodes[0].senderCard).toBe('AliceCard');
|
||||
expect(nodes[1].nickname).toBe('BobNick'); // card empty → nickname
|
||||
expect(nodes[2].nickname).toBe('Stranger'); // not in member list → L4 profile
|
||||
expect(nodes[3].nickname).toBe('Stranger'); // private node → L4 profile
|
||||
expect(nodes[4].nickname).toBe('KeepMe'); // already named → untouched
|
||||
expect(fetchGroupMemberList).toHaveBeenCalledTimes(1); // one fetch covers the whole group
|
||||
});
|
||||
|
||||
it('is a no-op (no fetch) when every node already has a name', async () => {
|
||||
const fetchGroupMemberList = vi.fn();
|
||||
const fetchUserProfile = vi.fn();
|
||||
const api = apiWith({ fetchGroupMemberList, fetchUserProfile });
|
||||
const nodes: any[] = [{ userUin: 1, nickname: 'has-name', groupId: 7, messageType: 'group', elements: [] }];
|
||||
expect(await (api as any).enrichSenders(nodes)).toBe(false);
|
||||
expect(fetchGroupMemberList).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the placeholder and never throws when resolution fails', async () => {
|
||||
const api = apiWith({
|
||||
fetchGroupMemberList: vi.fn(async () => { throw new Error('net down'); }),
|
||||
fetchUserProfile: vi.fn(async () => { throw new Error('net down'); }),
|
||||
});
|
||||
const nodes: any[] = [{ userUin: 10001, nickname: 'QQ用户', groupId: 700, messageType: 'group', elements: [] }];
|
||||
await expect((api as any).enrichSenders(nodes)).resolves.toBe(false);
|
||||
expect(nodes[0].nickname).toBe('QQ用户');
|
||||
});
|
||||
|
||||
it('does NOT fan a member-list failure out to per-uin profile lookups (rate-limit guard)', async () => {
|
||||
const fetchUserProfile = vi.fn(async (uin: number) => ({ uin, nickname: 'X' }));
|
||||
const api = apiWith({
|
||||
fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }),
|
||||
fetchUserProfile,
|
||||
});
|
||||
// 5 distinct group senders whose member list errors → must keep placeholder,
|
||||
// NOT trigger 5 profile calls.
|
||||
const nodes: any[] = Array.from({ length: 5 }, (_, i) => ({
|
||||
userUin: 20000 + i, nickname: '', groupId: 700, messageType: 'group', elements: [],
|
||||
}));
|
||||
expect(await (api as any).enrichSenders(nodes)).toBe(false);
|
||||
expect(fetchUserProfile).not.toHaveBeenCalled();
|
||||
expect(nodes.every((n) => n.nickname === '')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -88,13 +88,24 @@ describe('apis/group-admin', () => {
|
||||
expect(env.body?.rejectAddRequest ?? 0).toBe(0);
|
||||
});
|
||||
|
||||
it('leave sends 0x1097_1 with the groupUin', async () => {
|
||||
it('leave sends 0x1097_1, emits a self group_member_leave, and forgets the group (#133)', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new GroupAdminApi(bridge as any).leave(12345);
|
||||
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
expect(cmd).toBe('OidbSvcTrpcTcp.0x1097_1');
|
||||
const env = protobuf_decode<OidbBase<OidbLeaveGroup>>(bytes);
|
||||
expect(env.body).toMatchObject({ groupUin: 12345 });
|
||||
|
||||
// The server never pushes a member-decrease for our own voluntary leave, so
|
||||
// the bridge synthesizes it (self user_id/operator_id) and drops the group.
|
||||
expect(bridge.events.emit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
kind: 'group_member_leave',
|
||||
groupId: 12345,
|
||||
userUin: 10001,
|
||||
operatorUin: 10001,
|
||||
leaveType: 'leave',
|
||||
}));
|
||||
expect(bridge.identity.forgetGroup).toHaveBeenCalledWith(12345);
|
||||
});
|
||||
|
||||
it('setAdmin resolves UID and sends 0x1096_1', async () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
OidbGroupFileViewResp,
|
||||
OidbGroupFileFolderResp,
|
||||
OidbGroupSendFileReq,
|
||||
OidbGroupSendFileResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-file';
|
||||
import type {
|
||||
OidbPrivateFileUploadResp,
|
||||
@@ -25,19 +26,32 @@ import type {
|
||||
vi.mock('@snowluma/protocol/highway', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({})),
|
||||
uploadHighwayHttp: vi.fn(async () => undefined),
|
||||
FileChunkSource: { open: vi.fn(async () => ({ size: 3, read: vi.fn(), close: vi.fn(async () => undefined) })) },
|
||||
}));
|
||||
|
||||
vi.mock('@snowluma/protocol/highway/utils', () => ({
|
||||
loadBinarySource: vi.fn(async (_src: string, fallback: string) => ({
|
||||
bytes: new Uint8Array([1, 2, 3]),
|
||||
fileName: `${fallback}.bin`,
|
||||
})),
|
||||
computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })),
|
||||
computeMd5: vi.fn(() => new Uint8Array(16)),
|
||||
FILE_UPLOAD_MAX_BYTES: 4 * 1024 * 1024 * 1024,
|
||||
}));
|
||||
|
||||
// The upload path now stages the source to disk + stream-hashes it; mock those
|
||||
// two seams. stageSourceToDisk's filePath must be a REAL file so the mutation
|
||||
// guard's fsp.stat succeeds (configured per-test in beforeEach → STAGED_FILE).
|
||||
vi.mock('@snowluma/protocol/highway/stage', () => ({
|
||||
stageSourceToDisk: vi.fn(),
|
||||
}));
|
||||
vi.mock('@snowluma/protocol/highway/hash-file', () => ({
|
||||
hashFileStreaming: vi.fn(async () => ({
|
||||
md5: new Uint8Array(16), sha1: new Uint8Array(20),
|
||||
md5Hex: '00'.repeat(16), sha1Hex: '00'.repeat(20),
|
||||
sha1Blocks: [], headMd5: new Uint8Array(16),
|
||||
})),
|
||||
}));
|
||||
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import * as highwayClient from '@snowluma/protocol/highway';
|
||||
import * as stageMod from '@snowluma/protocol/highway/stage';
|
||||
import { GroupFileApi } from '../../src/bridge/apis/group-file';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
@@ -48,10 +62,23 @@ function packResponse(body: Uint8Array) {
|
||||
};
|
||||
}
|
||||
|
||||
let STAGED_FILE: string;
|
||||
|
||||
describe('apis/group-file', () => {
|
||||
beforeAll(() => {
|
||||
STAGED_FILE = path.join(os.tmpdir(), `sl-gf-staged-${process.pid}.bin`);
|
||||
fs.writeFileSync(STAGED_FILE, Buffer.from([1, 2, 3])); // real 3-byte file for the guard stat
|
||||
});
|
||||
afterAll(() => { try { fs.unlinkSync(STAGED_FILE); } catch { /* ignore */ } });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
|
||||
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
|
||||
vi.mocked(highwayClient.FileChunkSource.open).mockClear();
|
||||
vi.mocked(stageMod.stageSourceToDisk).mockResolvedValue({
|
||||
filePath: STAGED_FILE, fileSize: 3, fileName: 'file.bin',
|
||||
cleanup: vi.fn(async () => undefined),
|
||||
} as any);
|
||||
});
|
||||
|
||||
it('getCount returns { fileCount, maxCount } from the OIDB response', async () => {
|
||||
@@ -117,6 +144,32 @@ describe('apis/group-file', () => {
|
||||
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('[stream] PUTs from the staged disk file via FileChunkSource and releases the temp', async () => {
|
||||
const cleanup = vi.fn(async () => undefined);
|
||||
vi.mocked(stageMod.stageSourceToDisk).mockResolvedValueOnce({
|
||||
filePath: STAGED_FILE, fileSize: 3, fileName: 'file.bin', cleanup,
|
||||
} as any);
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbGroupFileResp>>({
|
||||
body: {
|
||||
upload: {
|
||||
fileId: 'fid-xyz', uploadIp: '1.2.3.4', uploadPort: 8080,
|
||||
fileKey: new Uint8Array([9]), checkKey: new Uint8Array([8]),
|
||||
},
|
||||
} as any,
|
||||
}),
|
||||
));
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
vi.spyOn(api, 'publish').mockResolvedValue();
|
||||
await api.upload(12345, '/path/file.bin');
|
||||
// Main file streamed from the staged path (not buffered), and the temp is
|
||||
// released afterward.
|
||||
expect(highwayClient.FileChunkSource.open).toHaveBeenCalledWith(STAGED_FILE, 3);
|
||||
expect(vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]![3]).toBeDefined();
|
||||
expect(cleanup).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('upload throws on missing upload response', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
@@ -170,6 +223,28 @@ describe('apis/group-file', () => {
|
||||
expect(publishSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('upload can PUT bytes without publishing a separate group file message', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbGroupFileResp>>({
|
||||
body: {
|
||||
upload: {
|
||||
fileId: 'fid-forward',
|
||||
uploadIp: '127.0.0.1',
|
||||
uploadPort: 443,
|
||||
fileKey: new Uint8Array([1]),
|
||||
checkKey: new Uint8Array([2]),
|
||||
} as any,
|
||||
},
|
||||
}),
|
||||
));
|
||||
const api = new GroupFileApi(bridge as any);
|
||||
const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue();
|
||||
await api.upload(12345, 'base64://AQID', 'forward.txt', '/', true, false);
|
||||
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
|
||||
expect(publishSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('upload returns success even when the chat post fails (file is still uploaded)', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
@@ -224,6 +299,26 @@ describe('apis/group-file', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('trans hits OIDB 0x6d9_0 and returns the saved path metadata', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbGroupSendFileResp>>({
|
||||
body: { transFile: { saveBusId: 102, saveFilePath: '/saved/path' } },
|
||||
}),
|
||||
));
|
||||
const out = await new GroupFileApi(bridge as any).trans(12345, 'fid-trans');
|
||||
expect(out).toEqual({ saveBusId: 102, saveFilePath: '/saved/path' });
|
||||
const [wire, bytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
expect(wire).toBe('OidbSvcTrpcTcp.0x6d9_0');
|
||||
const env = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes);
|
||||
expect(env.body?.transFile).toMatchObject({
|
||||
groupUin: 12345n,
|
||||
appId: 7,
|
||||
busId: 102,
|
||||
fileId: 'fid-trans',
|
||||
});
|
||||
});
|
||||
|
||||
it('uploadPrivate resolves both target + self UID before OIDB call', async () => {
|
||||
const bridge = mockBridge({
|
||||
identity: {
|
||||
@@ -233,6 +328,7 @@ describe('apis/group-file', () => {
|
||||
findUidByUin: vi.fn(() => 'cached-uid'),
|
||||
findUinByUid: vi.fn(() => 0),
|
||||
findGroupMember: vi.fn(() => null),
|
||||
forgetGroup: vi.fn(),
|
||||
},
|
||||
});
|
||||
vi.mocked(bridge.resolveUserUid)
|
||||
@@ -297,6 +393,54 @@ describe('apis/group-file', () => {
|
||||
expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uploadPrivate can PUT bytes without publishing a separate c2c file message', async () => {
|
||||
const bridge = mockBridge();
|
||||
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
|
||||
body: {
|
||||
upload: {
|
||||
uuid: 'pfid-forward',
|
||||
fileAddon: 'phash-forward',
|
||||
rtpMediaPlatformUploadAddress: [
|
||||
{ outIP: 0, outPort: 0, inIP: 16885952, inPort: 8080, iPType: 1 },
|
||||
],
|
||||
mediaPlatformUploadKey: new Uint8Array([1, 2, 3]),
|
||||
} as any,
|
||||
},
|
||||
}),
|
||||
));
|
||||
await new GroupFileApi(bridge as any).uploadPrivate(67890, 'base64://AQID', 'forward.txt', true, false);
|
||||
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
|
||||
expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('[stream] uploadPrivate PUTs from the staged disk file via FileChunkSource and releases the temp', async () => {
|
||||
const cleanup = vi.fn(async () => undefined);
|
||||
vi.mocked(stageMod.stageSourceToDisk).mockResolvedValueOnce({
|
||||
filePath: STAGED_FILE, fileSize: 3, fileName: 'file.bin', cleanup,
|
||||
} as any);
|
||||
const bridge = mockBridge();
|
||||
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
|
||||
body: {
|
||||
upload: {
|
||||
uuid: 'pfid-stream', fileAddon: 'phash',
|
||||
rtpMediaPlatformUploadAddress: [
|
||||
{ outIP: 0, outPort: 0, inIP: 16885952, inPort: 8080, iPType: 1 },
|
||||
],
|
||||
mediaPlatformUploadKey: new Uint8Array([1, 2, 3]),
|
||||
} as any,
|
||||
},
|
||||
}),
|
||||
));
|
||||
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file', 'doc.pdf', true, false);
|
||||
expect(highwayClient.FileChunkSource.open).toHaveBeenCalledWith(STAGED_FILE, 3);
|
||||
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
|
||||
expect(cleanup).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uploadPrivate reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => {
|
||||
const bridge = mockBridge();
|
||||
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
|
||||
|
||||
@@ -28,6 +28,7 @@ vi.mock('@snowluma/protocol/bridge-oidb', async () => {
|
||||
vi.mock('@snowluma/protocol/highway', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({})),
|
||||
uploadHighwayHttp: vi.fn(async () => undefined),
|
||||
BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} },
|
||||
}));
|
||||
|
||||
vi.mock('@snowluma/protocol/highway/utils', () => ({
|
||||
|
||||
@@ -49,16 +49,65 @@ describe('apis/qzone', () => {
|
||||
expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20);
|
||||
});
|
||||
|
||||
it('publish posts to the bot\'s own space with the given content', async () => {
|
||||
it('uploadImageFromSource uploads from file:// http:// base64:// and returns richval + url', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK', skey: 'SK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const uploadSpy = vi.spyOn(qzoneWeb, 'uploadQzoneImageFromSource').mockResolvedValue({
|
||||
richval: ',12345,abc,abc,22,800,600,,800,600',
|
||||
url: 'https://example.com/img.jpg',
|
||||
albumid: '12345',
|
||||
lloc: 'abc',
|
||||
type: 22,
|
||||
width: 600,
|
||||
height: 800,
|
||||
});
|
||||
const out = await new QzoneApi(bridge as never).uploadImageFromSource('file:///path/to/image.jpg');
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(uploadSpy).toHaveBeenCalledWith({ p_skey: 'PSK', skey: 'SK' }, '10001', 'file:///path/to/image.jpg');
|
||||
expect(out.richval).toBe(',12345,abc,abc,22,800,600,,800,600');
|
||||
expect(out.url).toBe('https://example.com/img.jpg');
|
||||
});
|
||||
|
||||
it('publish posts to the bot\'s own space with the given content (text-only)', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 });
|
||||
const out = await new QzoneApi(bridge as never).publish('hello');
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello');
|
||||
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined, 1, undefined);
|
||||
expect(out).toEqual({ tid: 'T', time: 1 });
|
||||
});
|
||||
|
||||
it('publish posts with richtype and richval for image post', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T2', time: 2 });
|
||||
const richval = ',12345,abc,abc,22,800,600,,800,600';
|
||||
const out = await new QzoneApi(bridge as never).publish('look at this', 1, richval);
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'look at this', 1, richval, 1, undefined);
|
||||
expect(out).toEqual({ tid: 'T2', time: 2 });
|
||||
});
|
||||
|
||||
it('publish posts with multiple images (richval joined with tab)', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T3', time: 3 });
|
||||
const richval = ',12345,a,a,22,800,600,,800,600\t,12346,b,b,22,1024,768,,1024,768';
|
||||
const out = await new QzoneApi(bridge as never).publish('two images', 1, richval);
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'two images', 1, richval, 1, undefined);
|
||||
expect(out).toEqual({ tid: 'T3', time: 3 });
|
||||
});
|
||||
|
||||
it('publish threads qzone visibility params', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 });
|
||||
await new QzoneApi(bridge as never).publish('hello', undefined, undefined, 16, '10002|10003');
|
||||
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined, 16, '10002|10003');
|
||||
});
|
||||
|
||||
it('delete removes a feed by tid from the bot\'s own space', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
@@ -68,6 +117,16 @@ describe('apis/qzone', () => {
|
||||
expect(delSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'TID9');
|
||||
});
|
||||
|
||||
it('updateRight changes a feed\'s visibility on the bot\'s own space', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const updSpy = vi.spyOn(qzoneWeb, 'updateQzoneMsgRight').mockResolvedValue({ ugc_right: 16 });
|
||||
const out = await new QzoneApi(bridge as never).updateRight('TID9', 16, '10002|10003');
|
||||
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
|
||||
expect(updSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'TID9', 16, '10002|10003');
|
||||
expect(out).toEqual({ ugc_right: 16 });
|
||||
});
|
||||
|
||||
it('like defaults the feed owner to self and passes opUin=self + like flag', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
@@ -92,7 +151,7 @@ describe('apis/qzone', () => {
|
||||
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '1' });
|
||||
const out = await new QzoneApi(bridge as never).comment('TIDX', 'nice', undefined);
|
||||
// selfUin='10001' commenter; owner defaults to self
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice');
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice', undefined, undefined);
|
||||
expect(out).toEqual({ comment_id: '1' });
|
||||
});
|
||||
|
||||
@@ -101,6 +160,15 @@ describe('apis/qzone', () => {
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '2' });
|
||||
await new QzoneApi(bridge as never).comment('TIDX', 'nice', 20002);
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', 'nice');
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '20002', 'TIDX', 'nice', undefined, undefined);
|
||||
});
|
||||
|
||||
it('comment with images (richType=1, richval=direct URLs joined with tab)', async () => {
|
||||
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
|
||||
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
|
||||
const cmtSpy = vi.spyOn(qzoneWeb, 'commentQzoneMsg').mockResolvedValue({ comment_id: '3' });
|
||||
const richval = 'https://example.com/a.jpg\thttps://example.com/b.jpg';
|
||||
await new QzoneApi(bridge as never).comment('TIDX', 'nice pic', undefined, 1, richval);
|
||||
expect(cmtSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', '10001', 'TIDX', 'nice pic', 1, richval);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,15 +3,22 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
|
||||
import type { FileExtra } from '@snowluma/proto-defs/message';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-actions/media';
|
||||
|
||||
vi.mock('@snowluma/protocol/element-builder', () => ({
|
||||
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
|
||||
}));
|
||||
|
||||
// Imported statically (not via `await import` inside each `it`) so the heavy
|
||||
// Bridge dependency-tree load happens once at file collection — not against a
|
||||
// single test's 5s timeout, which tipped over on slower CI runners. vi.mock is
|
||||
// hoisted above these by vitest, so element-builder is still mocked.
|
||||
import { Bridge } from '../src/bridge/bridge';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
|
||||
describe('Bridge private media routing', () => {
|
||||
it('includes resolved uid in the final c2c send request for media messages', async () => {
|
||||
const { Bridge } = await import('../src/bridge/bridge');
|
||||
const { IdentityService } = await import('@snowluma/protocol/identity-service');
|
||||
|
||||
class TestBridge extends Bridge {
|
||||
capturedBody: Uint8Array | null = null;
|
||||
@@ -59,12 +66,26 @@ describe('Bridge private media routing', () => {
|
||||
// BuildPacketBase` + `FileEntity.PackMessageContent`. Previous
|
||||
// implementation wrote c2c routing + richText.notOnlineFile +
|
||||
// c2cCmd=11 — the QQ-NT server rejected every c2c file send.
|
||||
const { Bridge } = await import('../src/bridge/bridge');
|
||||
const { IdentityService } = await import('@snowluma/protocol/identity-service');
|
||||
|
||||
class TestBridge extends Bridge {
|
||||
capturedBody: Uint8Array | null = null;
|
||||
override async sendRawPacket(_cmd: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||
finalizeCmd: string | null = null;
|
||||
|
||||
override async resolveUserUid(uin: number): Promise<string> {
|
||||
return uin === 10000 ? 'u_self' : `u_${uin}`;
|
||||
}
|
||||
|
||||
override async sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||
// The c2c file send first runs the 0xE37_800 finalize, then PbSendMsg.
|
||||
if (cmd.includes('0xe37_800')) {
|
||||
this.finalizeCmd = cmd;
|
||||
return {
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<OidbBase<OidbOfflineFileFinalizeResp>>({
|
||||
body: { body: { metadata: { field3: 11, field100: new Uint8Array([1]), field101: new Uint8Array([2]), field110: 22, timestamp1: 1710000123 } } },
|
||||
})),
|
||||
};
|
||||
}
|
||||
this.capturedBody = body;
|
||||
return {
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
@@ -118,9 +139,66 @@ describe('Bridge private media routing', () => {
|
||||
// expireTime is now+7d; just sanity-check it landed (non-zero, plausible)
|
||||
expect(fileExtra?.file?.expireTime).toBeGreaterThan(Math.floor(Date.now() / 1000));
|
||||
|
||||
// issue #157: when the 0xE37_800 finalize succeeds, its download routing
|
||||
// rides along in field6 (best-effort enrichment on top of the always-
|
||||
// present NotOnlineFile).
|
||||
expect(bridge.finalizeCmd).toBe('OidbSvcTrpcTcp.0xe37_800');
|
||||
expect(fileExtra?.field6?.field2).toMatchObject({
|
||||
fileUuid: 'uuid-abc-123',
|
||||
fileName: 'doc.txt',
|
||||
fileHash: 'hash-xyz',
|
||||
selfUid: 'u_self',
|
||||
destUid: 'u_peer_xyz',
|
||||
field1: 22, // ← finalize metadata.field110
|
||||
field6: 11, // ← finalize metadata.field3
|
||||
timestamp1: 1710000123,
|
||||
});
|
||||
expect(fileExtra?.field6?.field2?.field7).toEqual(new Uint8Array([2])); // ← metadata.field101
|
||||
expect(fileExtra?.field6?.field2?.field8).toEqual(new Uint8Array([1])); // ← metadata.field100
|
||||
|
||||
// c2cCmd is left at 0 / undefined — the old `c2cCmd=11` was a
|
||||
// stale go-cqhttp value the QQ-NT server doesn't recognise on the
|
||||
// c2c-file path.
|
||||
expect(request?.contentHead?.c2cCmd ?? 0).toBe(0);
|
||||
});
|
||||
|
||||
it('c2c file send survives a failing 0xE37_800 finalize — sends without field6 (#157 best-effort)', async () => {
|
||||
|
||||
class TestBridge extends Bridge {
|
||||
capturedBody: Uint8Array | null = null;
|
||||
|
||||
override async resolveUserUid(uin: number): Promise<string> {
|
||||
return uin === 10000 ? 'u_self' : `u_${uin}`;
|
||||
}
|
||||
|
||||
override async sendRawPacket(cmd: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||
// Finalize fails (server error → OidbError). The send must NOT fail
|
||||
// because of it.
|
||||
if (cmd.includes('0xe37_800')) {
|
||||
return { success: false, gotResponse: true, errorCode: 9999, errorMessage: 'finalize boom', responseData: Buffer.alloc(0) };
|
||||
}
|
||||
this.capturedBody = body;
|
||||
return {
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
|
||||
result: 0, errMsg: '', privateSequence: 88, timestamp1: 1710000000,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
const bridge = new TestBridge(IdentityService.memory('10000'));
|
||||
|
||||
// Should resolve (not throw) despite the finalize error.
|
||||
await bridge.apis.message.sendC2cFile(67890, 'u_peer_xyz', {
|
||||
fileId: 'uuid-abc-123', fileName: 'doc.txt', fileSize: 1024,
|
||||
fileMd5: new Uint8Array([1, 2, 3, 4]), fileHash: 'hash-xyz',
|
||||
});
|
||||
|
||||
// PbSendMsg still went out, carrying the file but NO field6.
|
||||
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
|
||||
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody as Uint8Array);
|
||||
const fileExtra = protobuf_decode<FileExtra>(request!.messageBody!.msgContent as Uint8Array);
|
||||
expect(fileExtra?.file?.fileUuid).toBe('uuid-abc-123');
|
||||
expect(fileExtra?.field6 ?? undefined).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// so this exercises the loop/cursor logic, not the wire decode (covered in
|
||||
// packages/protocol/tests/msg-push/fetch-group-history.test.ts).
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/msg-push', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@snowluma/protocol/msg-push')>();
|
||||
@@ -27,7 +27,22 @@ function gm(seq: number): any {
|
||||
const ctx = { identity: {}, sendRawPacket: vi.fn() } as any;
|
||||
|
||||
describe('MessageApi.getGroupHistory walk-back', () => {
|
||||
beforeEach(() => mockFetch.mockReset());
|
||||
// The walk-back loop enforces a real ~300ms gap between each SsoGetGroupMsg
|
||||
// send (a deliberate anti-flood throttle, unchanged in production). Fake the
|
||||
// clock so the test exercises the loop/cursor logic instantly instead of
|
||||
// waiting out 300ms × up-to-12 real sends.
|
||||
beforeEach(() => {
|
||||
mockFetch.mockReset();
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
// Drives a throttled getGroupHistory to completion under fake timers: kick it
|
||||
// off, flush the queued send-gap timers, then await the result.
|
||||
async function runHistory<T>(promise: Promise<T>): Promise<T> {
|
||||
await vi.runAllTimersAsync();
|
||||
return promise;
|
||||
}
|
||||
|
||||
it('walks back across short-capped windows, dedups, returns newest `want` ascending', async () => {
|
||||
// Server caps every window to its newest 10 sequences → forces walk-back.
|
||||
@@ -37,7 +52,7 @@ describe('MessageApi.getGroupHistory walk-back', () => {
|
||||
return out;
|
||||
});
|
||||
|
||||
const res = await new MessageApi(ctx).getGroupHistory(9999, 200, 50);
|
||||
const res = await runHistory(new MessageApi(ctx).getGroupHistory(9999, 200, 50));
|
||||
|
||||
expect(res).toHaveLength(50);
|
||||
expect(res[0].msgSeq).toBe(151); // newest 50 ending at 200 → 151..200
|
||||
@@ -54,7 +69,7 @@ describe('MessageApi.getGroupHistory walk-back', () => {
|
||||
return out;
|
||||
});
|
||||
|
||||
const res = await new MessageApi(ctx).getGroupHistory(9999, 20, 100); // only seq 1..20 exist
|
||||
const res = await runHistory(new MessageApi(ctx).getGroupHistory(9999, 20, 100)); // only seq 1..20 exist
|
||||
expect(res.map((m) => m.msgSeq)).toEqual(Array.from({ length: 20 }, (_, i) => i + 1));
|
||||
});
|
||||
|
||||
@@ -65,7 +80,7 @@ describe('MessageApi.getGroupHistory walk-back', () => {
|
||||
return [gm(end)]; // one message per window → never reaches a large `want`
|
||||
});
|
||||
|
||||
const res = await new MessageApi(ctx).getGroupHistory(9999, 100_000, 9999);
|
||||
const res = await runHistory(new MessageApi(ctx).getGroupHistory(9999, 100_000, 9999));
|
||||
expect(calls).toBeLessThanOrEqual(12); // HISTORY_MAX_REQUESTS
|
||||
expect(res.length).toBeLessThanOrEqual(200); // HISTORY_MAX_COUNT
|
||||
});
|
||||
|
||||
103
packages/core/tests/highway/chunk-source.test.ts
Normal file
103
packages/core/tests/highway/chunk-source.test.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
// ChunkSource is the buffer-or-disk abstraction the highway PUT loop reads
|
||||
// through (#stream-upload). The whole streaming refactor rests on one
|
||||
// invariant: a FileChunkSource must yield BYTE-FOR-BYTE the same chunks as a
|
||||
// BufferChunkSource over the same file, at every (offset, length) the uploader
|
||||
// asks for. These tests are that byte-oracle.
|
||||
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { promises as fsp } from 'fs';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { BufferChunkSource, FileChunkSource } from '@snowluma/protocol/highway';
|
||||
|
||||
// Mirrors highway-client's HIGHWAY_BLOCK_SIZE chunk walk without the network:
|
||||
// step through [0,size) in `block` strides, last chunk short by construction.
|
||||
async function collectChunks(src: { size: number; read(o: number, l: number): Promise<Uint8Array> }, block: number) {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let offset = 0;
|
||||
while (offset < src.size) {
|
||||
const len = Math.min(block, src.size - offset);
|
||||
chunks.push(new Uint8Array(await src.read(offset, len)));
|
||||
offset += len;
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
describe('ChunkSource — FileChunkSource ≡ BufferChunkSource', () => {
|
||||
let dir: string;
|
||||
beforeAll(async () => { dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-chunk-')); });
|
||||
afterAll(async () => { await fsp.rm(dir, { recursive: true, force: true }); });
|
||||
|
||||
// Sizes chosen around block boundaries: exact multiple, +1, -1, tiny, empty.
|
||||
for (const [label, size, block] of [
|
||||
['empty', 0, 7],
|
||||
['tiny (< block)', 5, 7],
|
||||
['exact multiple', 21, 7],
|
||||
['one past a boundary', 22, 7],
|
||||
['one before a boundary', 20, 7],
|
||||
['single full block', 7, 7],
|
||||
] as const) {
|
||||
it(`${label}: chunks + size are byte-identical (size=${size}, block=${block})`, async () => {
|
||||
const data = new Uint8Array(size);
|
||||
for (let i = 0; i < size; i++) data[i] = (i * 31 + 7) & 0xff;
|
||||
const file = path.join(dir, `${randomUUID()}.bin`);
|
||||
fs.writeFileSync(file, data);
|
||||
|
||||
const buf = new BufferChunkSource(data);
|
||||
const fch = await FileChunkSource.open(file, size);
|
||||
try {
|
||||
expect(fch.size).toBe(buf.size);
|
||||
expect(fch.size).toBe(size);
|
||||
const a = await collectChunks(buf, block);
|
||||
const b = await collectChunks(fch, block);
|
||||
expect(b.length).toBe(a.length);
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
expect(Buffer.from(b[i]!).equals(Buffer.from(a[i]!))).toBe(true);
|
||||
}
|
||||
// Reassembled stream equals the original bytes exactly.
|
||||
expect(Buffer.concat(b.map((c) => Buffer.from(c))).equals(Buffer.from(data))).toBe(true);
|
||||
} finally {
|
||||
await fch.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it('FileChunkSource.read returns EXACTLY the requested length (no short read leaks)', async () => {
|
||||
const data = new Uint8Array(1000).map((_, i) => (i * 13) & 0xff);
|
||||
const file = path.join(dir, `${randomUUID()}.bin`);
|
||||
fs.writeFileSync(file, data);
|
||||
const fch = await FileChunkSource.open(file, data.length);
|
||||
try {
|
||||
for (const [off, len] of [[0, 1], [0, 1000], [37, 200], [999, 1], [500, 500]] as const) {
|
||||
const got = await fch.read(off, len);
|
||||
expect(got.length).toBe(len);
|
||||
expect(Buffer.from(got).equals(Buffer.from(data.subarray(off, off + len)))).toBe(true);
|
||||
}
|
||||
} finally {
|
||||
await fch.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('FileChunkSource.read throws on unexpected EOF (request past end)', async () => {
|
||||
const data = new Uint8Array(10);
|
||||
const file = path.join(dir, `${randomUUID()}.bin`);
|
||||
fs.writeFileSync(file, data);
|
||||
const fch = await FileChunkSource.open(file, 10);
|
||||
try {
|
||||
await expect(fch.read(5, 20)).rejects.toThrow(/unexpected EOF/);
|
||||
} finally {
|
||||
await fch.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('BufferChunkSource.close and FileChunkSource.close both resolve (idempotent contract)', async () => {
|
||||
const buf = new BufferChunkSource(new Uint8Array(3));
|
||||
await expect(buf.close()).resolves.toBeUndefined();
|
||||
const file = path.join(dir, `${randomUUID()}.bin`);
|
||||
fs.writeFileSync(file, new Uint8Array(3));
|
||||
const fch = await FileChunkSource.open(file, 3);
|
||||
await expect(fch.close()).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
92
packages/core/tests/highway/hash-file.test.ts
Normal file
92
packages/core/tests/highway/hash-file.test.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
// hashFileStreaming is the streaming replacement for the buffered
|
||||
// `computeHashes` + `computeVideoSha1Blocks` (+ head-md5) used before an
|
||||
// upload. The refactor's whole promise is byte-for-byte identity, so this
|
||||
// test IS the oracle: for a spread of sizes around the 1 MiB block boundary
|
||||
// (and a spread of head limits around chunk boundaries) it asserts the
|
||||
// streaming result equals the buffered functions over the same bytes.
|
||||
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { promises as fsp } from 'fs';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
|
||||
import { computeHashes, computeMd5 } from '@snowluma/protocol/highway/utils';
|
||||
import { computeVideoSha1Blocks } from '@snowluma/protocol/highway/video-upload';
|
||||
|
||||
const MB = 1024 * 1024;
|
||||
|
||||
function synth(size: number): Uint8Array {
|
||||
const b = new Uint8Array(size);
|
||||
for (let i = 0; i < size; i++) b[i] = (i * 131 + 7) & 0xff;
|
||||
return b;
|
||||
}
|
||||
|
||||
function eq(a: Uint8Array, b: Uint8Array): boolean {
|
||||
return Buffer.from(a).equals(Buffer.from(b));
|
||||
}
|
||||
|
||||
describe('hashFileStreaming ≡ buffered computeHashes + computeVideoSha1Blocks + head-md5', () => {
|
||||
let dir: string;
|
||||
beforeAll(async () => { dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-hash-')); });
|
||||
afterAll(async () => { await fsp.rm(dir, { recursive: true, force: true }); });
|
||||
|
||||
// Sizes chosen around the 1 MiB block boundary + sub-block + multi-block.
|
||||
const SIZES = [0, 1, 63, 64, 65, MB - 1, MB, MB + 1, 2 * MB, 2 * MB + 123];
|
||||
|
||||
for (const size of SIZES) {
|
||||
it(`size=${size}: md5 / sha1 / sha1Blocks match the buffered helpers`, async () => {
|
||||
const data = synth(size);
|
||||
const file = path.join(dir, `${randomUUID()}.bin`);
|
||||
fs.writeFileSync(file, data);
|
||||
|
||||
const streamed = await hashFileStreaming(file);
|
||||
const buffered = computeHashes(data);
|
||||
const refBlocks = computeVideoSha1Blocks(data);
|
||||
|
||||
expect(eq(streamed.md5, buffered.md5)).toBe(true);
|
||||
expect(eq(streamed.sha1, buffered.sha1)).toBe(true);
|
||||
expect(streamed.md5Hex).toBe(buffered.md5Hex);
|
||||
expect(streamed.sha1Hex).toBe(buffered.sha1Hex);
|
||||
expect(streamed.headMd5).toBeUndefined();
|
||||
|
||||
// sha1Blocks must match exactly — same count, same bytes, same order.
|
||||
expect(streamed.sha1Blocks.length).toBe(refBlocks.length);
|
||||
for (let i = 0; i < refBlocks.length; i++) {
|
||||
expect(eq(streamed.sha1Blocks[i]!, refBlocks[i]!)).toBe(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it('headMd5 matches computeMd5(first N bytes) across boundaries (±1, block edge, ≥size)', async () => {
|
||||
const size = 2 * MB + 500;
|
||||
const data = synth(size);
|
||||
const file = path.join(dir, `${randomUUID()}.bin`);
|
||||
fs.writeFileSync(file, data);
|
||||
|
||||
// head limits: empty, tiny, mid-first-block, exact block boundary ±1,
|
||||
// and past the end (must clamp to size).
|
||||
const limits = [0, 1, 1000, MB - 1, MB, MB + 1, size - 1, size, size + 1];
|
||||
for (const L of limits) {
|
||||
const streamed = await hashFileStreaming(file, { headLimit: L });
|
||||
const ref = computeMd5(data.subarray(0, Math.min(data.length, L)));
|
||||
expect(streamed.headMd5).toBeDefined();
|
||||
expect(eq(streamed.headMd5!, ref)).toBe(true);
|
||||
// The rest of the digests are unaffected by headLimit.
|
||||
expect(streamed.md5Hex).toBe(computeHashes(data).md5Hex);
|
||||
}
|
||||
});
|
||||
|
||||
it('empty file: md5/sha1 of nothing, single finalized sha1 block, headMd5 of empty', async () => {
|
||||
const file = path.join(dir, `${randomUUID()}.bin`);
|
||||
fs.writeFileSync(file, new Uint8Array(0));
|
||||
const streamed = await hashFileStreaming(file, { headLimit: 10 });
|
||||
const buffered = computeHashes(new Uint8Array(0));
|
||||
expect(streamed.md5Hex).toBe(buffered.md5Hex);
|
||||
expect(streamed.sha1Hex).toBe(buffered.sha1Hex);
|
||||
expect(streamed.sha1Blocks.length).toBe(1); // just the finalized whole-file sha1
|
||||
expect(eq(streamed.sha1Blocks[0]!, buffered.sha1)).toBe(true);
|
||||
expect(eq(streamed.headMd5!, computeMd5(new Uint8Array(0)))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -88,7 +88,7 @@ vi.mock('net', () => ({
|
||||
createConnection: createConnectionMock,
|
||||
}));
|
||||
|
||||
import { uploadHighwayHttp, type HighwaySession } from '@snowluma/protocol/highway';
|
||||
import { uploadHighwayHttp, BufferChunkSource, type HighwaySession } from '@snowluma/protocol/highway';
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
@@ -130,7 +130,7 @@ describe('uploadHighwayHttp connection lifecycle', () => {
|
||||
// 0.5 MiB → 1 chunk。覆盖 PTT / 小图的常见场景。
|
||||
const bytes = new Uint8Array(512 * 1024);
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
makeBridge(), makeSession(), 1003, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(1);
|
||||
expect(createdSockets[0]!.destroyed).toBe(true);
|
||||
@@ -142,7 +142,7 @@ describe('uploadHighwayHttp connection lifecycle', () => {
|
||||
// 关闭,新实现必须为每个 chunk 各开一个 socket。
|
||||
const bytes = new Uint8Array(Math.floor(1.5 * HIGHWAY_BLOCK_SIZE));
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
makeBridge(), makeSession(), 1003, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
expect(createdSockets).toHaveLength(2);
|
||||
@@ -154,8 +154,15 @@ describe('uploadHighwayHttp connection lifecycle', () => {
|
||||
it('opens N connections for N chunks (3 chunks here)', async () => {
|
||||
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE));
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('a zero-length source opens ZERO connections (empty-input invariant)', async () => {
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1003, new BufferChunkSource(new Uint8Array(0)), new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -153,9 +153,12 @@ describe('runNtv2Upload — two images in one message (sequential)', () => {
|
||||
|
||||
// The PUT receives image-2's bytes, image-2's md5, and the
|
||||
// image-2-derived extend (NOT image-1's data).
|
||||
const [, , cmdId, putBytes, putMd5, putExtend] = vi.mocked(highway.uploadHighwayHttp).mock.calls[0]!;
|
||||
const [, , cmdId, putSource, putMd5, putExtend] = vi.mocked(highway.uploadHighwayHttp).mock.calls[0]!;
|
||||
expect(cmdId).toBe(1004);
|
||||
expect(putBytes).toBe(image2Bytes);
|
||||
// The PUT source is a ChunkSource wrapping image-2's bytes — verify it
|
||||
// yields image-2 exactly (not image-1) through its public read().
|
||||
expect(putSource.size).toBe(image2Bytes.length);
|
||||
expect(Buffer.from(await putSource.read(0, putSource.size)).equals(Buffer.from(image2Bytes))).toBe(true);
|
||||
expect(putMd5).toBe(image2Md5);
|
||||
|
||||
// Decode the extend bytes; uKey + fileUuid must come from image-2's
|
||||
|
||||
@@ -12,6 +12,7 @@ vi.mock('@snowluma/protocol/highway', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
|
||||
uploadHighwayHttp: vi.fn(async () => undefined),
|
||||
buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
|
||||
BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} },
|
||||
PRIVATE_IMAGE_CMD_ID: 1003,
|
||||
GROUP_IMAGE_CMD_ID: 1004,
|
||||
}));
|
||||
@@ -283,6 +284,11 @@ describe('pipeline — runNtv2Upload', () => {
|
||||
}))).rejects.toThrow(/image fast-upload not available/);
|
||||
});
|
||||
|
||||
// (Removed the forceFullOnFastPath retry tests with the feature itself — real-
|
||||
// machine testing + kernel RE proved the tryFastUploadCompleted:false retry
|
||||
// never forces a fresh upload; expired-but-indexed video resources are a
|
||||
// platform limitation. See #145.)
|
||||
|
||||
it('silently skips a sub-file with empty bytes when no fastOnlyError is configured', async () => {
|
||||
// This mirrors the video-thumb path where bytes are always synthesised
|
||||
// (FALLBACK_THUMB) so we don't expect the check to fire even if the
|
||||
|
||||
214
packages/core/tests/highway/stage.test.ts
Normal file
214
packages/core/tests/highway/stage.test.ts
Normal file
@@ -0,0 +1,214 @@
|
||||
// stageSourceToDisk unifies every upload source onto a local disk path so the
|
||||
// streaming uploader never buffers a whole file. These tests cover the three
|
||||
// source kinds, the crash-safety contract (hardlink survives caller-side
|
||||
// deletion — the retention race Codex flagged), size caps, symlink resolution,
|
||||
// cleanup, and the orphan reaper's active-set safety.
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { promises as fsp } from 'fs';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { stageSourceToDisk, sweepStagedUploads, STAGE_DIR } from '@snowluma/protocol/highway/stage';
|
||||
import { pathToFileURL } from 'url';
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
let scratch: string;
|
||||
|
||||
async function readStaged(p: string): Promise<Buffer> {
|
||||
return fsp.readFile(p);
|
||||
}
|
||||
|
||||
beforeEach(async () => { scratch = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-stage-src-')); });
|
||||
afterEach(async () => {
|
||||
globalThis.fetch = originalFetch;
|
||||
await fsp.rm(scratch, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('stageSourceToDisk — base64', () => {
|
||||
it('stages base64 bytes to disk', async () => {
|
||||
const data = Buffer.from('hello base64 world');
|
||||
const staged = await stageSourceToDisk(`base64://${data.toString('base64')}`, 1024);
|
||||
try {
|
||||
expect(staged.fileSize).toBe(data.length);
|
||||
expect(staged.fileName).toBe('');
|
||||
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
|
||||
expect(staged.filePath.startsWith(STAGE_DIR)).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
|
||||
it('rejects oversized base64 on decoded length (before allocation) and leaves no temp', async () => {
|
||||
const big = Buffer.alloc(4096).toString('base64');
|
||||
await expect(stageSourceToDisk(`base64://${big}`, 64)).rejects.toThrow(/too large/);
|
||||
const parts = (await fsp.readdir(STAGE_DIR).catch(() => [] as string[])).filter((n) => n.endsWith('.part'));
|
||||
expect(parts).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stageSourceToDisk — http', () => {
|
||||
it('streams an http download to disk with the URL basename', async () => {
|
||||
const body = new Uint8Array([9, 8, 7, 6, 5]);
|
||||
globalThis.fetch = (async () => new Response(body, { status: 200 })) as typeof fetch;
|
||||
const staged = await stageSourceToDisk('https://example.test/clip.mp4', 1024);
|
||||
try {
|
||||
expect(staged.fileName).toBe('clip.mp4');
|
||||
expect(staged.fileSize).toBe(body.length);
|
||||
expect((await readStaged(staged.filePath)).equals(Buffer.from(body))).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
|
||||
it('rejects an oversized http download and cleans up the .part', async () => {
|
||||
globalThis.fetch = (async () => new Response(new Uint8Array(4096), {
|
||||
status: 200, headers: { 'content-length': '4096' },
|
||||
})) as typeof fetch;
|
||||
await expect(stageSourceToDisk('https://example.test/big.bin', 64)).rejects.toThrow(/too large/);
|
||||
const leftover = (await fsp.readdir(STAGE_DIR).catch(() => [] as string[])).filter((n) => n.endsWith('.part'));
|
||||
expect(leftover).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects a STREAMED overflow (no Content-Length) after the sink+.part exist, then cleans up', async () => {
|
||||
// No content-length → the size cap only trips mid-stream, AFTER fileSink has
|
||||
// opened the .part. This exercises fileSink.discard()'s close-before-unlink.
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(c) { for (let i = 0; i < 8; i++) c.enqueue(new Uint8Array(4096)); c.close(); },
|
||||
});
|
||||
globalThis.fetch = (async () => new Response(stream, { status: 200 })) as typeof fetch;
|
||||
await expect(stageSourceToDisk('https://example.test/stream.bin', 4 * 1024)).rejects.toThrow(/too large/);
|
||||
const parts = (await fsp.readdir(STAGE_DIR).catch(() => [] as string[])).filter((n) => n.endsWith('.part'));
|
||||
expect(parts).toEqual([]);
|
||||
});
|
||||
|
||||
it('retries with a Referer after a network failure and stages the retry body cleanly (no attempt-1 leftovers)', async () => {
|
||||
const body = new Uint8Array([1, 2, 3, 4, 5, 6, 7]);
|
||||
let n = 0;
|
||||
globalThis.fetch = (async () => {
|
||||
n += 1;
|
||||
if (n === 1) throw new TypeError('fetch failed'); // anti-bot RST on attempt 1
|
||||
return new Response(body, { status: 200 });
|
||||
}) as typeof fetch;
|
||||
const staged = await stageSourceToDisk('https://example.test/r.mp4', 1024);
|
||||
try {
|
||||
expect(n).toBe(2);
|
||||
expect(staged.fileSize).toBe(body.length);
|
||||
expect((await readStaged(staged.filePath)).equals(Buffer.from(body))).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
});
|
||||
|
||||
describe('stageSourceToDisk — local files', () => {
|
||||
it('hardlinks a local file:// source and survives caller-side deletion (retention race)', async () => {
|
||||
const src = path.join(scratch, 'video.mp4');
|
||||
const data = Buffer.from('the caller-owned temp that retention will delete');
|
||||
fs.writeFileSync(src, data);
|
||||
|
||||
const staged = await stageSourceToDisk(pathToFileURL(src).href, 1 << 20);
|
||||
try {
|
||||
expect(staged.fileName).toBe('video.mp4');
|
||||
expect(staged.fileSize).toBe(data.length);
|
||||
// Simulate upload_file_stream's retention timer unlinking the original
|
||||
// BETWEEN the hash pass and the upload pass.
|
||||
await fsp.unlink(src);
|
||||
// The hardlink kept the inode alive — the staged path is still fully readable.
|
||||
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
|
||||
it('accepts a raw local path and preserves its basename', async () => {
|
||||
const src = path.join(scratch, 'doc.bin');
|
||||
fs.writeFileSync(src, Buffer.from([1, 2, 3, 4]));
|
||||
const staged = await stageSourceToDisk(src, 1 << 20);
|
||||
try {
|
||||
expect(staged.fileName).toBe('doc.bin');
|
||||
expect(staged.fileSize).toBe(4);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
|
||||
it('resolves a symlink to its target but keeps the symlink basename', async () => {
|
||||
const target = path.join(scratch, 'real-xyz.tmp');
|
||||
const linkPath = path.join(scratch, 'friendly.mp4');
|
||||
const data = Buffer.from('symlinked content');
|
||||
fs.writeFileSync(target, data);
|
||||
fs.symlinkSync(target, linkPath);
|
||||
const staged = await stageSourceToDisk(linkPath, 1 << 20);
|
||||
try {
|
||||
expect(staged.fileName).toBe('friendly.mp4'); // original basename, not the target's
|
||||
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
|
||||
it('falls back to a streamed copy when hardlink fails (e.g. cross-filesystem EXDEV)', async () => {
|
||||
const src = path.join(scratch, 'xfs.mp4');
|
||||
const data = Buffer.from('content that must copy when link() is refused');
|
||||
fs.writeFileSync(src, data);
|
||||
const linkSpy = vi.spyOn(fsp, 'link').mockRejectedValueOnce(Object.assign(new Error('EXDEV'), { code: 'EXDEV' }));
|
||||
try {
|
||||
const staged = await stageSourceToDisk(src, 1 << 20);
|
||||
try {
|
||||
expect(linkSpy).toHaveBeenCalledOnce();
|
||||
expect(staged.fileName).toBe('xfs.mp4');
|
||||
expect(staged.fileSize).toBe(data.length);
|
||||
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
|
||||
// The copy is an independent file — deleting the source leaves it intact.
|
||||
await fsp.unlink(src);
|
||||
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
} finally { linkSpy.mockRestore(); }
|
||||
});
|
||||
|
||||
it('rejects a non-regular file (directory)', async () => {
|
||||
await expect(stageSourceToDisk(scratch, 1 << 20)).rejects.toThrow(/not a regular file/);
|
||||
});
|
||||
|
||||
it('rejects an oversized local file before staging', async () => {
|
||||
const src = path.join(scratch, 'huge.bin');
|
||||
fs.writeFileSync(src, Buffer.alloc(200));
|
||||
await expect(stageSourceToDisk(src, 64)).rejects.toThrow(/too large: 200 > 64/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stageSourceToDisk — cleanup + reaper', () => {
|
||||
it('cleanup removes the staged temp and is idempotent', async () => {
|
||||
const src = path.join(scratch, 'c.bin');
|
||||
fs.writeFileSync(src, Buffer.from([1]));
|
||||
const staged = await stageSourceToDisk(src, 1 << 20);
|
||||
expect(fs.existsSync(staged.filePath)).toBe(true);
|
||||
await staged.cleanup();
|
||||
expect(fs.existsSync(staged.filePath)).toBe(false);
|
||||
await expect(staged.cleanup()).resolves.toBeUndefined(); // idempotent, no throw
|
||||
});
|
||||
|
||||
it('reaper removes an old ORPHAN temp but NEVER an in-flight (active) staged file', async () => {
|
||||
await fsp.mkdir(STAGE_DIR, { recursive: true });
|
||||
const old = Date.now() - 60 * 60 * 1000; // 1h ago
|
||||
|
||||
// Orphan: a temp NOT tracked in `active` (as a crash would leave), aged out.
|
||||
const orphan = path.join(STAGE_DIR, `stage-${randomUUID()}.orphan`);
|
||||
fs.writeFileSync(orphan, Buffer.from('crash leftover'));
|
||||
fs.utimesSync(orphan, new Date(old), new Date(old));
|
||||
|
||||
// In-flight: a real staged file (registered in `active`), also aged out —
|
||||
// the active-set must protect it from the age sweep.
|
||||
const src = path.join(scratch, 'inflight.bin');
|
||||
fs.writeFileSync(src, Buffer.from('being uploaded'));
|
||||
const staged = await stageSourceToDisk(src, 1 << 20);
|
||||
fs.utimesSync(staged.filePath, new Date(old), new Date(old)); // read-only upload → stale mtime
|
||||
|
||||
const removed = await sweepStagedUploads(Date.now());
|
||||
expect(fs.existsSync(orphan)).toBe(false); // orphan reaped
|
||||
expect(fs.existsSync(staged.filePath)).toBe(true); // active file preserved
|
||||
expect(removed).toBeGreaterThanOrEqual(1);
|
||||
|
||||
await staged.cleanup();
|
||||
});
|
||||
|
||||
it('reaper leaves a recent orphan alone', async () => {
|
||||
await fsp.mkdir(STAGE_DIR, { recursive: true });
|
||||
const recent = path.join(STAGE_DIR, `stage-${randomUUID()}.recent`);
|
||||
fs.writeFileSync(recent, Buffer.from('fresh'));
|
||||
try {
|
||||
await sweepStagedUploads(Date.now());
|
||||
expect(fs.existsSync(recent)).toBe(true);
|
||||
} finally { await fsp.rm(recent, { force: true }); }
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,12 @@
|
||||
// always provides bytes), and the video-specific OIDB fields.
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { promises as fsp } from 'fs';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { pathToFileURL } from 'url';
|
||||
import { computeHashes } from '@snowluma/protocol/highway/utils';
|
||||
|
||||
vi.mock('@snowluma/protocol/highway/pipeline', () => ({
|
||||
runNtv2Upload: vi.fn(async () => ({ msgInfo: { msgInfoBody: [], extBizInfo: {} } })),
|
||||
@@ -80,6 +86,16 @@ describe('video-upload', () => {
|
||||
expect(uploads[1]!.fastOnlyError).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does NOT set a force-full retry flag on the main file (#145 — proven ineffective)', async () => {
|
||||
// The old forceFullOnFastPath retry was removed: real-machine + kernel RE
|
||||
// showed it never forces a fresh upload (the server fast-paths by md5
|
||||
// metadata regardless of tryFastUploadCompleted). An expired-but-indexed
|
||||
// video resource is a platform limitation, not an upload-flow fix.
|
||||
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
|
||||
const uploads = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploads;
|
||||
expect((uploads[0] as unknown as Record<string, unknown>).forceFullOnFastPath).toBeUndefined();
|
||||
});
|
||||
|
||||
it('uploadInfo carries TWO entries (main mp4 + thumb jpg) with subFileType 0 and 100', async () => {
|
||||
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
|
||||
const uploadInfo = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo;
|
||||
@@ -90,6 +106,23 @@ describe('video-upload', () => {
|
||||
expect((uploadInfo[1] as any).fileInfo.type.type).toBe(1); // pic (thumb)
|
||||
});
|
||||
|
||||
it('[#145] group video carries real width/height; c2c stays 0/0', async () => {
|
||||
// A real QQ group video's MsgInfo has real dimensions (e.g. 296x640);
|
||||
// sending 0x0 makes QQ-NT receivers render 文件已过期 even though the
|
||||
// resource is fresh (verified on tempserver: 0x0 → expired, real dims →
|
||||
// renders). c2c is left at 0 — the server rejects non-zero dims there.
|
||||
await uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
|
||||
const groupInfo = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo;
|
||||
expect((groupInfo[0] as any).fileInfo.width).toBe(320); // FINGERPRINT.width
|
||||
expect((groupInfo[0] as any).fileInfo.height).toBe(240); // FINGERPRINT.height
|
||||
|
||||
vi.mocked(pipeline.runNtv2Upload).mockClear();
|
||||
await uploadVideoMsgInfo({} as any, false, 'recipient-uid', FINGERPRINT);
|
||||
const c2cInfo = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo;
|
||||
expect((c2cInfo[0] as any).fileInfo.width).toBe(0);
|
||||
expect((c2cInfo[0] as any).fileInfo.height).toBe(0);
|
||||
});
|
||||
|
||||
it('main video carries the real `time` (duration in seconds) — regression: was 0', async () => {
|
||||
// NTV2 server bakes the `time` field into the resulting MsgInfo
|
||||
// bytes that ride along as `commonElem.pbElem`; the receiver
|
||||
@@ -131,3 +164,69 @@ describe('video-upload', () => {
|
||||
expect(args[1]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('video-upload — streaming path (real on-disk source)', () => {
|
||||
beforeEach(() => { vi.mocked(pipeline.runNtv2Upload).mockClear(); });
|
||||
|
||||
it('stages + stream-hashes the source and PUTs via fileSource, never buffering bytes', async () => {
|
||||
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-vidstream-'));
|
||||
const file = path.join(dir, 'clip.mp4');
|
||||
const data = Buffer.alloc(3 * 1024 * 1024 + 77); // multi-1MiB-block + tail
|
||||
for (let i = 0; i < data.length; i++) data[i] = (i * 37 + 5) & 0xff;
|
||||
fs.writeFileSync(file, data);
|
||||
try {
|
||||
const bridge = { identity: { uin: '10001' } } as any;
|
||||
await uploadVideoMsgInfo(bridge, true, 12345, { type: 'video', url: pathToFileURL(file).href } as any);
|
||||
|
||||
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls.at(-1)![0];
|
||||
const main = args.uploads[0]!;
|
||||
// Main file streams from disk — fileSource set, no in-memory bytes.
|
||||
expect(main.fileSource).toBeDefined();
|
||||
expect(main.fileSource!.fileSize).toBe(data.length);
|
||||
expect(main.bytes.length).toBe(0);
|
||||
// The OIDB fileInfo carries the STREAMED hashes/size — must equal the
|
||||
// buffered hash of the same bytes (byte-identical guarantee end-to-end).
|
||||
const fi = (args.uploadInfo[0] as any).fileInfo;
|
||||
expect(fi.fileSize).toBe(data.length);
|
||||
expect(fi.fileHash).toBe(computeHashes(data).md5Hex);
|
||||
expect(fi.fileSha1).toBe(computeHashes(data).sha1Hex);
|
||||
// The staged temp is a copy/hardlink under the stage dir (NOT the source)
|
||||
// and is cleaned up after the send.
|
||||
expect(main.fileSource!.filePath).not.toBe(file);
|
||||
expect(fs.existsSync(main.fileSource!.filePath)).toBe(false);
|
||||
} finally {
|
||||
await fsp.rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('cleans up the staged temp even when the upload throws', async () => {
|
||||
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-vidfail-'));
|
||||
const file = path.join(dir, 'clip.mp4');
|
||||
fs.writeFileSync(file, Buffer.alloc(2048, 7));
|
||||
try {
|
||||
vi.mocked(pipeline.runNtv2Upload).mockRejectedValueOnce(new Error('upload boom'));
|
||||
await expect(
|
||||
uploadVideoMsgInfo({ identity: { uin: '1' } } as any, true, 12345, { type: 'video', url: pathToFileURL(file).href } as any),
|
||||
).rejects.toThrow(/upload boom/);
|
||||
// The staged temp created in loadVideo must be removed by the finally.
|
||||
const args = vi.mocked(pipeline.runNtv2Upload).mock.calls.at(-1)![0];
|
||||
const stagedPath = args.uploads[0]!.fileSource!.filePath;
|
||||
expect(fs.existsSync(stagedPath)).toBe(false);
|
||||
} finally {
|
||||
await fsp.rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects an empty video source (0 bytes)', async () => {
|
||||
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-vidempty-'));
|
||||
const file = path.join(dir, 'empty.mp4');
|
||||
fs.writeFileSync(file, new Uint8Array(0));
|
||||
try {
|
||||
await expect(
|
||||
uploadVideoMsgInfo({ identity: { uin: '1' } } as any, true, 12345, { type: 'video', url: pathToFileURL(file).href } as any),
|
||||
).rejects.toThrow(/empty/);
|
||||
} finally {
|
||||
await fsp.rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,6 +17,7 @@ vi.mock('@snowluma/protocol/highway', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
|
||||
uploadHighwayHttp: vi.fn(async () => undefined),
|
||||
buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
|
||||
BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} },
|
||||
PRIVATE_IMAGE_CMD_ID: 1003,
|
||||
GROUP_IMAGE_CMD_ID: 1004,
|
||||
}));
|
||||
|
||||
62
packages/core/tests/sse-response.test.ts
Normal file
62
packages/core/tests/sse-response.test.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { sseResponse } from '../src/webui/sse-response';
|
||||
|
||||
// A minimal hono-Context stand-in: sseResponse only reads c.req.raw.signal.
|
||||
function fakeCtx(signal: AbortSignal): Parameters<typeof sseResponse>[0] {
|
||||
return { req: { raw: { signal } } } as unknown as Parameters<typeof sseResponse>[0];
|
||||
}
|
||||
|
||||
describe('sseResponse', () => {
|
||||
it('returns an event-stream Response with the SSE headers', () => {
|
||||
const ac = new AbortController();
|
||||
const res = sseResponse(fakeCtx(ac.signal), () => { /* no-op */ });
|
||||
expect(res.headers.get('Content-Type')).toBe('text/event-stream');
|
||||
expect(res.headers.get('Cache-Control')).toBe('no-cache');
|
||||
expect(res.headers.get('Connection')).toBe('keep-alive');
|
||||
ac.abort(); // clear the heartbeat timer
|
||||
});
|
||||
|
||||
it('ch.send frames JSON as `data: …` and ch.raw enqueues verbatim', async () => {
|
||||
const ac = new AbortController();
|
||||
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
|
||||
ch.send({ type: 'ready' });
|
||||
ch.raw(ch.encode(': heartbeat\n\n'));
|
||||
});
|
||||
const reader = res.body!.getReader();
|
||||
const dec = new TextDecoder();
|
||||
expect(dec.decode((await reader.read()).value)).toBe('data: {"type":"ready"}\n\n');
|
||||
expect(dec.decode((await reader.read()).value)).toBe(': heartbeat\n\n');
|
||||
ac.abort();
|
||||
await reader.cancel();
|
||||
});
|
||||
|
||||
it('abort runs registered cleanups exactly once, flips isClosed, and closes the stream', async () => {
|
||||
const ac = new AbortController();
|
||||
const cleanupA = vi.fn();
|
||||
const cleanupB = vi.fn();
|
||||
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
|
||||
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
|
||||
channel = ch;
|
||||
ch.onClose(cleanupA);
|
||||
ch.onClose(cleanupB);
|
||||
});
|
||||
expect(channel.isClosed()).toBe(false);
|
||||
|
||||
ac.abort();
|
||||
expect(cleanupA).toHaveBeenCalledTimes(1);
|
||||
expect(cleanupB).toHaveBeenCalledTimes(1);
|
||||
expect(channel.isClosed()).toBe(true);
|
||||
|
||||
const r = await res.body!.getReader().read();
|
||||
expect(r.done).toBe(true);
|
||||
});
|
||||
|
||||
it('send after teardown is a silent no-op', () => {
|
||||
const ac = new AbortController();
|
||||
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
|
||||
sseResponse(fakeCtx(ac.signal), (ch) => { channel = ch; });
|
||||
ac.abort();
|
||||
expect(() => channel.send({ x: 1 })).not.toThrow();
|
||||
expect(channel.isClosed()).toBe(true);
|
||||
});
|
||||
});
|
||||
168
packages/core/tests/webui-connection-diff-loop.test.ts
Normal file
168
packages/core/tests/webui-connection-diff-loop.test.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { StateBus } from '../src/webui/state-bus';
|
||||
import { startConnectionDiffLoop } from '../src/webui/connection-diff-loop';
|
||||
|
||||
describe('startConnectionDiffLoop', () => {
|
||||
beforeEach(() => { vi.useFakeTimers(); });
|
||||
afterEach(() => { vi.useRealTimers(); });
|
||||
|
||||
it('does NOT publish when the snapshot is stable tick after tick', () => {
|
||||
const bus = new StateBus();
|
||||
const seen: string[] = [];
|
||||
bus.subscribe((r) => seen.push(r));
|
||||
const handle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => [{ uin: '12345', nickname: 'me', adapters: [] }],
|
||||
intervalMs: 500,
|
||||
});
|
||||
|
||||
vi.advanceTimersByTime(2_000); // 4 ticks
|
||||
expect(seen).toEqual([]);
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('first tick baselines the snapshot (no publish); only the second tick with a different value publishes', () => {
|
||||
const bus = new StateBus();
|
||||
const seen: string[] = [];
|
||||
bus.subscribe((r) => seen.push(r));
|
||||
let snap = [{ uin: '12345', nickname: 'me', adapters: [{ kind: 'http', status: 'listening' }] }];
|
||||
const handle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => snap,
|
||||
intervalMs: 500,
|
||||
});
|
||||
vi.advanceTimersByTime(500); // first observation — baseline, no publish
|
||||
expect(seen).toEqual([]);
|
||||
snap = [{ uin: '12345', nickname: 'me', adapters: [{ kind: 'http', status: 'connected' }] }];
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(seen).toEqual(['connections']);
|
||||
// Next tick: stable again → no extra publish.
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(seen).toEqual(['connections']);
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('publishes once per CHANGE, not once per tick the snapshot differs from initial', () => {
|
||||
const bus = new StateBus();
|
||||
const seen: string[] = [];
|
||||
bus.subscribe((r) => seen.push(r));
|
||||
const versions = [
|
||||
[{ uin: '1', nickname: 'a', adapters: [] }], // baseline (no publish on first observation)
|
||||
[{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'listening' }] }],
|
||||
[{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'listening' }] }],
|
||||
[{ uin: '1', nickname: 'a', adapters: [{ kind: 'http', status: 'connected' }] }],
|
||||
];
|
||||
let i = 0;
|
||||
const handle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => versions[Math.min(i, versions.length - 1)] ?? [],
|
||||
intervalMs: 500,
|
||||
});
|
||||
|
||||
vi.advanceTimersByTime(500); // i=0 baseline
|
||||
i = 1; vi.advanceTimersByTime(500); // change #1
|
||||
i = 2; vi.advanceTimersByTime(500); // stable vs i=1
|
||||
i = 3; vi.advanceTimersByTime(500); // change #2
|
||||
|
||||
expect(seen).toEqual(['connections', 'connections']);
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('dispose() stops further ticks, no publish even after a change', () => {
|
||||
const bus = new StateBus();
|
||||
const seen: string[] = [];
|
||||
bus.subscribe((r) => seen.push(r));
|
||||
let snap: object[] = [];
|
||||
const handle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => snap,
|
||||
intervalMs: 500,
|
||||
});
|
||||
handle.dispose();
|
||||
snap = [{ uin: '1', nickname: 'a', adapters: [] }];
|
||||
vi.advanceTimersByTime(5_000);
|
||||
expect(seen).toEqual([]);
|
||||
});
|
||||
|
||||
it('pickComparable() strips volatile fields so detail-only changes do NOT publish', () => {
|
||||
const bus = new StateBus();
|
||||
const seen: string[] = [];
|
||||
bus.subscribe((r) => seen.push(r));
|
||||
// Reproduces the real-world bug: HttpPostAdapter.describeStatus()
|
||||
// embeds HH:MM:SS in `detail`; every webhook delivery rotates that
|
||||
// string every second. WITHOUT pickComparable, the loop would publish
|
||||
// every tick under any active webhook. WITH it (stripping `detail`),
|
||||
// only level changes publish.
|
||||
let snap = [{ uin: '1', adapters: [{ kind: 'httpClient', status: 'ok', detail: '上次推送 14:00:00' }] }];
|
||||
const handle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => snap,
|
||||
pickComparable: (s) => {
|
||||
if (!Array.isArray(s)) return s;
|
||||
return (s as Array<{ uin: string; adapters?: unknown[] }>).map((acc) => ({
|
||||
uin: acc.uin,
|
||||
adapters: Array.isArray(acc.adapters)
|
||||
? acc.adapters.map((a: unknown) => {
|
||||
const o = a as { name?: string; kind?: string; status?: string };
|
||||
return { name: o.name, kind: o.kind, status: o.status };
|
||||
})
|
||||
: acc.adapters,
|
||||
}));
|
||||
},
|
||||
intervalMs: 500,
|
||||
});
|
||||
vi.advanceTimersByTime(500); // baseline
|
||||
expect(seen).toEqual([]);
|
||||
// detail changes every second; raw JSON differs each tick.
|
||||
for (let t = 1; t <= 10; t++) {
|
||||
snap = [{ uin: '1', adapters: [{ kind: 'httpClient', status: 'ok', detail: `上次推送 14:00:${String(t).padStart(2, '0')}` }] }];
|
||||
vi.advanceTimersByTime(500);
|
||||
}
|
||||
expect(seen).toEqual([]); // ZERO publishes — detail is not comparable
|
||||
// Now a REAL state change (status level) → publish exactly once.
|
||||
snap = [{ uin: '1', adapters: [{ kind: 'httpClient', status: 'down', detail: '连接失败' }] }];
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(seen).toEqual(['connections']);
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('a throwing pickComparable() is isolated — loop keeps ticking, no publish', () => {
|
||||
const bus = new StateBus();
|
||||
const seen: string[] = [];
|
||||
bus.subscribe((r) => seen.push(r));
|
||||
const handle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => [{ uin: '1' }],
|
||||
pickComparable: () => { throw new Error('projector boom'); },
|
||||
intervalMs: 500,
|
||||
});
|
||||
vi.advanceTimersByTime(2_000);
|
||||
expect(seen).toEqual([]);
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('survives a throwing snapshot() — keeps trying on the next tick', () => {
|
||||
const bus = new StateBus();
|
||||
const seen: string[] = [];
|
||||
bus.subscribe((r) => seen.push(r));
|
||||
let mode: 'throw' | 'stable' | 'changed' = 'throw';
|
||||
const handle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => {
|
||||
if (mode === 'throw') throw new Error('getConnectionStatuses failed');
|
||||
if (mode === 'stable') return [{ uin: '1', adapters: [] }];
|
||||
return [{ uin: '1', adapters: [{ kind: 'ws', status: 'connected' }] }];
|
||||
},
|
||||
intervalMs: 500,
|
||||
});
|
||||
vi.advanceTimersByTime(500); // throws — skipped, no publish
|
||||
expect(seen).toEqual([]);
|
||||
mode = 'stable';
|
||||
vi.advanceTimersByTime(500); // first SUCCESSFUL read — baseline, no publish
|
||||
expect(seen).toEqual([]);
|
||||
mode = 'changed';
|
||||
vi.advanceTimersByTime(500); // real change → publish
|
||||
expect(seen).toEqual(['connections']);
|
||||
handle.dispose();
|
||||
});
|
||||
});
|
||||
151
packages/core/tests/webui-debug-tools.test.ts
Normal file
151
packages/core/tests/webui-debug-tools.test.ts
Normal file
@@ -0,0 +1,151 @@
|
||||
import { afterAll, describe, expect, it } from 'vitest';
|
||||
import { readdir, readFile, rm } from 'fs/promises';
|
||||
import path from 'path';
|
||||
import {
|
||||
buildStreamInvokeResponse,
|
||||
DEBUG_UPLOAD_DIR,
|
||||
safeUploadName,
|
||||
streamUploadToDisk,
|
||||
uploadDestPath,
|
||||
} from '../src/webui/debug-tools';
|
||||
|
||||
const written: string[] = [];
|
||||
afterAll(async () => {
|
||||
await Promise.all(written.map((p) => rm(p, { force: true }).catch(() => {})));
|
||||
});
|
||||
|
||||
function streamOf(...chunks: Uint8Array[]): ReadableStream<Uint8Array> {
|
||||
let i = 0;
|
||||
return new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
if (i < chunks.length) controller.enqueue(chunks[i++]);
|
||||
else controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function readSse(res: Response): Promise<string[]> {
|
||||
const text = await res.text();
|
||||
return text.split('\n\n').filter((s) => s.startsWith('data: ')).map((s) => s.slice('data: '.length));
|
||||
}
|
||||
|
||||
describe('safeUploadName', () => {
|
||||
it('strips path traversal and separators to a bare basename', () => {
|
||||
expect(safeUploadName('../../etc/passwd')).toBe('passwd');
|
||||
expect(safeUploadName('/abs/secret.key')).toBe('secret.key');
|
||||
expect(safeUploadName('a\\b\\c.png')).toBe('c.png');
|
||||
expect(safeUploadName('..')).toBe('file'); // leading dots stripped → empty → fallback
|
||||
expect(safeUploadName('...hidden')).toBe('hidden');
|
||||
});
|
||||
it('collapses exotic chars and falls back for empties', () => {
|
||||
expect(safeUploadName('my pic!@#.jpg')).toBe('my_pic_.jpg');
|
||||
expect(safeUploadName('')).toBe('file');
|
||||
expect(safeUploadName(undefined)).toBe('file');
|
||||
});
|
||||
it('keeps the extension and caps length', () => {
|
||||
const long = 'x'.repeat(500) + '.mp4';
|
||||
const out = safeUploadName(long);
|
||||
expect(out.length).toBeLessThanOrEqual(120);
|
||||
expect(out.startsWith('x')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadDestPath', () => {
|
||||
it('produces a unique path inside the upload dir', () => {
|
||||
const a = uploadDestPath('pic.png');
|
||||
const b = uploadDestPath('pic.png');
|
||||
expect(a).not.toBe(b); // random id prefix
|
||||
expect(path.dirname(a)).toBe(DEBUG_UPLOAD_DIR);
|
||||
expect(a.endsWith('__pic.png')).toBe(true);
|
||||
const rel = path.relative(DEBUG_UPLOAD_DIR, a);
|
||||
expect(rel.startsWith('..')).toBe(false);
|
||||
expect(path.isAbsolute(rel)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('streamUploadToDisk', () => {
|
||||
it('streams bytes to disk and reports the size', async () => {
|
||||
const data = new TextEncoder().encode('hello debug upload');
|
||||
const res = await streamUploadToDisk(streamOf(data.slice(0, 5), data.slice(5)), 'note.txt');
|
||||
written.push(res.path);
|
||||
expect(res.size).toBe(data.byteLength);
|
||||
expect(path.dirname(res.path)).toBe(DEBUG_UPLOAD_DIR);
|
||||
expect(await readFile(res.path, 'utf8')).toBe('hello debug upload');
|
||||
});
|
||||
|
||||
it('rejects and removes the partial file when the cap is exceeded', async () => {
|
||||
const big = new Uint8Array(64);
|
||||
await expect(
|
||||
streamUploadToDisk(streamOf(big, big), 'big.bin', { maxBytes: 100 }),
|
||||
).rejects.toThrow(/大小上限/);
|
||||
// the partial must not survive — no leftover `__big.bin` in the dir
|
||||
const names = await readdir(DEBUG_UPLOAD_DIR).catch(() => [] as string[]);
|
||||
expect(names.filter((n) => n.endsWith('__big.bin'))).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects an empty body', async () => {
|
||||
await expect(streamUploadToDisk(null, 'x')).rejects.toThrow(/empty/);
|
||||
await expect(streamUploadToDisk(streamOf(), 'x')).rejects.toThrow(/empty/);
|
||||
});
|
||||
|
||||
it('propagates a mid-transfer source error and removes the partial', async () => {
|
||||
const failing = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode('partial-bytes'));
|
||||
controller.error(new Error('source aborted'));
|
||||
},
|
||||
});
|
||||
await expect(streamUploadToDisk(failing, 'oops.bin')).rejects.toThrow(/source aborted/);
|
||||
const names = await readdir(DEBUG_UPLOAD_DIR).catch(() => [] as string[]);
|
||||
expect(names.filter((n) => n.endsWith('__oops.bin'))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildStreamInvokeResponse', () => {
|
||||
const noDelay = async () => {};
|
||||
|
||||
it('relays each emitted frame as one SSE event, in order', async () => {
|
||||
const ac = new AbortController();
|
||||
const driver = async (_rq: string, emit: (j: string) => Promise<void>) => {
|
||||
await emit(JSON.stringify({ data: { type: 'stream', i: 1 } }));
|
||||
await emit(JSON.stringify({ data: { type: 'stream', i: 2 } }));
|
||||
await emit(JSON.stringify({ status: 'ok', data: { type: 'response' } }));
|
||||
};
|
||||
const res = buildStreamInvokeResponse(driver, '{"action":"x"}', ac.signal, noDelay);
|
||||
const frames = (await readSse(res)).map((s) => JSON.parse(s));
|
||||
expect(frames).toHaveLength(3);
|
||||
expect(frames[0].data.i).toBe(1);
|
||||
expect(frames[2].data.type).toBe('response');
|
||||
});
|
||||
|
||||
it('turns a driver error into a terminal failed frame', async () => {
|
||||
const ac = new AbortController();
|
||||
const driver = async (_rq: string, emit: (j: string) => Promise<void>) => {
|
||||
await emit(JSON.stringify({ data: { type: 'stream' } }));
|
||||
throw new Error('disk exploded');
|
||||
};
|
||||
const res = buildStreamInvokeResponse(driver, '{}', ac.signal, noDelay);
|
||||
const frames = (await readSse(res)).map((s) => JSON.parse(s));
|
||||
expect(frames).toHaveLength(2);
|
||||
expect(frames[1].status).toBe('failed');
|
||||
expect(frames[1].message).toMatch(/disk exploded/);
|
||||
});
|
||||
|
||||
it('passes the raw request through to the driver', async () => {
|
||||
const ac = new AbortController();
|
||||
let seen = '';
|
||||
const driver = async (rq: string, emit: (j: string) => Promise<void>) => {
|
||||
seen = rq;
|
||||
await emit('{"data":{"type":"response"}}');
|
||||
};
|
||||
const res = buildStreamInvokeResponse(driver, '{"action":"test_download_stream"}', ac.signal, noDelay);
|
||||
await readSse(res);
|
||||
expect(seen).toBe('{"action":"test_download_stream"}');
|
||||
});
|
||||
|
||||
it('exposes an SSE content-type', () => {
|
||||
const ac = new AbortController();
|
||||
const res = buildStreamInvokeResponse(async () => {}, '{}', ac.signal, noDelay);
|
||||
expect(res.headers.get('Content-Type')).toBe('text/event-stream');
|
||||
});
|
||||
});
|
||||
24
packages/core/tests/webui-sse-auth-allowlist.test.ts
Normal file
24
packages/core/tests/webui-sse-auth-allowlist.test.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { SSE_TOKEN_QUERY_PATHS } from '../src/webui/server';
|
||||
|
||||
// Regression lock for a class of bug that has bricked an SSE endpoint
|
||||
// before: EventSource cannot set Authorization headers, so every SSE
|
||||
// path MUST appear in this allowlist or the auth middleware computes
|
||||
// `queryToken = ''` and 401s every connect. A missing entry is silent —
|
||||
// the only symptom is "live updates don't work, refresh fixes it" — so
|
||||
// keep this list short and verified.
|
||||
describe('SSE_TOKEN_QUERY_PATHS', () => {
|
||||
it('contains every SSE stream the WebUI subscribes to', () => {
|
||||
expect(SSE_TOKEN_QUERY_PATHS.has('/api/logs/stream')).toBe(true);
|
||||
expect(SSE_TOKEN_QUERY_PATHS.has('/api/debug/stream')).toBe(true);
|
||||
expect(SSE_TOKEN_QUERY_PATHS.has('/api/state/stream')).toBe(true);
|
||||
});
|
||||
|
||||
it('does NOT carry any non-stream endpoint — token-via-query is reserved for SSE', () => {
|
||||
// The auth middleware accepts `?token=...` for these paths only; any
|
||||
// bearer-only endpoint listed here would leak tokens via access logs.
|
||||
for (const path of SSE_TOKEN_QUERY_PATHS) {
|
||||
expect(path.endsWith('/stream')).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
119
packages/core/tests/webui-state-bus.test.ts
Normal file
119
packages/core/tests/webui-state-bus.test.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { StateBus, type StateResource } from '../src/webui/state-bus';
|
||||
|
||||
describe('StateBus', () => {
|
||||
it('delivers a publish to a single subscriber with the resource kind', () => {
|
||||
const bus = new StateBus();
|
||||
const seen: StateResource[] = [];
|
||||
bus.subscribe((r) => seen.push(r));
|
||||
|
||||
bus.publish('processes');
|
||||
bus.publish('qq-list');
|
||||
bus.publish('connections');
|
||||
|
||||
expect(seen).toEqual(['processes', 'qq-list', 'connections']);
|
||||
});
|
||||
|
||||
it('fans out one publish to every subscriber', () => {
|
||||
const bus = new StateBus();
|
||||
const a = vi.fn();
|
||||
const b = vi.fn();
|
||||
const c = vi.fn();
|
||||
bus.subscribe(a);
|
||||
bus.subscribe(b);
|
||||
bus.subscribe(c);
|
||||
|
||||
bus.publish('processes');
|
||||
|
||||
expect(a).toHaveBeenCalledExactlyOnceWith('processes');
|
||||
expect(b).toHaveBeenCalledExactlyOnceWith('processes');
|
||||
expect(c).toHaveBeenCalledExactlyOnceWith('processes');
|
||||
});
|
||||
|
||||
it('returns an unsubscribe handle that stops future emits without touching the others', () => {
|
||||
const bus = new StateBus();
|
||||
const a = vi.fn();
|
||||
const b = vi.fn();
|
||||
const unsubA = bus.subscribe(a);
|
||||
bus.subscribe(b);
|
||||
|
||||
bus.publish('processes');
|
||||
unsubA();
|
||||
bus.publish('qq-list');
|
||||
|
||||
expect(a).toHaveBeenCalledExactlyOnceWith('processes');
|
||||
expect(b).toHaveBeenCalledTimes(2);
|
||||
expect(b.mock.calls).toEqual([['processes'], ['qq-list']]);
|
||||
});
|
||||
|
||||
it('is idempotent on double-unsubscribe', () => {
|
||||
const bus = new StateBus();
|
||||
const a = vi.fn();
|
||||
const unsubA = bus.subscribe(a);
|
||||
unsubA();
|
||||
unsubA();
|
||||
bus.publish('processes');
|
||||
expect(a).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('isolates subscriber exceptions — one throwing listener does not block the others or future publishes', () => {
|
||||
const bus = new StateBus();
|
||||
const before = vi.fn();
|
||||
const thrower = vi.fn(() => { throw new Error('boom'); });
|
||||
const after = vi.fn();
|
||||
bus.subscribe(before);
|
||||
bus.subscribe(thrower);
|
||||
bus.subscribe(after);
|
||||
|
||||
expect(() => bus.publish('processes')).not.toThrow();
|
||||
expect(before).toHaveBeenCalledExactlyOnceWith('processes');
|
||||
expect(after).toHaveBeenCalledExactlyOnceWith('processes');
|
||||
|
||||
bus.publish('qq-list');
|
||||
expect(before).toHaveBeenCalledTimes(2);
|
||||
expect(after).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('dispose() drops every subscriber and silently swallows further publishes', () => {
|
||||
const bus = new StateBus();
|
||||
const a = vi.fn();
|
||||
bus.subscribe(a);
|
||||
bus.dispose();
|
||||
bus.publish('processes');
|
||||
expect(a).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('a subscriber that subscribes a second time inside its own callback observes the FOLLOWING publish, not this one', () => {
|
||||
const bus = new StateBus();
|
||||
const second = vi.fn();
|
||||
const first = vi.fn(() => { bus.subscribe(second); });
|
||||
bus.subscribe(first);
|
||||
|
||||
bus.publish('processes');
|
||||
expect(first).toHaveBeenCalledExactlyOnceWith('processes');
|
||||
// The just-added subscriber must not receive the in-flight publish — that
|
||||
// would surprise SSE handlers that subscribe lazily during an emit fan-out.
|
||||
expect(second).not.toHaveBeenCalled();
|
||||
|
||||
bus.publish('qq-list');
|
||||
expect(second).toHaveBeenCalledExactlyOnceWith('qq-list');
|
||||
});
|
||||
|
||||
it('a subscriber that unsubscribes a peer mid-emit lets the survivor still receive THIS publish', () => {
|
||||
const bus = new StateBus();
|
||||
const order: string[] = [];
|
||||
let unsubB!: () => void;
|
||||
bus.subscribe(() => { order.push('a'); unsubB(); });
|
||||
unsubB = bus.subscribe(() => { order.push('b'); });
|
||||
bus.subscribe(() => { order.push('c'); });
|
||||
|
||||
bus.publish('processes');
|
||||
// Snapshot semantics: the fan-out iterates a copy, so peer-unsubscribe
|
||||
// does not skip any other listener that was attached when publish started.
|
||||
expect(order).toEqual(['a', 'b', 'c']);
|
||||
|
||||
order.length = 0;
|
||||
bus.publish('qq-list');
|
||||
expect(order).toEqual(['a', 'c']);
|
||||
});
|
||||
});
|
||||
249
packages/core/tests/webui-state-stream.test.ts
Normal file
249
packages/core/tests/webui-state-stream.test.ts
Normal file
@@ -0,0 +1,249 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { StateBus, type StateResource } from '../src/webui/state-bus';
|
||||
import { bindStateStream } from '../src/webui/state-stream';
|
||||
|
||||
interface CapturedFrame {
|
||||
resource: StateResource;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
function makeSnapshotFn(table: Partial<Record<StateResource, unknown>>) {
|
||||
return vi.fn(async (resource: StateResource): Promise<unknown> => table[resource]);
|
||||
}
|
||||
|
||||
describe('bindStateStream', () => {
|
||||
beforeEach(() => { vi.useFakeTimers(); });
|
||||
afterEach(() => { vi.useRealTimers(); });
|
||||
|
||||
it('sendAllInitial emits one frame per resource with the snapshot data', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
const snapshot = makeSnapshotFn({
|
||||
'processes': [{ pid: 4242, name: 'qq', status: 'available' }],
|
||||
'qq-list': [{ uin: '12345', nickname: 'me' }],
|
||||
'connections': [{ uin: '12345', nickname: 'me', adapters: [] }],
|
||||
});
|
||||
const handle = bindStateStream({
|
||||
bus,
|
||||
snapshot,
|
||||
send: (f) => sent.push(f),
|
||||
debounceMs: 50,
|
||||
});
|
||||
await handle.sendAllInitial();
|
||||
|
||||
expect(snapshot).toHaveBeenCalledTimes(3);
|
||||
expect(new Set(sent.map((f) => f.resource))).toEqual(new Set(['processes', 'qq-list', 'connections']));
|
||||
const procFrame = sent.find((f) => f.resource === 'processes');
|
||||
expect(procFrame?.data).toEqual([{ pid: 4242, name: 'qq', status: 'available' }]);
|
||||
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('a single bus publish reaches send() exactly once after debounceMs', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
const snapshot = makeSnapshotFn({ 'processes': [{ pid: 9999 }] });
|
||||
const handle = bindStateStream({
|
||||
bus,
|
||||
snapshot,
|
||||
send: (f) => sent.push(f),
|
||||
debounceMs: 50,
|
||||
});
|
||||
|
||||
bus.publish('processes');
|
||||
expect(sent).toHaveLength(0); // still debounced
|
||||
await vi.advanceTimersByTimeAsync(49);
|
||||
expect(sent).toHaveLength(0);
|
||||
await vi.advanceTimersByTimeAsync(2);
|
||||
expect(sent).toEqual([{ resource: 'processes', data: [{ pid: 9999 }] }]);
|
||||
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('coalesces a burst of publishes for the SAME resource into one send', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
const snapshot = makeSnapshotFn({ 'processes': 'fresh' });
|
||||
const handle = bindStateStream({
|
||||
bus, snapshot,
|
||||
send: (f) => sent.push(f),
|
||||
debounceMs: 50,
|
||||
});
|
||||
|
||||
for (let i = 0; i < 20; i++) bus.publish('processes');
|
||||
await vi.advanceTimersByTimeAsync(51);
|
||||
expect(sent).toEqual([{ resource: 'processes', data: 'fresh' }]);
|
||||
// Snapshot was only invoked once for the whole burst.
|
||||
expect(snapshot).toHaveBeenCalledExactlyOnceWith('processes');
|
||||
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('each resource has its own independent debounce timer', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
const snapshot = makeSnapshotFn({
|
||||
'processes': 'p',
|
||||
'qq-list': 'q',
|
||||
'connections': 'c',
|
||||
});
|
||||
const handle = bindStateStream({
|
||||
bus, snapshot,
|
||||
send: (f) => sent.push(f),
|
||||
debounceMs: 50,
|
||||
});
|
||||
|
||||
bus.publish('processes');
|
||||
await vi.advanceTimersByTimeAsync(30);
|
||||
bus.publish('qq-list');
|
||||
await vi.advanceTimersByTimeAsync(25); // processes fires at t=50 (5ms after this), qq-list pending till t=80
|
||||
expect(sent.map((f) => f.resource)).toEqual(['processes']);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30);
|
||||
expect(sent.map((f) => f.resource)).toEqual(['processes', 'qq-list']);
|
||||
|
||||
bus.publish('connections');
|
||||
await vi.advanceTimersByTimeAsync(51);
|
||||
expect(sent.map((f) => f.resource)).toEqual(['processes', 'qq-list', 'connections']);
|
||||
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('dispose() stops further sends, both pending and future', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
const snapshot = makeSnapshotFn({ 'processes': 'x' });
|
||||
const handle = bindStateStream({
|
||||
bus, snapshot,
|
||||
send: (f) => sent.push(f),
|
||||
debounceMs: 50,
|
||||
});
|
||||
|
||||
bus.publish('processes');
|
||||
handle.dispose();
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(sent).toEqual([]);
|
||||
|
||||
// Subsequent publishes are dead too.
|
||||
bus.publish('processes');
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('snapshot() rejection is isolated — the failed resource is skipped and others keep flowing', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
const snapshot = vi.fn(async (resource: StateResource): Promise<unknown> => {
|
||||
if (resource === 'processes') throw new Error('listProcesses failed');
|
||||
if (resource === 'qq-list') return [{ uin: '1' }];
|
||||
return [];
|
||||
});
|
||||
const handle = bindStateStream({
|
||||
bus, snapshot,
|
||||
send: (f) => sent.push(f),
|
||||
debounceMs: 50,
|
||||
});
|
||||
|
||||
bus.publish('processes');
|
||||
bus.publish('qq-list');
|
||||
await vi.advanceTimersByTimeAsync(60);
|
||||
|
||||
// qq-list went through; processes didn't (snapshot threw).
|
||||
expect(sent.find((f) => f.resource === 'qq-list')?.data).toEqual([{ uin: '1' }]);
|
||||
expect(sent.find((f) => f.resource === 'processes')).toBeUndefined();
|
||||
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('serialises overlapping flushes for the same resource — the LAST sent frame reflects the LATEST publish (no stale overwrite)', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
// Variable-latency snapshot: 1st call sleeps 200ms (slow), 2nd call
|
||||
// sleeps 10ms (fast). Without single-flight, the second publish would
|
||||
// race-overlap and send BEFORE the first, leaving the client's last
|
||||
// observed frame as the older snapshot.
|
||||
let call = 0;
|
||||
const versions = ['snap-T0', 'snap-T60'];
|
||||
const snapshot = vi.fn(async (_resource: StateResource): Promise<unknown> => {
|
||||
const i = call++;
|
||||
const sleep = i === 0 ? 200 : 10;
|
||||
await new Promise<void>((r) => setTimeout(r, sleep));
|
||||
return versions[i] ?? `snap-#${i}`;
|
||||
});
|
||||
const handle = bindStateStream({
|
||||
bus, snapshot,
|
||||
send: (f) => sent.push(f),
|
||||
debounceMs: 50,
|
||||
});
|
||||
|
||||
bus.publish('processes'); // schedules timer1 → fires at 50, snapshot A (200ms)
|
||||
await vi.advanceTimersByTimeAsync(60);
|
||||
bus.publish('processes'); // arrives WHILE flush A is mid-snapshot
|
||||
await vi.advanceTimersByTimeAsync(60); // hits 120: timer2 should have fired, flush B observed_after A completes
|
||||
await vi.advanceTimersByTimeAsync(300); // settle everything
|
||||
|
||||
// Exactly two frames; the LAST one must reflect the most recent snapshot.
|
||||
expect(sent).toHaveLength(2);
|
||||
expect(sent[sent.length - 1]).toEqual({ resource: 'processes', data: 'snap-T60' });
|
||||
// For single-flight: snapshot is called once per flush (no overlap),
|
||||
// so the SECOND snapshot read sees the latest state.
|
||||
expect(call).toBe(2);
|
||||
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('multiple publishes during an in-flight flush coalesce into ONE follow-up flush, not N', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
let call = 0;
|
||||
const snapshot = vi.fn(async (_resource: StateResource): Promise<unknown> => {
|
||||
call++;
|
||||
await new Promise<void>((r) => setTimeout(r, 100));
|
||||
return `snap-#${call}`;
|
||||
});
|
||||
const handle = bindStateStream({
|
||||
bus, snapshot,
|
||||
send: (f) => sent.push(f),
|
||||
debounceMs: 50,
|
||||
});
|
||||
|
||||
bus.publish('processes');
|
||||
await vi.advanceTimersByTimeAsync(55);
|
||||
// flush A in flight (100ms more). Send 5 publishes during the in-flight window.
|
||||
for (let i = 0; i < 5; i++) bus.publish('processes');
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
|
||||
// 1 initial flush + 1 coalesced follow-up = 2 frames, NOT 6.
|
||||
expect(sent).toHaveLength(2);
|
||||
expect(call).toBe(2);
|
||||
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('send() throw is isolated — the next publish still reaches a healthy send()', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
let mode: 'throw' | 'ok' = 'throw';
|
||||
const snapshot = makeSnapshotFn({ 'processes': 'x' });
|
||||
const handle = bindStateStream({
|
||||
bus, snapshot,
|
||||
send: (f) => {
|
||||
if (mode === 'throw') throw new Error('controller dead');
|
||||
sent.push(f);
|
||||
},
|
||||
debounceMs: 50,
|
||||
});
|
||||
|
||||
bus.publish('processes');
|
||||
await vi.advanceTimersByTimeAsync(60);
|
||||
expect(sent).toEqual([]);
|
||||
|
||||
mode = 'ok';
|
||||
bus.publish('processes');
|
||||
await vi.advanceTimersByTimeAsync(60);
|
||||
expect(sent).toEqual([{ resource: 'processes', data: 'x' }]);
|
||||
|
||||
handle.dispose();
|
||||
});
|
||||
});
|
||||
82
packages/core/tests/webui-state-wiring.test.ts
Normal file
82
packages/core/tests/webui-state-wiring.test.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { StateBus } from '../src/webui/state-bus';
|
||||
import { createStateWiring } from '../src/webui/state-wiring';
|
||||
import { BridgeManager } from '../src/bridge/manager';
|
||||
|
||||
describe('createStateWiring', () => {
|
||||
it('provides a fresh StateBus and an onSessionsChanged that publishes "processes"', () => {
|
||||
const wiring = createStateWiring();
|
||||
expect(wiring.bus).toBeInstanceOf(StateBus);
|
||||
const sub = vi.fn();
|
||||
wiring.bus.subscribe(sub);
|
||||
wiring.onSessionsChanged();
|
||||
expect(sub).toHaveBeenCalledExactlyOnceWith('processes');
|
||||
});
|
||||
|
||||
it('binds a BridgeManager so session-started publishes both "qq-list" and "connections"', () => {
|
||||
const wiring = createStateWiring();
|
||||
const bm = new BridgeManager();
|
||||
wiring.bindBridgeManager(bm);
|
||||
const seen: string[] = [];
|
||||
wiring.bus.subscribe((r) => seen.push(r));
|
||||
|
||||
// Real onHookLogin path — fires the session-started listener internally
|
||||
// exactly once (per uin).
|
||||
bm.onHookLogin(4242, '12345', {} as never);
|
||||
expect(seen).toEqual(['qq-list', 'connections']);
|
||||
});
|
||||
|
||||
it('publishes "qq-list" + "connections" on session-closed', () => {
|
||||
const wiring = createStateWiring();
|
||||
const bm = new BridgeManager();
|
||||
wiring.bindBridgeManager(bm);
|
||||
bm.onHookLogin(4242, '12345', {} as never);
|
||||
const sub = vi.fn();
|
||||
wiring.bus.subscribe(sub);
|
||||
|
||||
bm.onPidDisconnected(4242);
|
||||
|
||||
// Order is qq-list first (account list shrinks) then connections
|
||||
// (adapter status list shrinks). Two distinct resource invalidations.
|
||||
expect(sub).toHaveBeenCalledTimes(2);
|
||||
expect(sub).toHaveBeenNthCalledWith(1, 'qq-list');
|
||||
expect(sub).toHaveBeenNthCalledWith(2, 'connections');
|
||||
});
|
||||
|
||||
it('dispose() unwires onSessionsChanged + BridgeManager listeners (no further publishes)', () => {
|
||||
const wiring = createStateWiring();
|
||||
const bm = new BridgeManager();
|
||||
wiring.bindBridgeManager(bm);
|
||||
const sub = vi.fn();
|
||||
wiring.bus.subscribe(sub);
|
||||
|
||||
wiring.dispose();
|
||||
|
||||
// onSessionsChanged becomes a no-op.
|
||||
wiring.onSessionsChanged();
|
||||
expect(sub).not.toHaveBeenCalled();
|
||||
|
||||
// BridgeManager listener fires nothing into a disposed bus.
|
||||
bm.onHookLogin(4242, '12345', {} as never);
|
||||
expect(sub).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('survives a BridgeManager listener throw — the OTHER listeners on the same BridgeManager keep working', () => {
|
||||
const wiring = createStateWiring();
|
||||
const bm = new BridgeManager();
|
||||
wiring.bindBridgeManager(bm);
|
||||
|
||||
// A peer subscriber (e.g. OneBotManager) added AFTER state-wiring throws.
|
||||
const peer = vi.fn(() => { throw new Error('peer down'); });
|
||||
bm.addSessionStartedListener(peer);
|
||||
|
||||
const sub = vi.fn();
|
||||
wiring.bus.subscribe(sub);
|
||||
|
||||
expect(() => bm.onHookLogin(4242, '12345', {} as never)).not.toThrow();
|
||||
// The state-wiring listener still ran (BridgeManager isolates exceptions
|
||||
// per listener).
|
||||
expect(sub).toHaveBeenCalledWith('qq-list');
|
||||
expect(sub).toHaveBeenCalledWith('connections');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/mcp",
|
||||
"version": "1.10.0",
|
||||
"version": "1.11.3",
|
||||
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -29,4 +29,11 @@ it('generates src/generated/catalog.ts from the live action specs', () => {
|
||||
const dir = new URL('../src/generated/', import.meta.url);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(new URL('../src/generated/catalog.ts', import.meta.url), body);
|
||||
|
||||
// Plain-JSON twin of the catalog, consumed by the docs site (SnowLumaDocs)
|
||||
// via the sync-docs-catalog workflow. Same data as catalog.ts.
|
||||
writeFileSync(
|
||||
new URL('../src/generated/catalog.json', import.meta.url),
|
||||
JSON.stringify({ actions, categories }, null, 2) + '\n',
|
||||
);
|
||||
});
|
||||
|
||||
10065
packages/mcp/src/generated/catalog.json
Normal file
10065
packages/mcp/src/generated/catalog.json
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -11,6 +11,11 @@ export interface CatalogParam {
|
||||
default?: unknown;
|
||||
desc?: string;
|
||||
values?: ReadonlyArray<string | number>;
|
||||
/** Semantic role (group_id / user_id / member_id / image / face_id / …),
|
||||
* orthogonal to `type`; drives smart-widget selection in the WebUI console.
|
||||
* Kept as a loose string here so the package stays decoupled from onebot's
|
||||
* FieldRole union. */
|
||||
role?: string;
|
||||
/** JSON Schema fragment for this single field. */
|
||||
schema?: Record<string, unknown>;
|
||||
}
|
||||
@@ -21,10 +26,15 @@ export interface CatalogAction {
|
||||
category?: string;
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
/** JSON Schema for the action's `data` payload (absent when undocumented). */
|
||||
returnsSchema?: Record<string, unknown>;
|
||||
/** True only for pure data-fetch actions (no side effects). Drives the
|
||||
* read/write tool routing: read-only → query_action, else → invoke_action.
|
||||
* Classified at the source spec by what the action's `run` actually does. */
|
||||
readOnly: boolean;
|
||||
/** True for Stream API actions (multi-frame transport). Absent ⇒ ordinary
|
||||
* single-response action. */
|
||||
stream?: boolean;
|
||||
params: CatalogParam[];
|
||||
/** Cross-field invariants, e.g. "exactly one of: message_id | (group_id+user_id)". */
|
||||
invariants: string[];
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "1.10.0",
|
||||
"version": "1.11.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
|
||||
@@ -40,6 +40,10 @@
|
||||
"types": "./src/config.ts",
|
||||
"default": "./src/config.ts"
|
||||
},
|
||||
"./global-config": {
|
||||
"types": "./src/global-config.ts",
|
||||
"default": "./src/global-config.ts"
|
||||
},
|
||||
"./types": {
|
||||
"types": "./src/types.ts",
|
||||
"default": "./src/types.ts"
|
||||
|
||||
@@ -12,44 +12,19 @@
|
||||
// deferred product decision; this module produces format-agnostic data plus a
|
||||
// Markdown default. Point any renderer at `collectActionDocs()`.
|
||||
|
||||
import type { ActionDoc, ActionSpec, Field } from './action-kit';
|
||||
import { actions as infoActions } from './actions/info';
|
||||
import { actions as messageActions } from './actions/message';
|
||||
import { actions as friendActions } from './actions/friend';
|
||||
import { actions as groupInfoActions } from './actions/group-info';
|
||||
import { actions as groupAdminActions } from './actions/group-admin';
|
||||
import { actions as groupFileActions } from './actions/group-file';
|
||||
import { actions as requestActions } from './actions/request';
|
||||
import { actions as extendedActions } from './actions/extended';
|
||||
import { actions as groupAlbumActions } from './actions/group-album';
|
||||
import { actions as qzoneActions } from './actions/qzone';
|
||||
|
||||
type AnySpec = ActionSpec<Record<string, Field<unknown>>>;
|
||||
|
||||
// Source file = domain category. Each doc is tagged so the MCP / UI can group.
|
||||
const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [
|
||||
{ category: '信息', specs: infoActions },
|
||||
{ category: '消息', specs: messageActions },
|
||||
{ category: '好友', specs: friendActions },
|
||||
{ category: '群信息', specs: groupInfoActions },
|
||||
{ category: '群管理', specs: groupAdminActions },
|
||||
{ category: '群文件', specs: groupFileActions },
|
||||
{ category: '请求', specs: requestActions },
|
||||
{ category: '扩展', specs: extendedActions },
|
||||
{ category: '群相册', specs: groupAlbumActions },
|
||||
{ category: '空间', specs: qzoneActions },
|
||||
];
|
||||
import type { ActionDoc } from './action-kit';
|
||||
import { ACTION_GROUPS } from './actions';
|
||||
|
||||
/** Every declarative action's doc (with category), sorted by name. */
|
||||
export function collectActionDocs(): ActionDoc[] {
|
||||
return GROUPS
|
||||
.flatMap(({ category, specs }) => specs.map((s) => ({ ...s.describe(), category })))
|
||||
return ACTION_GROUPS
|
||||
.flatMap(({ category, actions }) => actions.map((s) => ({ ...s.describe(), category })))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Distinct categories with action counts. */
|
||||
export function collectCategories(): Array<{ category: string; count: number }> {
|
||||
return GROUPS.map(({ category, specs }) => ({ category, count: specs.length }));
|
||||
return ACTION_GROUPS.map(({ category, actions }) => ({ category, count: actions.length }));
|
||||
}
|
||||
|
||||
function paramRow(p: ActionDoc['params'][number]): string {
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
import { RETCODE, failedResponse } from './types';
|
||||
import type { ApiResponse, JsonObject, JsonValue } from './types';
|
||||
import type { ApiActionContext, ApiHandler } from './api-handler';
|
||||
import { type StreamSink, NOOP_SINK } from './streaming';
|
||||
|
||||
// ─────────────────────────── result currency ───────────────────────────
|
||||
|
||||
@@ -43,12 +44,33 @@ type Raw = JsonValue | typeof MISSING;
|
||||
* them into an action's `inputSchema` (consumed by docs / the MCP). */
|
||||
export type JsonSchema = Record<string, unknown>;
|
||||
|
||||
/** Semantic role of a param, orthogonal to `type` (which governs coercion).
|
||||
* Two `uint` fields `group_id` and `user_id` coerce identically but mean
|
||||
* different things — `role` is what a UI keys its picker/widget off of.
|
||||
* Closed set: consumers (the WebUI debug console) switch on it exhaustively
|
||||
* and fall back to the plain typed control for anything unrecognised. */
|
||||
export type FieldRole =
|
||||
| 'group_id'
|
||||
| 'user_id'
|
||||
| 'member_id' // a group member's uin — its picker depends on a sibling group_id
|
||||
| 'message_id'
|
||||
| 'file_id'
|
||||
| 'file'
|
||||
| 'image'
|
||||
| 'record'
|
||||
| 'video'
|
||||
| 'duration'
|
||||
| 'timestamp'
|
||||
| 'face_id';
|
||||
|
||||
export interface FieldDoc {
|
||||
type: string;
|
||||
required: boolean;
|
||||
default?: JsonValue;
|
||||
desc?: string;
|
||||
values?: readonly (string | number)[];
|
||||
/** Semantic role driving UI widget selection; orthogonal to `type`. */
|
||||
role?: FieldRole;
|
||||
/** JSON Schema fragment for this field's value (constraints only; presence
|
||||
* and default are applied at the object level by `describe()`). */
|
||||
schema?: JsonSchema;
|
||||
@@ -64,6 +86,10 @@ export interface Field<T> {
|
||||
* numeric field is an error, not a silent fallback). */
|
||||
default(value: T): Field<T>;
|
||||
describe(text: string): Field<T>;
|
||||
/** Stamp a semantic role (escape hatch for params whose name lies, or to
|
||||
* override a preset). Most call sites use the `f.groupId()`-style semantic
|
||||
* constructors instead. */
|
||||
role(role: FieldRole): Field<T>;
|
||||
/** Complete JSON Schema for this field's value (constraints + description +
|
||||
* default). Object-level required-ness is handled by `describe()`. */
|
||||
toJsonSchema(): JsonSchema;
|
||||
@@ -103,10 +129,15 @@ class FieldImpl<T> implements Field<T> {
|
||||
return new FieldImpl<T>(this.core, { ...this.doc, desc: text });
|
||||
}
|
||||
|
||||
role(role: FieldRole): Field<T> {
|
||||
return new FieldImpl<T>(this.core, { ...this.doc, role });
|
||||
}
|
||||
|
||||
toJsonSchema(): JsonSchema {
|
||||
const out: JsonSchema = { ...(this.doc.schema ?? {}) };
|
||||
if (this.doc.desc) out.description = this.doc.desc;
|
||||
if (this.doc.default !== undefined) out.default = this.doc.default;
|
||||
if (this.doc.role) out['x-role'] = this.doc.role;
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -147,6 +178,21 @@ function strSchema(opts: StrOpts): JsonSchema {
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Coerce to string (numbers/booleans stringify; matches legacy `asString`),
|
||||
* then apply emptiness / length bounds. Shared by `f.string()` and the
|
||||
* string-valued semantic constructors. */
|
||||
function stringCore(opts: StrOpts): Core<string> {
|
||||
return (raw, field) => {
|
||||
let s: string;
|
||||
if (typeof raw === 'string') s = raw;
|
||||
else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw);
|
||||
else return err(field, 'expected a string');
|
||||
if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty');
|
||||
if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`);
|
||||
return ok(s);
|
||||
};
|
||||
}
|
||||
|
||||
function arrayField<E>(el: Field<E>, mustBeNonEmpty: boolean): Field<E[]> & { nonEmpty(): Field<E[]> } {
|
||||
const core: Core<E[]> = (raw, field) => {
|
||||
if (!Array.isArray(raw)) return err(field, 'expected an array');
|
||||
@@ -180,7 +226,59 @@ export const f = {
|
||||
/** OneBot message id: a non-zero integer. NEGATIVES ARE VALID (ids are a
|
||||
* signed int32 hash) — do NOT use `uint()` for message_id. */
|
||||
messageId(): Field<number> {
|
||||
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, schema: intSchema({ nonZero: true }) });
|
||||
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, role: 'message_id', schema: intSchema({ nonZero: true }) });
|
||||
},
|
||||
// ── Semantic constructors (role-stamped) ──
|
||||
// Each wraps a coercion primitive and stamps a `role` so the WebUI debug
|
||||
// console renders the right picker. The Agent backfill replaces a bare
|
||||
// `f.uint()` named `group_id` with `f.groupId()`, etc. — purely additive to
|
||||
// coercion (a groupId still coerces exactly like a uint).
|
||||
/** Group number (uint) → group picker. */
|
||||
groupId(): Field<number> {
|
||||
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'group_id', schema: intSchema({ min: 1 }) });
|
||||
},
|
||||
/** Friend / stranger uin (uint) → friend picker. */
|
||||
userId(): Field<number> {
|
||||
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'user_id', schema: intSchema({ min: 1 }) });
|
||||
},
|
||||
/** Group member's uin (uint) → member picker, linked to a sibling group_id. */
|
||||
memberId(): Field<number> {
|
||||
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, role: 'member_id', schema: intSchema({ min: 1 }) });
|
||||
},
|
||||
/** Opaque file id (string) → file picker / history. */
|
||||
fileId(): Field<string> {
|
||||
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'file_id', schema: strSchema({ allowEmpty: false }) });
|
||||
},
|
||||
// Media sources reject '' (an empty path/URL is meaningless) — this matches
|
||||
// the `f.string({ allowEmpty: false })` they replace during backfill, so the
|
||||
// swap preserves the empty-string guard.
|
||||
/** Local path / URL / base64 of a generic file → FileSource control. */
|
||||
file(): Field<string> {
|
||||
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'file', schema: strSchema({ allowEmpty: false }) });
|
||||
},
|
||||
/** Image source (path / URL / base64) → FileSource control. */
|
||||
image(): Field<string> {
|
||||
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'image', schema: strSchema({ allowEmpty: false }) });
|
||||
},
|
||||
/** Voice/record source → FileSource control. */
|
||||
record(): Field<string> {
|
||||
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'record', schema: strSchema({ allowEmpty: false }) });
|
||||
},
|
||||
/** Video source → FileSource control. */
|
||||
video(): Field<string> {
|
||||
return new FieldImpl<string>(stringCore({ allowEmpty: false }), { type: 'string', required: true, role: 'video', schema: strSchema({ allowEmpty: false }) });
|
||||
},
|
||||
/** Seconds (int ≥ 0) → duration control. */
|
||||
duration(): Field<number> {
|
||||
return new FieldImpl<number>(intCore('an integer', { min: 0 }), { type: 'int', required: true, role: 'duration', schema: intSchema({ min: 0 }) });
|
||||
},
|
||||
/** Unix timestamp (int ≥ 0) → datetime control. */
|
||||
timestamp(): Field<number> {
|
||||
return new FieldImpl<number>(intCore('an integer', { min: 0 }), { type: 'int', required: true, role: 'timestamp', schema: intSchema({ min: 0 }) });
|
||||
},
|
||||
/** QQ face id (non-negative int; face 0 is valid) → face grid. */
|
||||
faceId(): Field<number> {
|
||||
return new FieldImpl<number>(intCore('a non-negative integer', { min: 0 }), { type: 'int', required: true, role: 'face_id', schema: intSchema({ min: 0 }) });
|
||||
},
|
||||
/** Finite number (fractions allowed). */
|
||||
number(): Field<number> {
|
||||
@@ -193,15 +291,7 @@ export const f = {
|
||||
/** String. Numbers/booleans stringify (matches legacy `asString`). Empty
|
||||
* allowed by default; `{ allowEmpty: false }` rejects ''. */
|
||||
string(opts: StrOpts = {}): Field<string> {
|
||||
return new FieldImpl<string>((raw, field) => {
|
||||
let s: string;
|
||||
if (typeof raw === 'string') s = raw;
|
||||
else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw);
|
||||
else return err(field, 'expected a string');
|
||||
if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty');
|
||||
if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`);
|
||||
return ok(s);
|
||||
}, { type: 'string', required: true, schema: strSchema(opts) });
|
||||
return new FieldImpl<string>(stringCore(opts), { type: 'string', required: true, schema: strSchema(opts) });
|
||||
},
|
||||
/** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */
|
||||
bool(): Field<boolean> {
|
||||
@@ -331,9 +421,17 @@ export interface ActionDoc {
|
||||
category?: string;
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
/** JSON Schema for the `data` payload inside the OneBot envelope (NOT the
|
||||
* whole envelope). Optional + authored incrementally; absent ⇒ data shape
|
||||
* is documented only by the prose `returns`. */
|
||||
returnsSchema?: JsonSchema;
|
||||
/** True only for pure data-fetch actions (no side effects). Drives the MCP's
|
||||
* read/write tool routing; defaults to false (treated as a write). */
|
||||
readOnly: boolean;
|
||||
/** True for Stream API actions (`defineStreamAction`) — they push multiple
|
||||
* frames through a sink, so a caller must use the streaming transport rather
|
||||
* than a single request/response. Absent ⇒ ordinary single-response action. */
|
||||
stream?: boolean;
|
||||
params: ParamDoc[];
|
||||
invariants: string[];
|
||||
/** Composed JSON Schema for the whole params object (properties + required). */
|
||||
@@ -342,22 +440,32 @@ export interface ActionDoc {
|
||||
|
||||
type Handler = (params: JsonObject) => Promise<ApiResponse>;
|
||||
|
||||
export interface ActionSpec<S extends Spec> {
|
||||
/**
|
||||
* The narrow shape both `ActionSpec` and `StreamActionSpec` share — enough to
|
||||
* register a spec onto an `ApiHandler` and to collect its docs. The action
|
||||
* registry barrel (`actions/index.ts`) is typed against this so it can hold
|
||||
* both kinds in one flat list without coupling to either concrete generic.
|
||||
*/
|
||||
export interface RegisteredActionSpec {
|
||||
describe(): ActionDoc;
|
||||
register(h: ApiHandler, ctx: ApiActionContext): void;
|
||||
}
|
||||
|
||||
export interface ActionSpec<S extends Spec> extends RegisteredActionSpec {
|
||||
readonly names: string[];
|
||||
readonly params: S;
|
||||
/** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */
|
||||
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
|
||||
/** Bind ctx and produce the `(params) => ApiResponse` for `registerAction`. */
|
||||
toHandler(ctx: ApiActionContext): Handler;
|
||||
/** Doc metadata (D4); a renderer walks this. */
|
||||
describe(): ActionDoc;
|
||||
register(h: ApiHandler, ctx: ApiActionContext): void;
|
||||
}
|
||||
|
||||
interface ActionDef<S extends Spec> {
|
||||
name: string | readonly [string, ...string[]];
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
/** JSON Schema for the `data` payload (NOT the envelope). See ActionDoc. */
|
||||
returnsSchema?: JsonSchema;
|
||||
/** Mark true ONLY for pure data-fetch actions with no side effects. Default
|
||||
* false = write. Surfaced via describe() into the catalog for the MCP's
|
||||
* read/write routing. Classify by what `run` actually does, not the name. */
|
||||
@@ -425,6 +533,7 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
|
||||
aliases: names.slice(1),
|
||||
summary: def.summary,
|
||||
returns: def.returns,
|
||||
returnsSchema: def.returnsSchema,
|
||||
readOnly: def.readOnly ?? false,
|
||||
params: entries.map(([name, field]) => ({ name, ...field.doc })),
|
||||
invariants: rules.map((rule) => rule.doc),
|
||||
@@ -438,6 +547,61 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────────────────── defineStreamAction ───────────────────────────
|
||||
// A Stream API action (#163): same param contract + doc machinery as
|
||||
// `defineAction`, but `run` additionally receives a `StreamSink` to push
|
||||
// intermediate frames, and it registers via `registerStreamAction` so the
|
||||
// network adapter streams its output. The handler's return value is still the
|
||||
// terminal `ApiResponse` (the final frame). Reuses `defineAction` for
|
||||
// parse/describe so the two stay in lock-step.
|
||||
|
||||
interface StreamActionDef<S extends Spec> {
|
||||
name: string | readonly [string, ...string[]];
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
returnsSchema?: JsonSchema;
|
||||
readOnly?: boolean;
|
||||
params: S;
|
||||
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
|
||||
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject, sink: StreamSink) => Promise<ApiResponse> | ApiResponse;
|
||||
}
|
||||
|
||||
export interface StreamActionSpec<S extends Spec> extends RegisteredActionSpec {
|
||||
readonly names: string[];
|
||||
readonly params: S;
|
||||
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
|
||||
}
|
||||
|
||||
export function defineStreamAction<S extends Spec>(def: StreamActionDef<S>): StreamActionSpec<S> {
|
||||
// Borrow defineAction's parse + describe (run is never invoked — register
|
||||
// below installs the sink-aware handler instead).
|
||||
const base = defineAction<S>({
|
||||
name: def.name,
|
||||
summary: def.summary,
|
||||
returns: def.returns,
|
||||
returnsSchema: def.returnsSchema,
|
||||
readOnly: def.readOnly,
|
||||
params: def.params,
|
||||
rules: def.rules,
|
||||
run: () => failedResponse(RETCODE.INTERNAL_ERROR, 'stream action dispatched without a sink'),
|
||||
});
|
||||
|
||||
return {
|
||||
names: base.names,
|
||||
params: def.params,
|
||||
parse: base.parse,
|
||||
describe: () => ({ ...base.describe(), stream: true }),
|
||||
register: (h, ctx) => {
|
||||
const handler = async (params: JsonObject, sink?: StreamSink): Promise<ApiResponse> => {
|
||||
const r = base.parse(params);
|
||||
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
|
||||
return def.run(r.value, ctx, params, sink ?? NOOP_SINK);
|
||||
};
|
||||
for (const name of base.names) h.registerStreamAction(name, handler);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────────────────── presets ───────────────────────────
|
||||
// `group_id` appears in 61/142 actions, `user_id` in 27 — these collapse the
|
||||
// dominant shape. The injected fields are surfaced in `describe()` so docs
|
||||
@@ -450,6 +614,7 @@ interface PresetDef<S extends Spec, Extra> {
|
||||
name: string | readonly [string, ...string[]];
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
returnsSchema?: JsonSchema;
|
||||
readOnly?: boolean;
|
||||
params?: S;
|
||||
rules?: (r: RuleBuilders<InferParams<S> & Extra>) => readonly CrossFieldRule[];
|
||||
@@ -458,7 +623,7 @@ interface PresetDef<S extends Spec, Extra> {
|
||||
|
||||
/** Pre-seeds `group_id` (uint, required). */
|
||||
export function groupAction<S extends Spec>(def: PresetDef<S, { group_id: number }>): ActionSpec<WithGroup<S>> {
|
||||
const params = { group_id: f.uint().describe('群号'), ...(def.params ?? {}) } as WithGroup<S>;
|
||||
const params = { group_id: f.groupId().describe('群号'), ...(def.params ?? {}) } as WithGroup<S>;
|
||||
return defineAction({ ...def, params } as unknown as ActionDef<WithGroup<S>>);
|
||||
}
|
||||
|
||||
@@ -467,8 +632,10 @@ export function groupUserAction<S extends Spec>(
|
||||
def: PresetDef<S, { group_id: number; user_id: number }>,
|
||||
): ActionSpec<WithGroupUser<S>> {
|
||||
const params = {
|
||||
group_id: f.uint().describe('群号'),
|
||||
user_id: f.uint().describe('QQ 号'),
|
||||
group_id: f.groupId().describe('群号'),
|
||||
// In a group action, the user_id is a member of *that* group — so its
|
||||
// picker links to the sibling group_id (member_id role, not user_id).
|
||||
user_id: f.memberId().describe('QQ 号'),
|
||||
...(def.params ?? {}),
|
||||
} as WithGroupUser<S>;
|
||||
return defineAction({ ...def, params } as unknown as ActionDef<WithGroupUser<S>>);
|
||||
@@ -478,6 +645,6 @@ export function groupUserAction<S extends Spec>(
|
||||
|
||||
/** Register many specs onto an ApiHandler. Coexists with legacy
|
||||
* `h.registerAction(name, fn)` in the same `register(h, ctx)`. */
|
||||
export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray<ActionSpec<Spec>>): void {
|
||||
export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray<RegisteredActionSpec>): void {
|
||||
for (const spec of specs) spec.register(h, ctx);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,4 @@
|
||||
import { defineAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { defineAction, f } from '../action-kit';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
export const actions = [
|
||||
@@ -7,6 +6,19 @@ export const actions = [
|
||||
name: 'get_friend_list',
|
||||
summary: '获取好友列表',
|
||||
readOnly: true,
|
||||
returns: '好友列表数组,每项含 QQ 号、昵称与备注。',
|
||||
returnsSchema: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
user_id: { type: 'integer', description: '好友 QQ 号' },
|
||||
nickname: { type: 'string', description: '好友昵称' },
|
||||
remark: { type: 'string', description: '好友备注' },
|
||||
},
|
||||
required: ['user_id', 'nickname', 'remark'],
|
||||
},
|
||||
},
|
||||
params: {},
|
||||
run: async (_p, ctx) => {
|
||||
if (ctx.getFriendList) {
|
||||
@@ -20,7 +32,20 @@ export const actions = [
|
||||
name: 'get_stranger_info',
|
||||
summary: '获取陌生人信息',
|
||||
readOnly: true,
|
||||
params: { user_id: f.uint().describe('QQ 号') },
|
||||
returns: '陌生人资料:QQ 号、昵称、性别、年龄,命中资料时另含等级。',
|
||||
returnsSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
user_id: { type: 'integer', description: 'QQ 号' },
|
||||
nickname: { type: 'string', description: '昵称' },
|
||||
sex: { type: 'string', description: '性别(male/female/unknown)' },
|
||||
age: { type: 'integer', description: '年龄' },
|
||||
qq_level: { type: 'integer', description: 'QQ 等级(仅查到资料时返回)' },
|
||||
level: { type: 'integer', description: 'QQ 等级,同 qq_level(仅查到资料时返回)' },
|
||||
},
|
||||
required: ['user_id', 'nickname', 'sex', 'age'],
|
||||
},
|
||||
params: { user_id: f.userId().describe('QQ 号') },
|
||||
run: async (p, ctx) => {
|
||||
const userId = p.user_id;
|
||||
if (ctx.getStrangerInfo) {
|
||||
@@ -34,7 +59,7 @@ export const actions = [
|
||||
defineAction({
|
||||
name: 'delete_friend',
|
||||
summary: '删除好友',
|
||||
params: { user_id: f.uint().describe('QQ 号'), block: f.bool().default(false) },
|
||||
params: { user_id: f.userId().describe('QQ 号'), block: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.friend.delete(p.user_id, p.block);
|
||||
return okResponse();
|
||||
@@ -42,6 +67,3 @@ export const actions = [
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
export const actions = [
|
||||
groupUserAction({
|
||||
@@ -16,7 +15,7 @@ export const actions = [
|
||||
groupAction({
|
||||
name: 'set_group_kick_members',
|
||||
summary: '批量踢出群成员',
|
||||
params: { user_id: f.array(f.uint()).nonEmpty(), reject_add_request: f.bool().default(false) },
|
||||
params: { user_id: f.array(f.memberId()).nonEmpty(), reject_add_request: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.kickMembers(p.group_id, p.user_id, p.reject_add_request);
|
||||
return okResponse();
|
||||
@@ -26,7 +25,7 @@ export const actions = [
|
||||
groupUserAction({
|
||||
name: 'set_group_ban',
|
||||
summary: '禁言群成员(duration=0 解除)',
|
||||
params: { duration: f.int({ min: 0 }).default(1800) },
|
||||
params: { duration: f.duration().default(1800) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.muteMember(p.group_id, p.user_id, p.duration);
|
||||
return okResponse();
|
||||
@@ -55,9 +54,13 @@ export const actions = [
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_search',
|
||||
summary: '允许群被搜索',
|
||||
summary: '设置群被搜索方式(群指纹 / 群号搜索开关)',
|
||||
params: {
|
||||
no_finger_open: f.int({ min: 0 }).optional(),
|
||||
no_code_finger_open: f.int({ min: 0 }).optional(),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setSearch(p.group_id);
|
||||
await ctx.bridge.apis.groupAdmin.setSearch(p.group_id, p.no_finger_open, p.no_code_finger_open);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
@@ -118,18 +121,11 @@ export const actions = [
|
||||
groupAction({
|
||||
name: 'set_group_portrait',
|
||||
summary: '设置群头像',
|
||||
params: { file: f.string({ allowEmpty: false }) },
|
||||
params: { file: f.image() },
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
|
||||
return okResponse();
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user