Compare commits
265
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92a1a02dd3 | ||
|
|
87527cb764 | ||
|
|
44679bebd4 | ||
|
|
f95d247e73 | ||
|
|
c989c764e3 | ||
|
|
940b823571 | ||
|
|
e0801ff9eb | ||
|
|
a71377ff17 | ||
|
|
f0203823e9 | ||
|
|
914e9a004f | ||
|
|
f588f0345c | ||
|
|
9632b00638 | ||
|
|
88cb2985e2 | ||
|
|
063ede4c62 | ||
|
|
12afae0632 | ||
|
|
89275ae279 | ||
|
|
1919e16081 | ||
|
|
a6dfd04924 | ||
|
|
99bcfca15c | ||
|
|
d86e0fc7b5 | ||
|
|
3068d3ef60 | ||
|
|
b69108e1cc | ||
|
|
b9bdcec5f1 | ||
|
|
2c7d9b6387 | ||
|
|
efb32ed069 | ||
|
|
cf2587a58b | ||
|
|
368becd078 | ||
|
|
93b5c1b4bf | ||
|
|
8cc5326a3a | ||
|
|
d610b3c90f | ||
|
|
797a4d754c | ||
|
|
7a07119ee9 | ||
|
|
1ef9a2c330 | ||
|
|
1914880df4 | ||
|
|
ad360c8eba | ||
|
|
0cc06b6b5e | ||
|
|
e05d3176a2 | ||
|
|
075a27cc46 | ||
|
|
805665a6d6 | ||
|
|
953b18b5cb | ||
|
|
1934e4e7f7 | ||
|
|
726fbc6c67 | ||
|
|
0591b160fb | ||
|
|
fe245d84bf | ||
|
|
d0a1b0e804 | ||
|
|
51c0ffab74 | ||
|
|
3e581780b3 | ||
|
|
173e21d80d | ||
|
|
5ac74ac5f5 | ||
|
|
1dffb22d05 | ||
|
|
dad2b0c5a7 | ||
|
|
b375e6f66e | ||
|
|
41b92263a7 | ||
|
|
6efadce2eb | ||
|
|
feea35da4c | ||
|
|
1ab14ea306 | ||
|
|
87e964ab95 | ||
|
|
b60b1a419c | ||
|
|
0ef9f9475c | ||
|
|
555e4be95e | ||
|
|
4ede23980c | ||
|
|
b8ba8a1792 | ||
|
|
20c31e11a8 | ||
|
|
ce050d1ba1 | ||
|
|
2a515c165c | ||
|
|
23ebee7f20 | ||
|
|
ad36d47cf0 | ||
|
|
f2d58d2f79 | ||
|
|
3cd35a76dd | ||
|
|
4e1cb51f98 | ||
|
|
5b71825ce3 | ||
|
|
55dbc022c4 | ||
|
|
b8680bbd69 | ||
|
|
aaf1e561d1 | ||
|
|
c88c8e7517 | ||
|
|
dac3deb7bd | ||
|
|
60c9669abd | ||
|
|
9ac39f480a | ||
|
|
6b66d4ab46 | ||
|
|
804b4c304c | ||
|
|
078900f81c | ||
|
|
62ab170b21 | ||
|
|
131a309381 | ||
|
|
0a6c5b7d2a | ||
|
|
7ef256c487 | ||
|
|
201d10c534 | ||
|
|
48ce95f53e | ||
|
|
26fe4e5fb5 | ||
|
|
4d6011ab04 | ||
|
|
445aac8638 | ||
|
|
95d4831da8 | ||
|
|
cfd8d5d651 | ||
|
|
463d62507a | ||
|
|
6328890d34 | ||
|
|
1bb8c9f46c | ||
|
|
acb0e04bbf | ||
|
|
6f278dc1da | ||
|
|
4379e4838d | ||
|
|
455763f109 | ||
|
|
83606270d8 | ||
|
|
47af79f9ac | ||
|
|
36c395a9b0 | ||
|
|
1bd26a906b | ||
|
|
f327fc1276 | ||
|
|
f5e95fc634 | ||
|
|
a7d293d79b | ||
|
|
6cf461ef8f | ||
|
|
a0f152229d | ||
|
|
f6adadcd12 | ||
|
|
117335166f | ||
|
|
9cdbcb0299 | ||
|
|
9e27910885 | ||
|
|
d05c516ed6 | ||
|
|
4b9921b711 | ||
|
|
c1a0091143 | ||
|
|
e1bb9b4722 | ||
|
|
ef73157c68 | ||
|
|
d474996485 | ||
|
|
0d73bb78d0 | ||
|
|
4457dd4b4a | ||
|
|
5ba7c21c4b | ||
|
|
a395577f77 | ||
|
|
5441203b76 | ||
|
|
2bd2643670 | ||
|
|
83f643f01b | ||
|
|
6782fd9cb3 | ||
|
|
39e6b45b81 | ||
|
|
6ec368f4b5 | ||
|
|
3045525e37 | ||
|
|
5ff12868bf | ||
|
|
bc070eca1c | ||
|
|
aaaf0994f6 | ||
|
|
8fbddf67bf | ||
|
|
62256ee816 | ||
|
|
e6aeef02b4 | ||
|
|
4b8cc4292b | ||
|
|
2b6a0ef3ff | ||
|
|
d8521d4345 | ||
|
|
8fdd41ea22 | ||
|
|
5a10fc4c9c | ||
|
|
0a924634b2 | ||
|
|
b088ffaff0 | ||
|
|
d879ba1027 | ||
|
|
3e31fe90dc | ||
|
|
c86982610f | ||
|
|
29e6baac72 | ||
|
|
86669d9451 | ||
|
|
b3bd68d48d | ||
|
|
096ad0acfa | ||
|
|
cc517080be | ||
|
|
b63c3c370b | ||
|
|
25a40f4ab6 | ||
|
|
cd6ada0caa | ||
|
|
3cb3024b39 | ||
|
|
b1fa11ca05 | ||
|
|
cfe61abce6 | ||
|
|
aec0c781b3 | ||
|
|
618dd52f46 | ||
|
|
d5f1e35c31 | ||
|
|
27284fd79b | ||
|
|
ecf0efc5e2 | ||
|
|
206727f823 | ||
|
|
9772d4f0bf | ||
|
|
55a2a24fc2 | ||
|
|
3fc521fb8b | ||
|
|
3941c825b5 | ||
|
|
30f0ae8571 | ||
|
|
b1730d74cd | ||
|
|
eee3c49f2d | ||
|
|
23352dcad4 | ||
|
|
226b48fd7a | ||
|
|
fea1996e46 | ||
|
|
94a8bf8609 | ||
|
|
44bbaaa1bb | ||
|
|
8583afaf2c | ||
|
|
6da412ab96 | ||
|
|
401f32d6b2 | ||
|
|
d014d6c379 | ||
|
|
925d9c0ac7 | ||
|
|
8e9e228a0f | ||
|
|
7ae0fa3c0e | ||
|
|
52f0f2d24b | ||
|
|
69a6148f75 | ||
|
|
e59f5e7c5b | ||
|
|
91f0eb3b7e | ||
|
|
a70a63343d | ||
|
|
2bbd98e90a | ||
|
|
c02c21c46b | ||
|
|
2e2c1266ac | ||
|
|
31bd8ea77b | ||
|
|
4c994dbd20 | ||
|
|
8004e9af9d | ||
|
|
80f34ca720 | ||
|
|
d46d8e4002 | ||
|
|
5a012fe0c8 | ||
|
|
b8b9be83c3 | ||
|
|
e7322e2e72 | ||
|
|
9e0dd5d75c | ||
|
|
7d5ca5523b | ||
|
|
d26aef86d8 | ||
|
|
f100faaeb6 | ||
|
|
2f5065545a | ||
|
|
5c2f620c54 | ||
|
|
679f3b5b9f | ||
|
|
8ded1065d4 | ||
|
|
b38db6715f | ||
|
|
58f1a1fc50 | ||
|
|
0357d136d8 | ||
|
|
190f156fca | ||
|
|
da3821ced4 | ||
|
|
1996192a5e | ||
|
|
fe44a2f5bc | ||
|
|
870e9a5fbc | ||
|
|
129b091081 | ||
|
|
dbf654ad57 | ||
|
|
c08150fc0c | ||
|
|
4aba81ec6b | ||
|
|
1e0c91e74d | ||
|
|
e08613062e | ||
|
|
cd6fcadea4 | ||
|
|
597a4c05f3 | ||
|
|
49439370e1 | ||
|
|
7eea8059cc | ||
|
|
c404974e75 | ||
|
|
4c385bf640 | ||
|
|
f968687a25 | ||
|
|
39d5a50d5f | ||
|
|
65683bb44d | ||
|
|
751217c13d | ||
|
|
c53c6651a5 | ||
|
|
005154077f | ||
|
|
1646f265ec | ||
|
|
4d958eb984 | ||
|
|
810509ef58 | ||
|
|
f1ae0736c6 | ||
|
|
c0e73cd738 | ||
|
|
27c527976b | ||
|
|
2ac0b92859 | ||
|
|
81699b839d | ||
|
|
634097460c | ||
|
|
c6619fda0a | ||
|
|
8e9a4d878e | ||
|
|
938975dd45 | ||
|
|
672802b424 | ||
|
|
185ba8353b | ||
|
|
f572be2561 | ||
|
|
c72de4adb6 | ||
|
|
198f25476f | ||
|
|
4b6237f24b | ||
|
|
4a0d14ce56 | ||
|
|
dae486a0ad | ||
|
|
8526d0c2c5 | ||
|
|
fb4d7716a1 | ||
|
|
6372e1479c | ||
|
|
3c97e71650 | ||
|
|
abe4ea80c8 | ||
|
|
ae2e894f14 | ||
|
|
3c772df818 | ||
|
|
8940f8864b | ||
|
|
ea841d929e | ||
|
|
e4179ffb47 | ||
|
|
958d17ecc0 | ||
|
|
8080104311 | ||
|
|
659e0bd3d0 | ||
|
|
b8ccbdbf18 |
No files matched your search
@@ -123,7 +123,7 @@ body:
|
||||
attributes:
|
||||
label: TRACE 日志 / 错误堆栈
|
||||
description: |
|
||||
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现。
|
||||
**必须提供 TRACE 级别日志**,否则我们几乎无法定位问题。SnowLuma 默认日志级别是 `info`,TRACE 不会输出,请务必先开启再复现,务必保留原始报文和完整Trace内容。
|
||||
|
||||
开启 TRACE 的两种方式(任选其一):
|
||||
- **WebUI(推荐)**:进入「日志」页 →「服务端日志级别」切到 `TRACE` → 显示过滤切到「开发」预设(确保 TRACE 行可见,否则导出不含 trace)→ 复现问题 → 点「导出当前视图」得到 `snowluma-logs-*.log`,拖到本输入框上传。
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# npm Trusted Publishing
|
||||
|
||||
The npm publish workflows use GitHub Actions OIDC instead of a long-lived
|
||||
`NPM_TOKEN`. Each package must have a matching Trusted Publisher entry on npm
|
||||
before its first publish after this migration.
|
||||
|
||||
For each package (`@snowluma/sdk`, `@snowluma/ui`, and `@snowluma/mcp`), open
|
||||
the package's npm settings and add a **GitHub Actions** trusted publisher with:
|
||||
|
||||
| Field | Value |
|
||||
| --- | --- |
|
||||
| Organization or user | `SnowLuma` |
|
||||
| Repository | `SnowLuma` |
|
||||
| Workflow filename | The exact filename below |
|
||||
| Environment | `SnowLuma` |
|
||||
|
||||
| Package | Workflow filename |
|
||||
| --- | --- |
|
||||
| `@snowluma/sdk` | `sdk-npm-publish.yml` |
|
||||
| `@snowluma/ui` | `ui-npm-publish.yml` |
|
||||
| `@snowluma/mcp` | `mcp-npm-publish.yml` |
|
||||
|
||||
The workflow job keeps the `SnowLuma` GitHub Environment, so the environment
|
||||
field must match exactly. The workflows grant `id-token: write`, use Node 24
|
||||
(which provides a recent enough npm CLI), and publish with provenance. They do
|
||||
not read `NPM_TOKEN`.
|
||||
|
||||
After all three entries are saved, rerun the failed workflow runs. Once a
|
||||
successful publish is confirmed for every package, the obsolete `NPM_TOKEN`
|
||||
environment secret can be removed from GitHub Actions settings.
|
||||
@@ -1,4 +1,5 @@
|
||||
# Run the root validation commands on every pull request.
|
||||
# Command list is duplicated in tools/ci-check.mjs — keep them identical.
|
||||
name: CI
|
||||
|
||||
on:
|
||||
@@ -38,14 +39,7 @@ jobs:
|
||||
# catalog.json the docs site consumes). Fail if the committed snapshot
|
||||
# drifted from the live specs — keeps the API docs from going stale.
|
||||
- name: Verify generated action catalog is up to date
|
||||
run: |
|
||||
catalog_status="$(git status --porcelain=v1 --untracked-files=all -- packages/mcp/src/generated)"
|
||||
if [ -n "$catalog_status" ]; then
|
||||
git diff -- packages/mcp/src/generated
|
||||
printf '%s\n' "$catalog_status"
|
||||
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
|
||||
exit 1
|
||||
fi
|
||||
run: node tools/check-action-catalog.mjs
|
||||
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -143,6 +143,9 @@ jobs:
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
- name: Verify release layout
|
||||
run: pnpm check:release-layout
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
|
||||
|
||||
@@ -22,6 +22,10 @@ on:
|
||||
description: 'Override platforms (defaults to vars.DOCKER_PLATFORMS or linux/amd64,linux/arm64)'
|
||||
required: false
|
||||
default: ''
|
||||
ghcr_image_override:
|
||||
description: 'Override GHCR image name (defaults to vars.GHCR_IMAGE, leave empty to skip GHCR)'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -42,6 +46,8 @@ jobs:
|
||||
SNOWLUMA_TAG: ${{ inputs.snowluma_tag }}
|
||||
IMAGE_OVERRIDE: ${{ inputs.docker_image_override }}
|
||||
PLATFORMS_OVERRIDE: ${{ inputs.platforms_override }}
|
||||
GHCR_IMAGE: ${{ vars.GHCR_IMAGE }}
|
||||
GHCR_OVERRIDE: ${{ inputs.ghcr_image_override }}
|
||||
with:
|
||||
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
|
||||
script: |
|
||||
@@ -59,6 +65,7 @@ jobs:
|
||||
const platforms = process.env.PLATFORMS_OVERRIDE || process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
|
||||
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
|
||||
const ref = process.env.DOCKER_REF || 'main';
|
||||
const ghcrImage = process.env.GHCR_OVERRIDE || process.env.GHCR_IMAGE || '';
|
||||
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner,
|
||||
@@ -72,7 +79,8 @@ jobs:
|
||||
platforms,
|
||||
snowluma_tag: tag,
|
||||
snowluma_repository: sourceRepo,
|
||||
ghcr_image: ghcrImage,
|
||||
},
|
||||
});
|
||||
|
||||
core.info(`Re-dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
|
||||
core.info(`Re-dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, ghcr_image=${ghcrImage}, platforms=${platforms}).`);
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Main PR target guard
|
||||
|
||||
# `main` is a pointer moved by Promote Dev to Main. Contributor and bot
|
||||
# feature work lands on dev. A PR opened against main (like the GHCR
|
||||
# fork PR) is what puts unique commits on main and fans the network graph.
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
reject:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Reject pull requests targeting main
|
||||
run: |
|
||||
echo '::error::Open this PR against dev, not main. main is updated only by Promote Dev to Main.'
|
||||
exit 1
|
||||
@@ -40,7 +40,10 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
@@ -77,21 +80,17 @@ jobs:
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
- name: Show Trusted Publishing toolchain
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
node --version
|
||||
npm --version
|
||||
|
||||
- name: Publish MCP to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/mcp
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
# Authentication is supplied by npm Trusted Publishing through the
|
||||
# GitHub OIDC token (permissions.id-token: write above).
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
@@ -106,4 +105,5 @@ jobs:
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -1,20 +1,13 @@
|
||||
name: Promote Dev to Main
|
||||
|
||||
# `dev` is the working branch. `main` is a pointer to the same history, moved
|
||||
# only by this workflow. Merge commits from dev → main are what painted the
|
||||
# GitHub network graph; this job moves the `main` ref to `dev` instead.
|
||||
on:
|
||||
push:
|
||||
branches: [dev]
|
||||
tags: ['chore.*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
auto_merge:
|
||||
description: Enable auto-merge on the resulting PR
|
||||
type: choice
|
||||
options: ['true', 'false']
|
||||
default: 'true'
|
||||
merge_method:
|
||||
description: Merge strategy when auto-merging
|
||||
type: choice
|
||||
options: ['merge', 'squash', 'rebase']
|
||||
default: 'merge'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -28,8 +21,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
run: ${{ steps.check.outputs.run }}
|
||||
auto_merge: ${{ steps.check.outputs.auto_merge }}
|
||||
merge_method: ${{ steps.check.outputs.merge_method }}
|
||||
reason: ${{ steps.check.outputs.reason }}
|
||||
steps:
|
||||
- name: Decide whether to promote
|
||||
@@ -39,32 +30,24 @@ jobs:
|
||||
REF: ${{ github.ref }}
|
||||
REF_TYPE: ${{ github.ref_type }}
|
||||
HEAD_COMMIT_MSG: ${{ github.event.head_commit.message }}
|
||||
INPUT_AUTO_MERGE: ${{ inputs.auto_merge }}
|
||||
INPUT_MERGE_METHOD: ${{ inputs.merge_method }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
run='false'
|
||||
auto_merge='true'
|
||||
merge_method='merge'
|
||||
reason=''
|
||||
|
||||
case "${EVENT_NAME}" in
|
||||
workflow_dispatch)
|
||||
run='true'
|
||||
auto_merge="${INPUT_AUTO_MERGE:-true}"
|
||||
merge_method="${INPUT_MERGE_METHOD:-merge}"
|
||||
reason='Manual workflow_dispatch'
|
||||
;;
|
||||
push)
|
||||
if [ "${REF_TYPE}" = 'tag' ]; then
|
||||
run='true'
|
||||
merge_method='merge'
|
||||
reason="Tag push: ${REF}"
|
||||
elif [ "${REF}" = 'refs/heads/dev' ]; then
|
||||
msg="${HEAD_COMMIT_MSG:-}"
|
||||
if printf '%s' "${msg}" | grep -qiE '^\[merge\]|^chore\(release\):'; then
|
||||
run='true'
|
||||
merge_method='merge'
|
||||
reason='Commit message prefix on dev ([merge] or chore(release):)'
|
||||
else
|
||||
reason='Commit on dev without [merge] / chore(release): prefix'
|
||||
@@ -80,8 +63,6 @@ jobs:
|
||||
|
||||
{
|
||||
echo "run=${run}"
|
||||
echo "auto_merge=${auto_merge}"
|
||||
echo "merge_method=${merge_method}"
|
||||
echo "reason=${reason}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
@@ -93,8 +74,6 @@ jobs:
|
||||
echo "| Event | \`${EVENT_NAME}\` |"
|
||||
echo "| Ref | \`${REF}\` |"
|
||||
echo "| Run | \`${run}\` |"
|
||||
echo "| Auto-merge | \`${auto_merge}\` |"
|
||||
echo "| Merge method | \`${merge_method}\` |"
|
||||
echo "| Reason | ${reason} |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
|
||||
@@ -123,123 +102,49 @@ jobs:
|
||||
owner: ${{ github.repository_owner }}
|
||||
repositories: ${{ github.event.repository.name }}
|
||||
|
||||
- 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 "id=${bot_id}"
|
||||
echo "email=${bot_email}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
echo "Resolved bot: ${bot_login} <${bot_email}>"
|
||||
|
||||
- name: Checkout main
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
ref: dev
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
|
||||
- name: Compare dev to main
|
||||
id: diff
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch origin dev:dev
|
||||
ahead="$(git rev-list --count main..dev)"
|
||||
behind="$(git rev-list --count dev..main)"
|
||||
dev_sha="$(git rev-parse dev)"
|
||||
dev_short="$(git rev-parse --short dev)"
|
||||
{
|
||||
echo "ahead=${ahead}"
|
||||
echo "behind=${behind}"
|
||||
echo "dev_sha=${dev_sha}"
|
||||
echo "dev_short=${dev_short}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
if [ "${ahead}" = '0' ]; then
|
||||
echo "skip=true" >> "${GITHUB_OUTPUT}"
|
||||
echo "::notice::dev has no commits ahead of main; nothing to promote."
|
||||
else
|
||||
echo "skip=false" >> "${GITHUB_OUTPUT}"
|
||||
echo "dev is ${ahead} ahead, ${behind} behind main."
|
||||
fi
|
||||
|
||||
- name: Ensure automation label exists
|
||||
if: steps.diff.outputs.skip != 'true'
|
||||
- name: Point main at dev
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
run: |
|
||||
gh label create automation --color 0E8A16 --description 'Automated bot PRs' 2>/dev/null || true
|
||||
|
||||
- name: Create or update Pull Request
|
||||
id: pr
|
||||
if: steps.diff.outputs.skip != 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
DEV_SHA: ${{ steps.diff.outputs.dev_sha }}
|
||||
DEV_SHORT: ${{ steps.diff.outputs.dev_short }}
|
||||
AHEAD: ${{ steps.diff.outputs.ahead }}
|
||||
BEHIND: ${{ steps.diff.outputs.behind }}
|
||||
REASON: ${{ needs.decide.outputs.reason }}
|
||||
REF: ${{ github.ref }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
title="chore: promote dev → main (${DEV_SHORT})"
|
||||
git fetch origin dev main
|
||||
dev_sha="$(git rev-parse origin/dev)"
|
||||
main_sha="$(git rev-parse origin/main)"
|
||||
dev_short="$(git rev-parse --short origin/dev)"
|
||||
main_short="$(git rev-parse --short origin/main)"
|
||||
|
||||
if [ "${dev_sha}" = "${main_sha}" ]; then
|
||||
echo "::notice::main already equals dev @ ${dev_short}; nothing to promote."
|
||||
{
|
||||
echo "main already equals dev @ ${dev_short}"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
unique="$(git cherry origin/dev origin/main | awk '/^\+/ { print $2 }' || true)"
|
||||
if [ -n "${unique}" ]; then
|
||||
echo '::error::main has unique commits that dev does not. Cherry-pick them onto dev first.' >&2
|
||||
git log --oneline --no-walk ${unique}
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git push --force-with-lease="refs/heads/main:${main_sha}" origin "origin/dev:refs/heads/main"
|
||||
echo "::notice::Updated main ${main_short} → dev@${dev_short}"
|
||||
{
|
||||
echo "Automated promotion of \`dev\` into \`main\`."
|
||||
echo "## Promote"
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Source | \`dev\` @ \`${DEV_SHA}\` |"
|
||||
echo "| Trigger ref | \`${REF}\` |"
|
||||
echo "| Trigger reason | ${REASON} |"
|
||||
echo "| \`main\` was | \`${main_sha}\` |"
|
||||
echo "| \`main\` now | \`dev\` @ \`${dev_sha}\` |"
|
||||
echo "| Reason | ${REASON} |"
|
||||
echo "| Workflow run | ${RUN_URL} |"
|
||||
echo "| Ahead / Behind | ${AHEAD} / ${BEHIND} |"
|
||||
echo
|
||||
echo "Created by SnowLuma Bot."
|
||||
} > pr-body.md
|
||||
|
||||
existing="$(gh pr list --base main --head dev --state open --json number --jq '.[0].number' 2>/dev/null || true)"
|
||||
if [ -n "${existing}" ]; then
|
||||
gh pr edit "${existing}" --title "${title}" --body-file pr-body.md
|
||||
pr_number="${existing}"
|
||||
echo "Updated existing PR #${pr_number}"
|
||||
else
|
||||
url="$(gh pr create --base main --head dev --title "${title}" --body-file pr-body.md --label automation)"
|
||||
pr_number="${url##*/}"
|
||||
echo "Opened new PR #${pr_number} (${url})"
|
||||
fi
|
||||
|
||||
echo "number=${pr_number}" >> "${GITHUB_OUTPUT}"
|
||||
{
|
||||
echo "## Promote PR"
|
||||
echo
|
||||
echo "- Number: #${pr_number}"
|
||||
echo "- Source: \`dev@${DEV_SHORT}\`"
|
||||
echo "- Ahead/Behind: ${AHEAD}/${BEHIND}"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
|
||||
- name: Enable auto-merge
|
||||
if: steps.diff.outputs.skip != 'true' && needs.decide.outputs.auto_merge == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
PR_NUMBER: ${{ steps.pr.outputs.number }}
|
||||
MERGE_METHOD: ${{ needs.decide.outputs.merge_method }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
method_flag='--merge'
|
||||
case "${MERGE_METHOD}" in
|
||||
squash) method_flag='--squash' ;;
|
||||
rebase) method_flag='--rebase' ;;
|
||||
*) method_flag='--merge' ;;
|
||||
esac
|
||||
gh pr merge "${PR_NUMBER}" --auto ${method_flag}
|
||||
echo "::notice::Auto-merge enabled on PR #${PR_NUMBER} with strategy: ${MERGE_METHOD}"
|
||||
@@ -37,14 +37,7 @@ jobs:
|
||||
run: pnpm typecheck
|
||||
|
||||
- name: Verify generated action catalog is up to date
|
||||
run: |
|
||||
catalog_status="$(git status --porcelain=v1 --untracked-files=all -- packages/mcp/src/generated)"
|
||||
if [ -n "$catalog_status" ]; then
|
||||
git diff -- packages/mcp/src/generated
|
||||
printf '%s\n' "$catalog_status"
|
||||
echo '::error::Generated action catalog is stale. Run `pnpm --filter @snowluma/mcp gen` and commit packages/mcp/src/generated/.' >&2
|
||||
exit 1
|
||||
fi
|
||||
run: node tools/check-action-catalog.mjs
|
||||
|
||||
build:
|
||||
needs: preflight
|
||||
@@ -96,6 +89,9 @@ jobs:
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
- name: Verify release layout
|
||||
run: pnpm check:release-layout
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+)
|
||||
@@ -221,6 +217,7 @@ jobs:
|
||||
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
|
||||
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
|
||||
DOCKER_REF: ${{ vars.DOCKER_REF }}
|
||||
GHCR_IMAGE: ${{ vars.GHCR_IMAGE }}
|
||||
with:
|
||||
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
|
||||
script: |
|
||||
@@ -236,6 +233,7 @@ jobs:
|
||||
const platforms = process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
|
||||
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
|
||||
const ref = process.env.DOCKER_REF || 'main';
|
||||
const ghcrImage = process.env.GHCR_IMAGE || '';
|
||||
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner,
|
||||
@@ -249,7 +247,8 @@ jobs:
|
||||
platforms,
|
||||
snowluma_tag: tag,
|
||||
snowluma_repository: sourceRepo,
|
||||
ghcr_image: ghcrImage,
|
||||
},
|
||||
});
|
||||
|
||||
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
|
||||
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, ghcr_image=${ghcrImage}, platforms=${platforms}).`);
|
||||
@@ -37,7 +37,10 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
@@ -74,21 +77,17 @@ jobs:
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
- name: Show Trusted Publishing toolchain
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
node --version
|
||||
npm --version
|
||||
|
||||
- name: Publish SDK to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/sdk
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
# Authentication is supplied by npm Trusted Publishing through the
|
||||
# GitHub OIDC token (permissions.id-token: write above).
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
@@ -103,4 +102,5 @@ jobs:
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -37,7 +37,10 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
# Trusted Publishing requires Node >=22.14 and npm >=11.5.1.
|
||||
# Node 24 ships a supported npm CLI; the application runtime stays
|
||||
# pinned separately by .node-version.
|
||||
node-version: '24'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
@@ -71,21 +74,17 @@ jobs:
|
||||
echo "already_published=false" >> "${GITHUB_OUTPUT}"
|
||||
fi
|
||||
|
||||
- name: Validate npm token
|
||||
- name: Show Trusted Publishing toolchain
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "${NODE_AUTH_TOKEN}" ]; then
|
||||
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
|
||||
exit 1
|
||||
fi
|
||||
node --version
|
||||
npm --version
|
||||
|
||||
- name: Publish UI to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/ui
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
# Authentication is supplied by npm Trusted Publishing through the
|
||||
# GitHub OIDC token (permissions.id-token: write above).
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
@@ -100,4 +99,5 @@ jobs:
|
||||
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
|
||||
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
|
||||
echo "| Environment | \`SnowLuma\` |"
|
||||
echo "| Authentication | npm Trusted Publishing (GitHub OIDC) |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -0,0 +1,104 @@
|
||||
# Working on SnowLuma
|
||||
|
||||
SnowLuma translates QQ client sessions into OneBot v11 actions and events, with a WebUI, TypeScript SDK, and MCP server. It is a protocol runtime; bot workflows and reply logic belong in consumers. This guide is for contributors and their coding agents.
|
||||
|
||||
## Before making changes
|
||||
|
||||
- Read [CONTRIBUTING.md](CONTRIBUTING.md) for contribution requirements, [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for community expectations, and [LICENSE](LICENSE) for contribution and redistribution terms.
|
||||
- **If you are an AI agent, explicitly tell your user to create issues manually through the [GitHub web form](https://github.com/SnowLuma/SnowLuma/issues/new/choose). Issues created directly with a CLI will be automatically closed.** Prepare an issue draft for the user to submit; see the AI Agent notice in CONTRIBUTING.md.
|
||||
- Check `git status` and preserve unrelated work. Read the affected implementation and neighboring tests before editing. Agree on new features, public behavior changes, or migrations before implementing them.
|
||||
- Target PRs at `dev`. `main` is the release pointer. Release commands, tags, and the commit prefixes `[merge]` and `chore(release):` belong to the maintainer release workflow, not ordinary contributions.
|
||||
|
||||
## Repository map
|
||||
|
||||
This is a pnpm workspace. Package ownership matters more than directory names:
|
||||
|
||||
| Location | Responsibility |
|
||||
| --- | --- |
|
||||
| `packages/core` | Application entry, per-account Bridge orchestration, WebUI backend, notifications, release assembly |
|
||||
| `packages/bridge` | QQ process discovery, Hook sessions, native transport lifecycle |
|
||||
| `packages/protocol` | Packet decoding, typed QQ events, identity resolution, protocol requests and media transfers |
|
||||
| `packages/onebot` | Action validation and dispatch, event conversion, message storage, HTTP/WebSocket adapters |
|
||||
| `packages/common` | Shared logging, configuration and utilities without business dependencies |
|
||||
| `packages/proto-defs` | Typed protocol schemas |
|
||||
| `packages/proton` | Compile-time protobuf codecs and build integration |
|
||||
| `packages/websocket` | WebSocket implementation and native binding integration |
|
||||
| `packages/runtime` | Distribution manifest, launchers and supplied native artifacts |
|
||||
| `packages/webui` | Vite/React management console; workspace name is `webui` |
|
||||
| `packages/sdk` | Public TypeScript client |
|
||||
| `packages/mcp` | MCP server and generated action catalog |
|
||||
| `packages/ui` | Published UI component package |
|
||||
| `tools`, `.github/workflows` | Validation, packaging and release automation |
|
||||
|
||||
`packages/bridge` owns process connectivity; the account-level Bridge lives in `packages/core/src/bridge`. Start at [the application entry](packages/core/src/index.ts) to follow their composition.
|
||||
|
||||
Read the relevant owner before changing a path:
|
||||
|
||||
| Change | Start here |
|
||||
| --- | --- |
|
||||
| Connection or account lifecycle | [Hook manager](packages/bridge/src/hook-manager.ts), [Bridge manager](packages/core/src/bridge/manager.ts), [OneBot instance](packages/onebot/src/instance.ts) |
|
||||
| Incoming QQ events or identity | [Packet pipeline](packages/protocol/src/packet-pipeline.ts), [message decoders](packages/protocol/src/msg-push/index.ts), [identity service](packages/protocol/src/identity-service.ts) |
|
||||
| OneBot actions or message segments | [Action definitions](packages/onebot/src/actions/index.ts), [validation helpers](packages/onebot/src/action-kit.ts), [event conversion](packages/onebot/src/event-converter/index.ts) |
|
||||
| WebUI | [Interaction conventions](packages/webui/README.md), `packages/webui/src`, `packages/core/src/webui` |
|
||||
| SDK or MCP | [SDK guide](packages/sdk/README.md), [SDK versioning](packages/sdk/VERSIONING.md), [MCP guide](packages/mcp/README.md) |
|
||||
| Protocol codec generation | [Proton guide](packages/proton/README.md), the affected package's `vitest.config.ts` |
|
||||
|
||||
## Setup and validation
|
||||
|
||||
Use the Node version in [.node-version](.node-version) and the pnpm version in [package.json](package.json). Install with `pnpm install --frozen-lockfile`; keep the existing lockfile unless changing dependencies.
|
||||
|
||||
Run commands from the repository root:
|
||||
|
||||
```sh
|
||||
pnpm typecheck # all workspace packages with a typecheck script
|
||||
pnpm lint
|
||||
pnpm test # all workspace packages with a test script
|
||||
pnpm run build:all # release inputs and published packages
|
||||
pnpm test:core # Core only; not a substitute for workspace tests
|
||||
pnpm --filter @snowluma/onebot test # example: tests for the affected package
|
||||
pnpm --filter webui test # the frontend package has no @snowluma/ prefix
|
||||
```
|
||||
|
||||
Use focused tests while iterating. Before handing off a code change, run the full checks required by CONTRIBUTING.md and report anything that could not run. [PR CI](.github/workflows/ci.yml) is the reference; `pnpm run ci` reproduces its commands locally, including dependency installation and the generated-catalog check.
|
||||
|
||||
- **Documentation-only changes:** verify links, paths, commands and `git diff --check`; runtime tests do not validate prose.
|
||||
- **Shared types or actions:** run workspace typechecking as well as behavior tests. A passing Vitest run does not prove type correctness.
|
||||
- **Protocol codecs:** keep the existing Proton integration in tests so they exercise the same transformations as production. Import real implementations; do not duplicate the algorithm in the test.
|
||||
- **Native coverage:** `pnpm test:native` is separate from default protocol tests and requires compatible native artifacts. A missing artifact or unavailable target is a reported limitation, not permission to bypass the check.
|
||||
- **Live QQ behavior:** fixture tests and a successful API response do not prove delivery or client rendering. State what was tested locally and what still needs a real client.
|
||||
|
||||
`pnpm dev` starts Core and can attach to local QQ processes; use it only when runtime testing is intended. `pnpm dev:web` starts the frontend, which expects a WebUI backend. Follow the existing test fakes for isolated work rather than starting a live account unnecessarily.
|
||||
|
||||
## Implementation rules
|
||||
|
||||
- **Fix the cause.** Reproduce failures at the owning layer and add a regression test for the observable behavior. Avoid account-, filename-, or example-specific patches.
|
||||
- **Make errors observable.** Do not turn exceptions into empty results or successful responses. Preserve error context and use the shared logger for important transitions and failures. If evidence is insufficient, add targeted diagnostics and describe what remains unknown.
|
||||
- **Preserve account isolation.** Identity, message storage and session state belong to their account. Keep teardown ordering and in-flight work handling intact when changing lifecycle code.
|
||||
- **Keep parsing separate from effects.** QQ decoders and OneBot event converters translate data. Live state updates belong to their owning pipeline or service; reading history must not mutate live membership or pending requests.
|
||||
- **Use the declared interfaces.** OneBot consumes the [Bridge interface](packages/core/src/bridge/bridge-interface.ts). Reuse package exports and existing dependency injection instead of reaching into another owner's state or building a second registry.
|
||||
- **Validate at inputs.** Use the existing action field and cross-field validation helpers. Preserve accepted input forms, response fields and error behavior unless the change explicitly calls for new semantics. Do not silently discard invalid outbound message content.
|
||||
- **Protect persisted data.** Message history and media metadata are durable records. Do not add automatic deletion or treat them as disposable caches. Migration changes need failure and restart coverage; keep failures visible.
|
||||
- **Preserve transport policy.** Retain configured bind addresses and access checks. TLS startup failure must not silently downgrade to HTTP. Distinguish saved configuration from changes actually applied to a running adapter.
|
||||
- **Keep types and ownership clear.** Follow the strict TypeScript configuration, existing import style and two-space indentation. Validate unknown external data instead of hiding mismatches with casts or fallback values. Keep comments about reasons and non-obvious behavior.
|
||||
- **Keep diagnostics safe.** Use existing sanitization when recording external input. Credentials, private keys, private account data and unredacted captures do not belong in commits, fixtures or public reports.
|
||||
|
||||
## Generated files and related changes
|
||||
|
||||
OneBot action definitions own validation and catalog metadata. After changing an action name, parameter, result description or execution mode:
|
||||
|
||||
1. Update the owning definition in `packages/onebot/src/actions` and its tests.
|
||||
2. Run `pnpm --filter @snowluma/mcp gen`.
|
||||
3. Inspect and include the corresponding changes in `packages/mcp/src/generated/catalog.ts` and `catalog.json`. Do not hand-edit generated catalog entries.
|
||||
4. Check affected SDK types and callers, run their relevant tests, and run workspace typechecking.
|
||||
|
||||
`pnpm test` also runs the MCP catalog generator and may change these tracked snapshots. CI's `node tools/check-action-catalog.mjs` rejects a working-tree catalog diff; it is a clean-checkout drift check, not the generator itself.
|
||||
|
||||
SDK breaking changes also update [CHANGELOG.md](packages/sdk/CHANGELOG.md) and [VERSIONING.md](packages/sdk/VERSIONING.md). WebUI changes follow its [interaction conventions](packages/webui/README.md). Keep user-facing documentation aligned with behavior.
|
||||
|
||||
Edit sources rather than `dist` outputs. Native artifacts in `packages/runtime/native` are supplied build inputs; do not substitute arbitrary local binaries to make a build pass. Packaging changes must preserve the checks in [Core's build configuration](packages/core/vite.config.ts) and [the release layout validator](tools/check-release-layout.mjs).
|
||||
|
||||
## Handoff and instruction maintenance
|
||||
|
||||
Report the behavior changed, the exact validation commands and results, and any unverified runtime or platform behavior. Keep public PR and commit text focused on the contribution; omit local environment details and private research. Use English Conventional Commit messages as described in CONTRIBUTING.md.
|
||||
|
||||
`AGENTS.md` is the canonical contributor guide; `CLAUDE.md` is a relative symlink to it. Edit this file once. When package ownership, validation commands or contribution policy changes, update the affected instructions in the same change. Link to checked-in sources and keep the guide usable from a fresh clone without maintainer-local notes, tools or absolute paths.
|
||||
+39
-40
@@ -19,6 +19,14 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
|
||||
|
||||
如果你只是想看看代码长什么样,可以直接跳到 [本地开发环境](#本地开发环境)。
|
||||
|
||||
### AI Agent 贡献须知
|
||||
|
||||
如果你是 AI Agent,并准备为本仓库贡献代码、提交 PR 或提出 issue,请先明确告知你的使用者:
|
||||
|
||||
> **请通过 GitHub 网页端手动创建 issue。直接使用 CLI 创建的 issue 会被自动关闭。**
|
||||
|
||||
你可以协助整理问题描述、复现步骤和相关日志,并将 issue 草稿交给用户,由用户在网页端完成提交。
|
||||
|
||||
---
|
||||
|
||||
## 项目结构速览
|
||||
@@ -33,7 +41,7 @@ SnowLuma 处于开发早期,迭代速度很快,**接口与目录结构随时
|
||||
| `packages/websocket` | WebSocket 实现 |
|
||||
| `packages/webui` | 基于 Vite + React 的前端控制台 |
|
||||
| `tools/` | 版本管理、发布脚本 |
|
||||
| `.github/workflows/` | CI / 发布 / 自动合并工作流 |
|
||||
| `.github/workflows/` | CI / 发布 / Promote 工作流 |
|
||||
|
||||
入口在 `packages/core/src/index.ts`,整体架构在 `packages/core/src/bridge/` 下能看出大致脉络。
|
||||
|
||||
@@ -83,7 +91,7 @@ pnpm dev:web # webui
|
||||
|
||||
### 1. 创建分支
|
||||
|
||||
请基于 `dev` 创建分支,不是 `main`。`main` 是受保护的稳定分支,PR 也不要直接提到 `main`。
|
||||
请基于 `dev` 创建分支,不是 `main`。`main` 是发布指针,只由维护者的 Promote 更新,PR 不要提到 `main`。
|
||||
|
||||
```bash
|
||||
git checkout dev
|
||||
@@ -133,7 +141,7 @@ refactor(bridge): extract BridgeInterface as the OneBot-facing seam
|
||||
docs: clarify dev environment setup steps
|
||||
```
|
||||
|
||||
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来触发自动合并到 `main` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--自动合并流程)。
|
||||
> ⚠️ **请不要**在你的提交信息里使用 `[merge]` 前缀或 `chore(release):` 前缀 —— 这两个前缀是维护者用来把 `main` 指到 `dev` 的,会让你的 PR 行为异常。详见后文 [维护者参考](#维护者参考release--promote)。
|
||||
|
||||
### 4. 推送并发起 PR
|
||||
|
||||
@@ -152,7 +160,7 @@ git push origin fix/onebot-mention-encoding
|
||||
|
||||
- 维护者会在能腾出时间时来 review。如果一周内没有任何回应,欢迎在 PR 里 @ 一下,或者去社群里提醒。
|
||||
- review 意见请尽量在同一个 PR 内修改,避免反复关闭重开。
|
||||
- 合并方式由维护者决定,通常是 squash merge 到 `dev`。**`main` 由维护者通过自动化工作流统一从 `dev` 合入**,你不需要操心 `main`。
|
||||
- 合并方式由维护者决定,通常是 squash merge 到 `dev`。**`main` 由维护者通过 Promote 指到当时的 `dev`**,你不需要操心 `main`。
|
||||
|
||||
---
|
||||
|
||||
@@ -191,28 +199,30 @@ git push origin fix/onebot-mention-encoding
|
||||
|
||||
---
|
||||
|
||||
## 维护者参考:release & 自动合并流程
|
||||
## 维护者参考:release & Promote
|
||||
|
||||
> 以下内容主要写给具备 `main` 推送 / 发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
|
||||
> 以下内容主要写给具备发版权限的维护者。普通贡献者只需要把 PR 提到 `dev`,不需要关心这一节。
|
||||
|
||||
### 分支模型
|
||||
|
||||
SnowLuma 使用 **`main` + `dev`** 双分支模型:
|
||||
|
||||
- **`main`** — 受保护的稳定分支,仅接收来自 `dev` 的合并 PR。**禁止直接 push**。
|
||||
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先合入 `dev`。
|
||||
- **`dev`** — 日常开发分支。所有功能、修复、文档变更都先进入 `dev`。
|
||||
- **`main`** — 发布指针,应与某次 Promote 当时的 `dev` 尖端是**同一个提交**。不要直接 push,也不要往 `main` 开 PR(CI 会拒)。
|
||||
- **`native/auto-update-*`** — 由 `SnowLuma Bot` 自动创建的原生产物更新分支(来自 `SnowLumaNative`,不需要手动维护)。
|
||||
|
||||
### 把 `dev` 合并到 `main`
|
||||
### 把 `main` 指到 `dev`
|
||||
|
||||
工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。无论用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
|
||||
工作流 `.github/workflows/promote-dev-to-main.yml` 以 `SnowLuma Bot` 身份把 `main` 指到当前 `dev` 尖端,**不再开 merge PR**。`main` 上若有 `dev` 还没有的独有改动,Promote 会失败,需要先把那些改动收回 `dev`。
|
||||
|
||||
推到 `dev` 仍会跑 `dev-build.yml`。Promote **不等**那组检查;发版请用下面的 `pnpm release`,它会在本地先跑完整 CI。
|
||||
|
||||
#### 1. 提交信息前缀(推荐日常使用)
|
||||
|
||||
向 `dev` push 一个提交,提交信息**以**以下任一前缀**开头**即触发(不区分大小写):
|
||||
|
||||
- `[merge]` — 例如 `[merge] fix: hotfix for OneBot mention`
|
||||
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯
|
||||
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯。**只许用在真正的版本 bump**,不要写进普通 CI / 工具提交。
|
||||
|
||||
> 是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
|
||||
|
||||
@@ -220,38 +230,22 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
|
||||
|
||||
任何符合 `chore.*` 的 tag(如 `chore.merge-20240509`、`chore.promote-v1.7.0`)被推送时也会触发:
|
||||
|
||||
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(开 PR,自动合并)
|
||||
- `chore.*` → 仅触发 `promote-dev-to-main.yml`(把 `main` 指到 `dev`)
|
||||
- `v*` → 仅触发 `release.yml`(构建发布产物)
|
||||
|
||||
推荐流程:先用 `chore.*` tag 把 `dev` 合入 `main`,待合并完成后再在 `main` 上打 `v*` tag 触发发布。这样 `release.yml` 始终基于已过完所有检查的 `main` HEAD 构建。
|
||||
推荐流程:用 `pnpm release`(或先 Promote,再确认 `origin/main` 已等于 `dev` 尖端)之后,在 `main` 上打 `v*` tag。这样 `release.yml` 始终基于当时的 `main` HEAD 构建。
|
||||
|
||||
#### 3. 手动触发
|
||||
|
||||
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。可选输入:
|
||||
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。没有 merge 策略选项;跑起来就是一次指针更新。
|
||||
|
||||
- `auto_merge`:是否启用 auto-merge(默认 `true`)。
|
||||
- `merge_method`:`merge` / `squash` / `rebase`(默认 `merge`)。
|
||||
### 不要给 `main` 套「必须走 PR」
|
||||
|
||||
### 启用 `main` 分支保护(必做)
|
||||
Promote 不通过 PR 更新 `main`。如果给 `main` 打开 **Require a pull request before merging** 或禁止更新引用,Promote 会失效。
|
||||
|
||||
仓库管理员需要在 GitHub 上为 `main` 配置规则集(Repository Rules)或经典分支保护,至少满足:
|
||||
可以限制删除 `main`。外来 PR 必须打 `dev`;打到 `main` 的 PR 会被 `main-pr-target-guard.yml` 拒绝。
|
||||
|
||||
1. **Settings → Rules → Rulesets**(推荐)或 **Settings → Branches → Branch protection rules**。
|
||||
2. 选择 `main` 作为目标分支。
|
||||
3. 勾选:
|
||||
- **Restrict deletions** — 禁止删除 `main`。
|
||||
- **Require a pull request before merging** — 所有合并必须走 PR。
|
||||
- **Block force pushes** — 禁止强推。
|
||||
- **Require status checks to pass before merging(必勾)** — 把以下来自 `dev-build.yml` 的 check 全部加为 required:
|
||||
- `typecheck`
|
||||
- `build (win-x64)`
|
||||
- `build (linux-x64)`
|
||||
- `build (linux-arm64)`
|
||||
- **Require branches to be up to date before merging** — 保证 PR 合并前已 rebase 过最新 `main`。
|
||||
4. 在 **Bypass list / Allow specified actors to bypass** 中加入 `SnowLuma Bot` GitHub App。这样 `gh pr merge --auto` 才能在所有 required check 通过后由机器人自动完成合并;否则 PR 会一直卡在 auto-merge 等待人工 review。
|
||||
5. **不要**把任何用户加入 push 白名单,确保「禁止向 `main` 直接提交」的约束生效。第一次设置完后,连仓库管理员也只能通过 PR 改 `main`。
|
||||
|
||||
效果:任何对 `dev` 的推送都会先在 `dev-build.yml` 上跑 typecheck + 三个架构的 build;只有全部成功,promote 工作流的 `--auto` 合并才会真正发生。失败时 PR 会保留在 open 状态,修复后再次推到 `dev` 即可重新触发检查。
|
||||
本地若已经 checkout 过旧的 `main`,Promote 之后可能无法快进,对齐 `origin/main` 即可。
|
||||
|
||||
### 必需的 Secrets
|
||||
|
||||
@@ -260,25 +254,30 @@ SnowLuma 使用 **`main` + `dev`** 双分支模型:
|
||||
- `SNOWLUMA_BOT_APP_ID` — 数字类型的 App ID。
|
||||
- `SNOWLUMA_BOT_PRIVATE_KEY` — 该 App 的 PEM 私钥。
|
||||
|
||||
App 必须在本仓库已安装,且授予 **Contents: Read+Write**、**Pull requests: Read+Write**。
|
||||
App 必须在本仓库已安装,且授予 **Contents: Read+Write**。
|
||||
|
||||
### 本地工作流速查(维护者)
|
||||
|
||||
```bash
|
||||
# 把 dev 合入 main(三选一)
|
||||
# 推荐:一条命令走完 bump → Promote → 等 main 跟上 → 打 v* tag
|
||||
pnpm release 1.7.0
|
||||
|
||||
# 只要把 main 指到 dev(三选一)
|
||||
|
||||
# 方式 A:commit-msg 前缀
|
||||
git commit -m "chore(release): v1.7.0" # 或 "[merge] fix: hotfix"
|
||||
git push # → 触发 promote-dev-to-main
|
||||
|
||||
# 方式 B:chore.* 合并 tag(与发布 tag 解耦)
|
||||
git tag chore.merge-20240509 # 或 chore.promote-v1.7.0 等
|
||||
# 方式 B:chore.* tag(与发布 tag 解耦)
|
||||
git tag chore.merge-20240509
|
||||
git push origin chore.merge-20240509 # → 触发 promote-dev-to-main
|
||||
|
||||
# 方式 C:在 Actions 页面手动 Run workflow
|
||||
|
||||
# 合并完成后,发布版本(在 main 上打 v* tag)
|
||||
git checkout main && git pull
|
||||
# Promote 完成后,若要自己打发布 tag
|
||||
git fetch origin
|
||||
git switch main
|
||||
git merge --ff-only origin/main # 对不齐就 reset 到 origin/main
|
||||
git tag v1.7.0
|
||||
git push origin v1.7.0 # → 仅触发 release.yml
|
||||
```
|
||||
|
||||
@@ -12,19 +12,26 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="#快速开始">快速开始</a> ·
|
||||
<a href="#运行链路">运行链路</a> ·
|
||||
<a href="./docs/onebot-actions.md">动作参考</a> ·
|
||||
<a href="./packages/sdk/README.md">SDK</a> ·
|
||||
<a href="./packages/mcp/README.md">MCP</a> ·
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/issues">问题反馈</a>
|
||||
</p>
|
||||
|
||||
SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时。它把 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,并通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口;每个账号拥有独立会话,适合机器人开发、自动化与协议研究。
|
||||
SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,并通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口。
|
||||
|
||||
> [!CAUTION]
|
||||
> **使用边界**:SnowLuma 是独立的第三方互操作项目,**与腾讯 / QQ 无任何隶属或授权关系**。本项目仅供学习与技术研究,请遵守《QQ 用户协议》及适用法律;软件按“现状”提供、不附带任何担保,使用风险自负。详见 [`EULA.md`](EULA.md)。
|
||||
> SnowLuma 是独立的第三方项目,与腾讯 / QQ 无隶属或授权关系。项目仅供学习与技术研究,请遵守《QQ 用户协议》及适用法律;软件按“现状”提供,使用风险自负。详见 [`EULA.md`](EULA.md)。
|
||||
>
|
||||
> **Disclaimer**: SnowLuma is an independent third-party interoperability project with no affiliation with or endorsement by Tencent / QQ. It is provided for study and research only, “as is” and without warranty. See [`EULA.md`](EULA.md).
|
||||
> **Disclaimer:** SnowLuma is independent of Tencent / QQ and is provided for study and research only, “as is” and without warranty.
|
||||
|
||||
## 核心能力
|
||||
|
||||
| 场景 | 能力 |
|
||||
| --- | --- |
|
||||
| OneBot 接入 | OneBot v11 动作与事件;WebSocket 服务端 / 客户端及 HTTP 服务端 / 上报 |
|
||||
| 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及常见卡片 |
|
||||
| 多账号运行 | 各账号独立维护会话、身份映射、消息存储和网络配置 |
|
||||
| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试和存储管理 |
|
||||
| 开发者工具 | [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) |
|
||||
|
||||
## 运行链路
|
||||
|
||||
@@ -32,94 +39,33 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时。它把 QQ 原
|
||||
<img src="./assets/readme/runtime-map.svg" width="100%" alt="QQ 会话经过协议桥接与 OneBot 标准化后连接到 WebSocket、HTTP、WebUI、SDK 和 MCP" />
|
||||
</p>
|
||||
|
||||
SnowLuma 将会话接入、协议解析、身份映射、OneBot 转换和网络适配拆成清晰边界。多个 QQ 账号可以并行运行,同时保持独立状态、日志与连接配置。
|
||||
|
||||
## 核心能力
|
||||
|
||||
| 场景 | SnowLuma 提供 |
|
||||
| --- | --- |
|
||||
| OneBot 接入 | OneBot v11 动作与事件,支持 WebSocket 服务端 / 客户端、HTTP 服务端 / 上报及同端口复用 |
|
||||
| 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及 JSON / XML 卡片等常见消息元素 |
|
||||
| 多账号运行 | 每个 QQ 账号独立维护会话、身份映射、消息存储与网络适配器 |
|
||||
| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试、存储管理、密码管理与可定制总览 |
|
||||
| 开发者工具 | 提供 [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) |
|
||||
| 可观察错误 | 关键解析与执行失败会留下明确上下文,不以静默丢弃掩盖问题 |
|
||||
会话接入、协议解析、身份映射、OneBot 转换和网络适配保持独立边界;多个 QQ 账号可并行运行。
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 选择发行包
|
||||
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载对应平台的完整发行包并解压。Lite 版需 Node.js 22.13+(23 系需 23.4+)。
|
||||
2. Windows 运行 `launcher.bat`;Linux 执行:
|
||||
|
||||
前往 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载与你的平台匹配的版本:
|
||||
```bash
|
||||
chmod +x launcher.sh
|
||||
./launcher.sh
|
||||
```
|
||||
|
||||
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 22.13+;23 系需 23.4+) |
|
||||
| --- | --- | --- |
|
||||
| Windows x64 | `SnowLuma-vX.Y.Z-win-x64.zip` | `SnowLuma-vX.Y.Z-win-x64-lite.zip` |
|
||||
| Linux x64 | `SnowLuma-vX.Y.Z-linux-x64.tar.gz` | `SnowLuma-vX.Y.Z-linux-x64-lite.tar.gz` |
|
||||
| Linux arm64 | `SnowLuma-vX.Y.Z-linux-arm64.tar.gz` | `SnowLuma-vX.Y.Z-linux-arm64-lite.tar.gz` |
|
||||
3. 打开 [`http://localhost:5099`](http://localhost:5099),使用启动日志中的初始密码登录 WebUI,按引导接入 QQ 进程并配置 OneBot 连接。
|
||||
|
||||
完整版适合直接解压运行;Lite 版只移除了内置 Node.js,其余运行时依赖与 WebUI 静态资源保持一致。
|
||||
## 接入与文档
|
||||
|
||||
### 2. 启动 SnowLuma
|
||||
| 入口 | 文档 |
|
||||
| --- | --- |
|
||||
| WebSocket / HTTP | [OneBot 动作参考](docs/onebot-actions.md) |
|
||||
| TypeScript SDK | [`packages/sdk/README.md`](packages/sdk/README.md) |
|
||||
| MCP | [`packages/mcp/README.md`](packages/mcp/README.md) |
|
||||
|
||||
Windows 运行 `launcher.bat`。Linux 在解压目录执行:
|
||||
JSON 消息段接受标准的 `data.data` 字符串,也兼容 `data.data` 非数组对象和 `{ type: "json", data: "..." }` 简写;`data` 必填,最终内容必须是 JSON 对象。
|
||||
|
||||
```bash
|
||||
chmod +x launcher.sh
|
||||
./launcher.sh
|
||||
```
|
||||
## 开发
|
||||
|
||||
### 3. 打开 WebUI
|
||||
|
||||
浏览器访问 [`http://localhost:5099`](http://localhost:5099)。初始账号为 `admin`,随机密码会显示在启动日志中;首次登录后,WebUI 会在同一个引导流程中完成协议确认与访问密码设置,随后即可接入已启动的 QQ 进程并配置 OneBot 连接。
|
||||
|
||||
<details>
|
||||
<summary><strong>无人值守部署:通过环境变量确认协议</strong></summary>
|
||||
|
||||
同时设置以下两个变量可跳过 WebUI 首次使用引导中的协议确认步骤:
|
||||
|
||||
```bash
|
||||
SNOWLUMA_ACCEPT_EULA=1
|
||||
SNOWLUMA_ACCEPT_PRIVACY=1
|
||||
```
|
||||
|
||||
两项必须同时设置,且环境变量确认不会写入持久化同意记录。设置变量即表示运营者已阅读并同意 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md)。
|
||||
|
||||
全新无人值守部署还可以使用 `SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD` 预设 WebUI 密码(至少 8 位);由该变量初始化的密码不再要求进入强制修改步骤。已有 `config/webui.json` 时仍以现有凭据为准。
|
||||
|
||||
</details>
|
||||
|
||||
## 可选:登录时补齐云端历史
|
||||
|
||||
WebUI 的账号“通用设置”可开启登录历史补齐,默认关闭,并在下次登录或重启后生效。该功能只把缺失的 QQ 云端漫游消息静默写入 SnowLuma 本地历史库,不重放 OneBot 事件,也不改变 QQ 已读状态。
|
||||
|
||||
花名册预热完成后会等待 30 秒,且进程内一次只为一个账号执行自动补齐。每次登录最多扫描 100 个群和 100 位好友,优先续补本地已知缺口,每类最多处理 3 个会话;每个会话最多读取 20 条消息,自动请求之间至少间隔 2 秒,失败后本次登录不重试。
|
||||
|
||||
## 日志与存储管理
|
||||
|
||||
WebUI 的“系统设置 → 存储管理”可查看受管数据占用、调整日志策略,并清理日志、非活动传输临时文件或离线账号的消息、媒体和表情回应数据库。清理范围固定,不包含配置、凭据或其他文件。
|
||||
|
||||
| 设置 | 默认值 | 环境变量 |
|
||||
| --- | --- | --- |
|
||||
| 日志树总量上限 | 1024 MB | `SNOWLUMA_LOG_MAX_TOTAL_MB` |
|
||||
| 日志保留天数 | 7 天;`0` 表示关闭按日期清理 | `SNOWLUMA_LOG_RETAIN_DAYS` |
|
||||
| 按账号额外写日志 | 关闭 | `SNOWLUMA_LOG_PER_UIN` |
|
||||
|
||||
以上环境变量优先于 `config/runtime.json`,对应字段会在 WebUI 中显示为锁定。`SNOWLUMA_LOG_MAX_MB` 仅控制单个日志分卷大小,不是日志树总量上限。
|
||||
|
||||
文件日志等级可通过 `SNOWLUMA_LOG_FILE_LEVEL` 单独设置为 `debug`、`info`、`success`、`warn` 或 `error`,默认为 `debug`。该启动参数不写入 `config/runtime.json`,也不受 WebUI 实时日志等级影响;TRACE 始终不落盘。
|
||||
|
||||
## 选择接入方式
|
||||
|
||||
| 入口 | 适合场景 | 参考 |
|
||||
| --- | --- | --- |
|
||||
| WebSocket / HTTP | 对接现有 OneBot 机器人框架 | [OneBot 动作参考](docs/onebot-actions.md) |
|
||||
| TypeScript SDK | 编写类型安全的客户端与消息逻辑 | [`packages/sdk`](packages/sdk/README.md) |
|
||||
| MCP | 让支持 MCP 的工具查询或调用 SnowLuma 动作 | [`packages/mcp`](packages/mcp/README.md) |
|
||||
| WebUI | 管理运行状态、日志、账号与连接 | 启动后访问 `http://localhost:5099` |
|
||||
|
||||
## 开发与贡献
|
||||
|
||||
本地开发需要 Node.js 22.13+(23 系需 23.4+)与项目锁定的 pnpm 10.28.0。所有日常开发基于 `dev` 分支:
|
||||
需要 Node.js 22.13+(23 系需 23.4+)与 pnpm 10.28.0,日常开发基于 `dev` 分支:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/SnowLuma/SnowLuma.git
|
||||
@@ -127,51 +73,30 @@ cd SnowLuma
|
||||
git checkout dev
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm typecheck
|
||||
pnpm lint
|
||||
pnpm test
|
||||
pnpm run build:all
|
||||
```
|
||||
|
||||
`pnpm test` 会运行所有声明了常规测试的 workspace;`pnpm test:all` 是兼容别名,`pnpm test:core` 只运行 Core 测试。原生模块测试需单独运行 `pnpm test:native`。`pnpm coverage` 会生成各常规测试 workspace 的覆盖率报告,但不设置覆盖率阻断阈值。
|
||||
贡献流程见 [`CONTRIBUTING.md`](CONTRIBUTING.md);模块边界与项目词汇见 [`CONTEXT.md`](CONTEXT.md);开发方向见 [`RoadMap.md`](RoadMap.md)。
|
||||
|
||||
- 先读 [`CONTEXT.md`](CONTEXT.md) 了解模块边界与项目词汇。
|
||||
- 提交代码前阅读 [`CONTRIBUTING.md`](CONTRIBUTING.md) 与 [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md)。
|
||||
- 开发方向与已完成事项见 [`RoadMap.md`](RoadMap.md)。
|
||||
## 引用消息预览
|
||||
|
||||
<details>
|
||||
<summary><strong>主要目录</strong></summary>
|
||||
|
||||
| 路径 | 作用 |
|
||||
| --- | --- |
|
||||
| `packages/protocol` | QQ 协议定义、数据包解析、消息推送与 OIDB 服务 |
|
||||
| `packages/onebot` | OneBot 动作执行、事件转换与网络适配 |
|
||||
| `packages/core` | 运行时编排、QQ 会话桥接与 WebUI 服务端 |
|
||||
| `packages/webui` | React 管理界面 |
|
||||
| `packages/sdk` | 对外发布的 TypeScript SDK |
|
||||
| `packages/mcp` | 面向 MCP 客户端的动作目录与执行入口 |
|
||||
|
||||
</details>
|
||||
OneBot 发送 `reply` 段时,会将本地消息缓存中的原文附入 QQ 引用预览,保留文字、换行与引用关系。图片、语音等非文字段以类型提示显示,不重新上传媒体;原消息中的嵌套引用不递归展开。只有消息元数据而没有缓存正文时,不生成虚构的预览内容。
|
||||
|
||||
## 使用边界与许可
|
||||
|
||||
> [!IMPORTANT]
|
||||
> SnowLuma 使用 **源码可见非商业许可**,**不是 OSI 开源许可**。源码可用于查看、学习、非商业自托管及私下修改;任何商业使用,以及公开发布修改版或衍生版,均需事先取得书面授权。
|
||||
> SnowLuma 使用**源码可见非商业许可**,不是 OSI 开源许可。源码可用于查看、学习、非商业自托管及私下修改;商业使用,以及公开发布修改版或衍生版,均需事先取得书面授权。
|
||||
|
||||
- 完整条款见 [`LICENSE`](LICENSE)。
|
||||
- 随附的原生附加组件为专有组件,不在源码许可范围内。
|
||||
- 二进制发行包另受 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md) 约束。
|
||||
- 商业授权请联系 `motricseven@foxmail.com`。
|
||||
完整条款见 [`LICENSE`](LICENSE);二进制发行包另受 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md) 约束;商业授权请联系 `motricseven@foxmail.com`。随附的原生附加组件为专有组件,不在源码许可范围内。
|
||||
|
||||
SnowLuma is source-available for study and non-commercial self-hosting, but it is **not OSI open source**. Commercial use and public distribution of modified or derivative versions require prior written permission. Bundled native components are proprietary and excluded from the source license.
|
||||
SnowLuma is source-available for study and non-commercial self-hosting, but it is not OSI open source. Commercial use and public distribution of modified or derivative versions require prior written permission.
|
||||
|
||||
## 社区与支持
|
||||
## 社区与鸣谢
|
||||
|
||||
- [提交问题](https://github.com/SnowLuma/SnowLuma/issues)
|
||||
- [QQ 群](https://qm.qq.com/q/g3UMLpWALe)
|
||||
- [Telegram](https://t.me/napcatqq)
|
||||
|
||||
## 鸣谢
|
||||
|
||||
项目参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
|
||||
|
||||
<p align="center">
|
||||
|
||||
+12
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.13.0",
|
||||
"version": "1.14.22",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -11,6 +11,7 @@
|
||||
"build:webui": "pnpm --filter webui build",
|
||||
"build:mcp": "pnpm --filter @snowluma/mcp build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter @snowluma/ui build && pnpm --filter webui build",
|
||||
"check:release-layout": "node tools/check-release-layout.mjs",
|
||||
"dev": "pnpm --filter @snowluma/core dev",
|
||||
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
|
||||
"dev:web": "pnpm --filter webui dev",
|
||||
@@ -24,6 +25,7 @@
|
||||
"typecheck": "pnpm -r --if-present typecheck",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"ci": "node tools/ci-check.mjs",
|
||||
"start": "node dist/index.mjs",
|
||||
"bump": "node tools/bump-version.mjs",
|
||||
"release": "node tools/release.mjs"
|
||||
@@ -49,7 +51,15 @@
|
||||
},
|
||||
"overrides": {
|
||||
"esbuild@<0.28.1": "^0.28.1",
|
||||
"@babel/core@<7.29.6": "^7.29.6"
|
||||
"@babel/core@<7.29.6": "^7.29.6",
|
||||
"qs@<=6.15.3": "^6.16.0",
|
||||
"fast-uri@<3.1.6": "^3.1.6",
|
||||
"@hono/node-server@<1.19.15": "^1.19.15",
|
||||
"hono": "~4.12.34",
|
||||
"postcss@<=8.5.22": "^8.5.23",
|
||||
"ip-address@<=10.3.0": "^10.3.1",
|
||||
"body-parser@<2.3.0": "^2.3.0",
|
||||
"brace-expansion@<5.0.7": "^5.0.7"
|
||||
}
|
||||
},
|
||||
"packageManager": "pnpm@10.28.0",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.13.0",
|
||||
"version": "1.14.22",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
@@ -24,6 +24,10 @@
|
||||
"types": "./src/hook-packet-client.ts",
|
||||
"default": "./src/hook-packet-client.ts"
|
||||
},
|
||||
"./packet-timeout": {
|
||||
"types": "./src/packet-timeout.ts",
|
||||
"default": "./src/packet-timeout.ts"
|
||||
},
|
||||
"./injector": {
|
||||
"types": "./src/injector.ts",
|
||||
"default": "./src/injector.ts"
|
||||
|
||||
@@ -81,7 +81,7 @@ export type HookManagerDeps = {
|
||||
* Responsibilities:
|
||||
* - Route user commands (load/unload/refresh) to the matching session.
|
||||
* - Route watcher diff events to the matching session.
|
||||
* - Forward session events ('login' / 'disconnected' / receive health) to BridgeManager.
|
||||
* - Forward session events ('login' / 'disconnected' / transport health) to BridgeManager.
|
||||
* - Retry stuck-in-connecting sessions on every watcher tick (so a
|
||||
* failed connect eventually recovers without a manual refresh).
|
||||
* - Retry the bounded early-process auto-load race without retrying
|
||||
@@ -160,7 +160,7 @@ export class HookManager {
|
||||
} else {
|
||||
this.pipeWatcher = new PipeWatcher({
|
||||
listProcesses: this.enumerate,
|
||||
listLivePipes: () => QqHookClient.listLivePipes(),
|
||||
listLivePipes: processes => QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
|
||||
intervalMs: deps.watcherIntervalMs,
|
||||
log: this.log,
|
||||
});
|
||||
|
||||
@@ -1,10 +1,23 @@
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { QqHookClient, type QqHookSendReply } from './qq-hook-client';
|
||||
import { packetTimeoutMs } from './packet-timeout';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
QqHookClient,
|
||||
type QqHookSendReply,
|
||||
} from './qq-hook-client';
|
||||
|
||||
export type OutboundHealthListener = (healthy: boolean) => void;
|
||||
|
||||
export class HookPacketClient implements PacketSender {
|
||||
constructor(private readonly client: QqHookClient) { }
|
||||
private outboundHealthy = true;
|
||||
|
||||
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
constructor(
|
||||
private readonly client: QqHookClient,
|
||||
private readonly onOutboundHealthChanged?: OutboundHealthListener,
|
||||
) { }
|
||||
|
||||
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
|
||||
}
|
||||
@@ -14,6 +27,7 @@ export class HookPacketClient implements PacketSender {
|
||||
wantReply: true,
|
||||
replyTimeoutMs: timeoutMs,
|
||||
}) as QqHookSendReply;
|
||||
this.setOutboundHealthy(true);
|
||||
return {
|
||||
success: reply.error === 0,
|
||||
gotResponse: true,
|
||||
@@ -22,6 +36,10 @@ export class HookPacketClient implements PacketSender {
|
||||
responseData: reply.body,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof HookPipeRequestError
|
||||
&& error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE) {
|
||||
this.setOutboundHealthy(false);
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
@@ -31,4 +49,10 @@ export class HookPacketClient implements PacketSender {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private setOutboundHealthy(healthy: boolean): void {
|
||||
if (this.outboundHealthy === healthy) return;
|
||||
this.outboundHealthy = healthy;
|
||||
this.onOutboundHealthChanged?.(healthy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
export interface HookRuntimeDirDeps {
|
||||
platform?: NodeJS.Platform;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
ownUid?: number;
|
||||
readText?: (file: string) => string;
|
||||
}
|
||||
|
||||
function configuredDirectory(value: string | undefined, variable: string): string | null {
|
||||
if (!value) return null;
|
||||
if (!path.isAbsolute(value)) {
|
||||
throw new Error(`${variable} must be an absolute path`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseProcessEnvironment(raw: string): NodeJS.ProcessEnv {
|
||||
const result: NodeJS.ProcessEnv = {};
|
||||
for (const entry of raw.split('\0')) {
|
||||
if (!entry) continue;
|
||||
const separator = entry.indexOf('=');
|
||||
if (separator <= 0) continue;
|
||||
result[entry.slice(0, separator)] = entry.slice(separator + 1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseRealUid(status: string): number | null {
|
||||
const match = /^Uid:\s+(\d+)/m.exec(status);
|
||||
if (!match) return null;
|
||||
const uid = Number(match[1]);
|
||||
return Number.isSafeInteger(uid) && uid >= 0 ? uid : null;
|
||||
}
|
||||
|
||||
function isProcessGoneError(error: unknown): boolean {
|
||||
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
||||
return code === 'ENOENT' || code === 'ESRCH';
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function ownRuntimeDir(
|
||||
platform: NodeJS.Platform,
|
||||
env: NodeJS.ProcessEnv,
|
||||
ownUid: number,
|
||||
): string {
|
||||
const explicit = configuredDirectory(
|
||||
env.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
'SNOWLUMA_HOOK_RUNTIME_DIR',
|
||||
);
|
||||
if (explicit) return explicit;
|
||||
|
||||
const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR');
|
||||
if (xdg) return xdg;
|
||||
|
||||
if (platform === 'darwin') {
|
||||
const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR');
|
||||
if (tmpdir) return path.join(tmpdir, 'snowluma-hook');
|
||||
}
|
||||
return `/tmp/snowluma-${ownUid}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the socket directory for the target QQ process. The supervisor may
|
||||
* run under a different user, so its own runtime directory is not authoritative.
|
||||
*/
|
||||
export function resolveHookRuntimeDir(
|
||||
targetPid?: number,
|
||||
deps: HookRuntimeDirDeps = {},
|
||||
): string {
|
||||
const platform = deps.platform ?? process.platform;
|
||||
const env = deps.env ?? process.env;
|
||||
const ownUid = deps.ownUid
|
||||
?? (typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid);
|
||||
const readText = deps.readText ?? ((file: string) => readFileSync(file, 'utf8'));
|
||||
|
||||
if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) {
|
||||
return ownRuntimeDir(platform, env, ownUid);
|
||||
}
|
||||
|
||||
let environError: unknown;
|
||||
try {
|
||||
const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`));
|
||||
const explicit = configuredDirectory(
|
||||
targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
`QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`,
|
||||
);
|
||||
if (explicit) return explicit;
|
||||
const xdg = configuredDirectory(
|
||||
targetEnv.XDG_RUNTIME_DIR,
|
||||
`QQ process ${targetPid} XDG_RUNTIME_DIR`,
|
||||
);
|
||||
if (xdg) return xdg;
|
||||
environError = new Error('runtime directory is not present');
|
||||
} catch (error) {
|
||||
// An invalid explicit path is configuration corruption and must remain
|
||||
// visible. Permission/race failures are expected when /proc disappears;
|
||||
// the status-file fallback below can still recover the target uid.
|
||||
if (error instanceof Error && error.message.includes('must be an absolute path')) {
|
||||
throw error;
|
||||
}
|
||||
environError = error;
|
||||
}
|
||||
|
||||
let statusError: unknown;
|
||||
try {
|
||||
const uid = parseRealUid(readText(`/proc/${targetPid}/status`));
|
||||
if (uid !== null) return `/tmp/snowluma-${uid}`;
|
||||
statusError = new Error('real uid is not available');
|
||||
} catch (error) {
|
||||
statusError = error;
|
||||
}
|
||||
|
||||
if (isProcessGoneError(statusError)
|
||||
&& (isProcessGoneError(environError)
|
||||
|| (environError instanceof Error
|
||||
&& environError.message === 'runtime directory is not present'))) {
|
||||
return ownRuntimeDir(platform, env, ownUid);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`cannot resolve hook runtime directory for PID ${targetPid}: `
|
||||
+ `environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`,
|
||||
);
|
||||
}
|
||||
@@ -15,10 +15,12 @@ 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). */
|
||||
/** How often to re-check account identity while the connection is not ready.
|
||||
* Identity alone never proves that requests can be served. */
|
||||
const LOGIN_RECONCILE_INTERVAL_MS = 3000;
|
||||
const LOGIN_IDENTITY_OBSERVE_INTERVAL_MS = 30_000;
|
||||
const LOGIN_HINT_MAX_ATTEMPTS = 3;
|
||||
const LOGIN_HINT_RETRY_DELAYS_MS = [3000, 9000] as const;
|
||||
|
||||
/** QQ emits this response periodically while its MSF receive path is healthy.
|
||||
* Seeing it once arms the watchdog; before that, silence is UNKNOWN rather
|
||||
@@ -66,8 +68,10 @@ export type HookSessionDeps = {
|
||||
*
|
||||
* Emitted events:
|
||||
* 'login' (uin, packetSender) — real-UIN login detected
|
||||
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
|
||||
* 'receive-health-changed' (healthy) — receive path confirmed stale/recovered
|
||||
* 'disconnected' (wasLoggedIn) — connection dropped, torn down, or
|
||||
* dispose() of a logged-in session
|
||||
* (process shutdown uses this path)
|
||||
* 'receive-health-changed' (healthy) — combined receive/request path health changed
|
||||
* 'status-changed' (status, error) — status field mutated
|
||||
* 'disposed' () — session stopped tracking this PID
|
||||
*/
|
||||
@@ -99,7 +103,13 @@ export class HookSession extends EventEmitter {
|
||||
private disposed = false;
|
||||
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private probing = false;
|
||||
private acceptedLoginHintUin = '';
|
||||
private loginHintAttemptUin = '';
|
||||
private loginHintAttempts = 0;
|
||||
private nextLoginHintAt = 0;
|
||||
private nextLoginIdentityObservationAt = 0;
|
||||
private _receiveHealthy = true;
|
||||
private _outboundHealthy = true;
|
||||
private receiveWatchUin = '';
|
||||
private receiveWatchArmed = false;
|
||||
private receiveWatchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
@@ -123,7 +133,9 @@ export class HookSession extends EventEmitter {
|
||||
get uin(): string { return this._uin; }
|
||||
get method(): string { return this._method; }
|
||||
get isDisposed(): boolean { return this.disposed; }
|
||||
get receiveHealthy(): boolean { return this._receiveHealthy; }
|
||||
get receiveHealthy(): boolean {
|
||||
return this._receiveHealthy && this._outboundHealthy;
|
||||
}
|
||||
|
||||
attachProcessInfo(info: { name?: string; path?: string }): void {
|
||||
if (info.name) this._name = info.name;
|
||||
@@ -227,8 +239,13 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.disposed = true;
|
||||
this.tearDownClient();
|
||||
// Process shutdown must take the same PID-detach path as a live drop.
|
||||
// tearDownClient strips the pipe client first, so this emit is the only
|
||||
// disconnected edge HookManager will see.
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
@@ -492,7 +509,10 @@ export class HookSession extends EventEmitter {
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.client) {
|
||||
this.client = this.makeClient(this.pid);
|
||||
this.sender = new HookPacketClient(this.client);
|
||||
this.sender = new HookPacketClient(
|
||||
this.client,
|
||||
healthy => this.setOutboundHealthy(healthy),
|
||||
);
|
||||
this.bound = false;
|
||||
}
|
||||
if (!this.bound) {
|
||||
@@ -575,6 +595,8 @@ export class HookSession extends EventEmitter {
|
||||
this.bound = false;
|
||||
this.connected = false;
|
||||
this.loggedIn = false;
|
||||
this._outboundHealthy = true;
|
||||
this.resetLoginHint();
|
||||
}
|
||||
|
||||
private handleLoginState(state: QqHookLoginState): void {
|
||||
@@ -582,15 +604,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.
|
||||
// Login readiness has now been confirmed, so identity probing is done.
|
||||
if (this.loggedIn) {
|
||||
this.stopLoginReconcile();
|
||||
// A PID can switch accounts without an intermediate logout edge. Never
|
||||
// carry the previous account's heartbeat deadline into the new epoch.
|
||||
if (this.receiveWatchUin !== this._uin) this.resetReceiveWatch(this._uin);
|
||||
if (this.receiveWatchUin !== this._uin) {
|
||||
this.resetReceiveWatch(this._uin);
|
||||
this._outboundHealthy = true;
|
||||
}
|
||||
} else {
|
||||
this.resetReceiveWatch();
|
||||
this._outboundHealthy = true;
|
||||
}
|
||||
|
||||
// Only the connected/logged-in states are ours to set here; when fully
|
||||
@@ -639,13 +664,9 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
// ─────────────── 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).
|
||||
// The local endpoint can identify an auto-restored account before the
|
||||
// runtime is ready. Forward identity for reconciliation, but never synthesize
|
||||
// online state from the probe.
|
||||
|
||||
private startLoginReconcile(): void {
|
||||
if (this.loginProbeTimer || this.disposed) return;
|
||||
@@ -666,34 +687,85 @@ export class HookSession extends EventEmitter {
|
||||
// slow probe never stacks concurrent subprocess-spawning scans.
|
||||
if (this.probing) return;
|
||||
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
|
||||
if (Date.now() < this.nextLoginIdentityObservationAt) return;
|
||||
this.probing = true;
|
||||
try {
|
||||
let info: QqPortLoginInfo | null;
|
||||
try {
|
||||
info = await this.probeLogin(this.pid);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
this.log.trace(
|
||||
'login identity probe failed: PID=%d err=%s',
|
||||
this.pid,
|
||||
errMsg(error),
|
||||
);
|
||||
return; // best-effort; the interval retries
|
||||
}
|
||||
// The await yielded — re-check we still want this before mutating state.
|
||||
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
|
||||
if (info?.loggedIn && isRealUin(info.uin)) {
|
||||
this.log.info('login reconciled via active probe: PID=%d UIN=%s', this.pid, info.uin);
|
||||
// isRealUin guarantees a pure non-empty digit string, so BigInt() here
|
||||
// cannot throw (keep that contract if isRealUin's regex is ever changed).
|
||||
// Reconcile through QqHookClient instead of mutating HookSession alone:
|
||||
// packet sending and login waiters must observe the same state before
|
||||
// the login event starts Bridge / OneBot initialization.
|
||||
this.client!.reconcileLoginState({
|
||||
loggedIn: true,
|
||||
uin: info.uin,
|
||||
uinNumber: BigInt(info.uin),
|
||||
});
|
||||
if (info?.identityKnown && isRealUin(info.uin)) {
|
||||
const client = this.client;
|
||||
if (!client) return;
|
||||
if (this.acceptedLoginHintUin === info.uin) {
|
||||
this.nextLoginIdentityObservationAt = Date.now()
|
||||
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
return;
|
||||
}
|
||||
if (this.loginHintAttemptUin !== info.uin) {
|
||||
this.loginHintAttemptUin = info.uin;
|
||||
this.loginHintAttempts = 0;
|
||||
this.nextLoginHintAt = 0;
|
||||
this.nextLoginIdentityObservationAt = 0;
|
||||
}
|
||||
if (this.loginHintAttempts >= LOGIN_HINT_MAX_ATTEMPTS
|
||||
|| Date.now() < this.nextLoginHintAt) return;
|
||||
|
||||
const attempt = ++this.loginHintAttempts;
|
||||
this.log.info('login identity discovered: PID=%d UIN=%s; awaiting readiness', this.pid, info.uin);
|
||||
try {
|
||||
await client.reconcileLoginIdentity(info.uin);
|
||||
if (this.client !== client || this.disposed || !this.connected || this.loggedIn) return;
|
||||
this.acceptedLoginHintUin = info.uin;
|
||||
this.nextLoginIdentityObservationAt = Date.now()
|
||||
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
} catch (error) {
|
||||
if (this.client !== client || this.disposed) return;
|
||||
if (attempt >= LOGIN_HINT_MAX_ATTEMPTS) {
|
||||
this.log.warn(
|
||||
'login identity reconciliation failed: PID=%d UIN=%s attempts=%d err=%s',
|
||||
this.pid,
|
||||
info.uin,
|
||||
attempt,
|
||||
errMsg(error),
|
||||
);
|
||||
this.nextLoginIdentityObservationAt = Date.now()
|
||||
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
} else {
|
||||
this.nextLoginHintAt = Date.now()
|
||||
+ LOGIN_HINT_RETRY_DELAYS_MS[attempt - 1]!;
|
||||
this.log.trace(
|
||||
'login identity hint failed: PID=%d UIN=%s attempt=%d err=%s',
|
||||
this.pid,
|
||||
info.uin,
|
||||
attempt,
|
||||
errMsg(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.probing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private resetLoginHint(): void {
|
||||
this.acceptedLoginHintUin = '';
|
||||
this.loginHintAttemptUin = '';
|
||||
this.loginHintAttempts = 0;
|
||||
this.nextLoginHintAt = 0;
|
||||
this.nextLoginIdentityObservationAt = 0;
|
||||
}
|
||||
|
||||
private handlePacket(packet: QqHookPacket): void {
|
||||
if (!this.loggedIn) return;
|
||||
const uin = packet.uin || this._uin;
|
||||
@@ -790,8 +862,29 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
private setReceiveHealthy(healthy: boolean): void {
|
||||
if (this._receiveHealthy === healthy) return;
|
||||
const previous = this.receiveHealthy;
|
||||
this._receiveHealthy = healthy;
|
||||
this.emit('receive-health-changed', healthy);
|
||||
if (previous !== this.receiveHealthy) {
|
||||
this.emit('receive-health-changed', this.receiveHealthy);
|
||||
}
|
||||
}
|
||||
|
||||
private setOutboundHealthy(healthy: boolean): void {
|
||||
if (this._outboundHealthy === healthy) return;
|
||||
const previous = this.receiveHealthy;
|
||||
this._outboundHealthy = healthy;
|
||||
if (previous !== this.receiveHealthy) {
|
||||
this.emit('receive-health-changed', this.receiveHealthy);
|
||||
}
|
||||
if (healthy) {
|
||||
this.log.info('request path recovered: PID=%d UIN=%s', this.pid, this._uin);
|
||||
} else {
|
||||
this.log.warn(
|
||||
'request path unavailable: PID=%d UIN=%s; reporting good=false',
|
||||
this.pid,
|
||||
this._uin,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private resetReceiveWatch(uin = ''): void {
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
|
||||
/** Default wait for a QQ reply when the caller does not pass one. */
|
||||
export const DEFAULT_PACKET_TIMEOUT_MS = 15_000;
|
||||
|
||||
export function packetTimeoutMs(env?: NodeJS.ProcessEnv): number {
|
||||
return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env });
|
||||
}
|
||||
@@ -11,8 +11,9 @@ export type PipeWatcherDeps = {
|
||||
* 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>>;
|
||||
/** Native: PIDs that currently have a live SnowLuma named pipe. The current
|
||||
* process snapshot lets Linux inspect each target user's runtime directory. */
|
||||
listLivePipes: (processes: readonly HookProcessBaseInfo[]) => Promise<Set<number>>;
|
||||
/** Polling interval in ms. Defaults to 1500, floored to 250. */
|
||||
intervalMs?: number;
|
||||
log?: Logger;
|
||||
@@ -158,12 +159,12 @@ export class PipeWatcher extends EventEmitter {
|
||||
this.emit('tick');
|
||||
return;
|
||||
}
|
||||
let livePipes: Set<number>;
|
||||
let livePipes: Set<number> | null;
|
||||
try {
|
||||
livePipes = await this.listLivePipes();
|
||||
livePipes = await this.listLivePipes(processes);
|
||||
} catch (error) {
|
||||
this.log.warn('listLivePipes failed: %s', errMsg(error));
|
||||
livePipes = new Set();
|
||||
livePipes = null;
|
||||
}
|
||||
|
||||
const newKnownPids = new Set<number>();
|
||||
@@ -179,11 +180,19 @@ export class PipeWatcher extends EventEmitter {
|
||||
// 2. Pipes that came up. Ignore pipes for processes we don't know
|
||||
// about (would race against an out-of-order tick).
|
||||
const newLivePipes = new Set<number>();
|
||||
for (const pid of livePipes) {
|
||||
if (!newKnownPids.has(pid)) continue;
|
||||
newLivePipes.add(pid);
|
||||
if (!this.livePipes.has(pid)) {
|
||||
this.emit('pipe-up', pid);
|
||||
if (livePipes === null) {
|
||||
// Keep the last known pipe state for processes that still exist, while
|
||||
// allowing confirmed process exits to complete their normal teardown.
|
||||
for (const pid of this.livePipes) {
|
||||
if (newKnownPids.has(pid)) newLivePipes.add(pid);
|
||||
}
|
||||
} else {
|
||||
for (const pid of livePipes) {
|
||||
if (!newKnownPids.has(pid)) continue;
|
||||
newLivePipes.add(pid);
|
||||
if (!this.livePipes.has(pid)) {
|
||||
this.emit('pipe-up', pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,16 +6,25 @@ import {
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
import { readdirSync, promises as fs } from 'fs';
|
||||
import net from 'net';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
import { resolveHookRuntimeDir } from './hook-runtime-dir';
|
||||
|
||||
export const PIPE_MAGIC = 0x31504851;
|
||||
export const PIPE_VERSION = 1;
|
||||
export const HEADER_SIZE = 40;
|
||||
// Keep these byte limits in lockstep with nnphook's pipe_protocol.hpp. The
|
||||
// native readers already enforce them; mirroring them here prevents the JS
|
||||
// endpoint from buffering frames that the peer can never accept.
|
||||
export const MAX_PIPE_CMD_BYTES = 4096;
|
||||
export const MAX_PIPE_MSG_BYTES = 65536;
|
||||
export const MAX_PIPE_BODY_BYTES = 16 * 1024 * 1024;
|
||||
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
|
||||
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
|
||||
export const PIPE_STATUS_CONNECTION_UNAVAILABLE = -39;
|
||||
const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250;
|
||||
const packetLog = createLogger('QQHook.Packet');
|
||||
const runtimeLog = createLogger('QQHook.Runtime');
|
||||
@@ -28,6 +37,7 @@ export enum PipeOp {
|
||||
error = 5,
|
||||
recvPacket = 6,
|
||||
loginState = 7,
|
||||
loginIdentityHint = 17,
|
||||
}
|
||||
|
||||
const PipeFlagWantReply = 1 << 0;
|
||||
@@ -63,6 +73,7 @@ export interface QqHookSendReply {
|
||||
export interface QqHookClientOptions {
|
||||
ackTimeoutMs?: number;
|
||||
replyTimeoutMs?: number;
|
||||
runtimeDir?: string;
|
||||
}
|
||||
|
||||
export interface QqHookSendOptions {
|
||||
@@ -94,6 +105,20 @@ interface PendingAck {
|
||||
wantReply: boolean;
|
||||
}
|
||||
|
||||
function isMissingDirectoryError(error: unknown): boolean {
|
||||
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
||||
return code === 'ENOENT' || code === 'ENOTDIR';
|
||||
}
|
||||
|
||||
function isUnavailableSocketError(error: unknown): boolean {
|
||||
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
||||
return code === 'ENOENT'
|
||||
|| code === 'ENOTDIR'
|
||||
|| code === 'ENOTSOCK'
|
||||
|| code === 'ECONNREFUSED'
|
||||
|| code === 'ECONNRESET';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync directory scan for `mojo.<pid>.control.sock` socket files in the
|
||||
* runtime dir, returning the pid set. Used by the darwin path of
|
||||
@@ -108,14 +133,15 @@ interface PendingAck {
|
||||
* variant still gates the subsequent `pipe-up` emit via a real connect.
|
||||
*/
|
||||
export function listSnowlumaPipePidsSync(
|
||||
runtimeDir = linuxRuntimeDir(),
|
||||
runtimeDir = resolveHookRuntimeDir(),
|
||||
): Set<number> {
|
||||
const result = new Set<number>();
|
||||
let names: string[];
|
||||
try {
|
||||
names = readdirSync(runtimeDir);
|
||||
} catch {
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (isMissingDirectoryError(error)) return result;
|
||||
throw error;
|
||||
}
|
||||
for (const name of names) {
|
||||
const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name);
|
||||
@@ -126,37 +152,11 @@ export function listSnowlumaPipePidsSync(
|
||||
return result;
|
||||
}
|
||||
|
||||
function linuxRuntimeDir(): string {
|
||||
// Name kept for historical reasons (the function predates the macOS port);
|
||||
// applies to every non-win32 platform. The fallback order mirrors each
|
||||
// platform hook's runtime_dir(): explicit override first, then the OS-
|
||||
// native ephemeral-dir convention.
|
||||
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
|
||||
if (explicit && explicit.length > 0) return explicit;
|
||||
const xdg = process.env.XDG_RUNTIME_DIR;
|
||||
if (xdg && xdg.length > 0) return xdg;
|
||||
// macOS: dylib defaults to "$TMPDIR/snowluma-hook" (apps/qq/macos/
|
||||
// qq_hook_dylib.cpp's runtime_dir()). $TMPDIR is per-user on macOS
|
||||
// (under /var/folders/.../T) so this is the right place — Linux's
|
||||
// /tmp/snowluma-<uid> doesn't exist on a stock Mac.
|
||||
if (process.platform === 'darwin') {
|
||||
const tmpdir = process.env.TMPDIR;
|
||||
if (tmpdir && tmpdir.length > 0) {
|
||||
const trimmed = tmpdir.endsWith('/') ? tmpdir.slice(0, -1) : tmpdir;
|
||||
return path.join(trimmed, 'snowluma-hook');
|
||||
}
|
||||
}
|
||||
// Linux fallback: mirrors hook_stub.cpp runtime_dir() last-resort.
|
||||
// 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}`;
|
||||
}
|
||||
|
||||
function mojoPipeName(pid: number, suffix: string): string {
|
||||
function mojoPipeName(pid: number, suffix: string, runtimeDir = resolveHookRuntimeDir(pid)): string {
|
||||
if (process.platform === 'win32') {
|
||||
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
|
||||
}
|
||||
return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`);
|
||||
return path.join(runtimeDir, `mojo.${pid}.${suffix}.sock`);
|
||||
}
|
||||
|
||||
type LinuxPipeProbe = (socketPath: string) => Promise<boolean>;
|
||||
@@ -165,16 +165,18 @@ async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
|
||||
try {
|
||||
const stat = await fs.stat(socketPath);
|
||||
if (!stat.isSocket()) return false;
|
||||
} catch {
|
||||
return false;
|
||||
} catch (error) {
|
||||
if (isUnavailableSocketError(error)) return false;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return new Promise<boolean>((resolve) => {
|
||||
return new Promise<boolean>((resolve, reject) => {
|
||||
let socket: net.Socket;
|
||||
try {
|
||||
socket = net.createConnection(socketPath);
|
||||
} catch {
|
||||
resolve(false);
|
||||
} catch (error) {
|
||||
if (isUnavailableSocketError(error)) resolve(false);
|
||||
else reject(error);
|
||||
return;
|
||||
}
|
||||
let done = false;
|
||||
@@ -189,20 +191,31 @@ async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
|
||||
};
|
||||
timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS);
|
||||
socket.once('connect', () => finish(true));
|
||||
socket.once('error', () => finish(false));
|
||||
socket.once('error', error => {
|
||||
if (isUnavailableSocketError(error)) finish(false);
|
||||
else {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
socket.removeAllListeners();
|
||||
socket.destroy();
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function listLiveLinuxPipePids(
|
||||
runtimeDir = linuxRuntimeDir(),
|
||||
runtimeDir = resolveHookRuntimeDir(),
|
||||
probe: LinuxPipeProbe = isConnectableUnixSocket,
|
||||
): Promise<Set<number>> {
|
||||
const result = new Set<number>();
|
||||
let names: string[];
|
||||
try {
|
||||
names = await fs.readdir(runtimeDir);
|
||||
} catch {
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (isMissingDirectoryError(error)) return result;
|
||||
throw error;
|
||||
}
|
||||
|
||||
await Promise.all(names.map(async (name) => {
|
||||
@@ -262,8 +275,12 @@ function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string):
|
||||
});
|
||||
}
|
||||
|
||||
class HookPipeRequestError extends Error {
|
||||
constructor(message: string) {
|
||||
export class HookPipeRequestError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status: number,
|
||||
readonly requestId: number,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'HookPipeRequestError';
|
||||
}
|
||||
@@ -303,6 +320,7 @@ function encodeFrame({
|
||||
const cmdBuf = Buffer.from(cmd, 'utf8');
|
||||
const msgBuf = Buffer.from(msg, 'utf8');
|
||||
const bodyBuf = toBuffer(body);
|
||||
validatePipeFrameLengths(cmdBuf.length, msgBuf.length, bodyBuf.length);
|
||||
const header = Buffer.alloc(HEADER_SIZE);
|
||||
header.writeUInt32LE(PIPE_MAGIC, 0);
|
||||
header.writeUInt16LE(PIPE_VERSION, 4);
|
||||
@@ -317,45 +335,115 @@ function encodeFrame({
|
||||
return Buffer.concat([header, cmdBuf, msgBuf, bodyBuf]);
|
||||
}
|
||||
|
||||
function validatePipeFrameLengths(cmdLen: number, msgLen: number, bodyLen: number): void {
|
||||
const lengths = [
|
||||
['command', cmdLen, MAX_PIPE_CMD_BYTES],
|
||||
['message', msgLen, MAX_PIPE_MSG_BYTES],
|
||||
['body', bodyLen, MAX_PIPE_BODY_BYTES],
|
||||
] as const;
|
||||
for (const [name, length, limit] of lengths) {
|
||||
if (length > limit) {
|
||||
throw new Error(`pipe frame ${name} length ${length} exceeds limit ${limit}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface PendingPipeFrame {
|
||||
op: number;
|
||||
requestId: number;
|
||||
status: number;
|
||||
flags: number;
|
||||
value0: bigint;
|
||||
cmdLen: number;
|
||||
msgLen: number;
|
||||
bodyLen: number;
|
||||
payload: Buffer;
|
||||
received: number;
|
||||
}
|
||||
|
||||
class FrameReader {
|
||||
private buffer = Buffer.alloc(0);
|
||||
private readonly header = Buffer.alloc(HEADER_SIZE);
|
||||
private headerBytes = 0;
|
||||
private pending: PendingPipeFrame | null = null;
|
||||
|
||||
constructor(private readonly onFrame: (frame: PipeFrame) => void) { }
|
||||
|
||||
push(chunk: Buffer): void {
|
||||
this.buffer = Buffer.concat([this.buffer, chunk]);
|
||||
while (this.buffer.length >= HEADER_SIZE) {
|
||||
const magic = this.buffer.readUInt32LE(0);
|
||||
const version = this.buffer.readUInt16LE(4);
|
||||
if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) {
|
||||
throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`);
|
||||
let chunkOffset = 0;
|
||||
while (chunkOffset < chunk.length) {
|
||||
if (!this.pending) {
|
||||
const headerBytes = Math.min(HEADER_SIZE - this.headerBytes, chunk.length - chunkOffset);
|
||||
chunk.copy(
|
||||
this.header,
|
||||
this.headerBytes,
|
||||
chunkOffset,
|
||||
chunkOffset + headerBytes,
|
||||
);
|
||||
this.headerBytes += headerBytes;
|
||||
chunkOffset += headerBytes;
|
||||
if (this.headerBytes < HEADER_SIZE) return;
|
||||
|
||||
this.headerBytes = 0;
|
||||
const magic = this.header.readUInt32LE(0);
|
||||
const version = this.header.readUInt16LE(4);
|
||||
if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) {
|
||||
throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`);
|
||||
}
|
||||
|
||||
const cmdLen = this.header.readUInt32LE(20);
|
||||
const msgLen = this.header.readUInt32LE(24);
|
||||
const bodyLen = this.header.readUInt32LE(28);
|
||||
validatePipeFrameLengths(cmdLen, msgLen, bodyLen);
|
||||
const payloadLength = cmdLen + msgLen + bodyLen;
|
||||
this.pending = {
|
||||
op: this.header.readUInt16LE(6),
|
||||
requestId: this.header.readUInt32LE(8),
|
||||
status: this.header.readInt32LE(12),
|
||||
flags: this.header.readUInt32LE(16),
|
||||
value0: this.header.readBigUInt64LE(32),
|
||||
cmdLen,
|
||||
msgLen,
|
||||
bodyLen,
|
||||
payload: payloadLength === 0 ? Buffer.alloc(0) : Buffer.allocUnsafe(payloadLength),
|
||||
received: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const cmdLen = this.buffer.readUInt32LE(20);
|
||||
const msgLen = this.buffer.readUInt32LE(24);
|
||||
const bodyLen = this.buffer.readUInt32LE(28);
|
||||
const total = HEADER_SIZE + cmdLen + msgLen + bodyLen;
|
||||
if (this.buffer.length < total) return;
|
||||
const pending = this.pending;
|
||||
const payloadBytes = Math.min(
|
||||
pending.payload.length - pending.received,
|
||||
chunk.length - chunkOffset,
|
||||
);
|
||||
if (payloadBytes > 0) {
|
||||
chunk.copy(
|
||||
pending.payload,
|
||||
pending.received,
|
||||
chunkOffset,
|
||||
chunkOffset + payloadBytes,
|
||||
);
|
||||
pending.received += payloadBytes;
|
||||
chunkOffset += payloadBytes;
|
||||
}
|
||||
if (pending.received < pending.payload.length) return;
|
||||
|
||||
this.pending = null;
|
||||
const frame: PipeFrame = {
|
||||
op: this.buffer.readUInt16LE(6),
|
||||
requestId: this.buffer.readUInt32LE(8),
|
||||
status: this.buffer.readInt32LE(12),
|
||||
flags: this.buffer.readUInt32LE(16),
|
||||
value0: this.buffer.readBigUInt64LE(32),
|
||||
op: pending.op,
|
||||
requestId: pending.requestId,
|
||||
status: pending.status,
|
||||
flags: pending.flags,
|
||||
value0: pending.value0,
|
||||
cmd: '',
|
||||
msg: '',
|
||||
body: Buffer.alloc(0),
|
||||
};
|
||||
|
||||
let offset = HEADER_SIZE;
|
||||
frame.cmd = this.buffer.subarray(offset, offset + cmdLen).toString('utf8');
|
||||
offset += cmdLen;
|
||||
frame.msg = this.buffer.subarray(offset, offset + msgLen).toString('utf8');
|
||||
offset += msgLen;
|
||||
frame.body = Buffer.from(this.buffer.subarray(offset, offset + bodyLen));
|
||||
|
||||
this.buffer = this.buffer.subarray(total);
|
||||
let offset = 0;
|
||||
frame.cmd = pending.payload.subarray(offset, offset + pending.cmdLen).toString('utf8');
|
||||
offset += pending.cmdLen;
|
||||
frame.msg = pending.payload.subarray(offset, offset + pending.msgLen).toString('utf8');
|
||||
offset += pending.msgLen;
|
||||
frame.body = Buffer.from(pending.payload.subarray(offset, offset + pending.bodyLen));
|
||||
this.onFrame(frame);
|
||||
}
|
||||
}
|
||||
@@ -363,6 +451,7 @@ class FrameReader {
|
||||
|
||||
export class QqHookClient extends EventEmitter {
|
||||
readonly pid: number;
|
||||
readonly runtimeDir: string;
|
||||
readonly defaultAckTimeoutMs: number;
|
||||
readonly defaultReplyTimeoutMs: number;
|
||||
|
||||
@@ -383,11 +472,13 @@ export class QqHookClient extends EventEmitter {
|
||||
private loginWaiters: Deferred<QqHookLoginState>[] = [];
|
||||
|
||||
constructor(pid: number, {
|
||||
ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS,
|
||||
ackTimeoutMs = positiveIntEnv('SNOWLUMA_HOOK_ACK_TIMEOUT_MS', DEFAULT_ACK_TIMEOUT_MS),
|
||||
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
|
||||
runtimeDir = resolveHookRuntimeDir(pid),
|
||||
}: QqHookClientOptions = {}) {
|
||||
super();
|
||||
this.pid = pid;
|
||||
this.runtimeDir = runtimeDir;
|
||||
this.defaultAckTimeoutMs = ackTimeoutMs;
|
||||
this.defaultReplyTimeoutMs = replyTimeoutMs;
|
||||
}
|
||||
@@ -413,16 +504,14 @@ export class QqHookClient extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile a login edge that the native hook could not replay after the
|
||||
* pipe connected. The client remains the single source of truth so packet
|
||||
* sending, login waiters, and HookSession all observe the same transition.
|
||||
* Forward an observed account identity for reconciliation. This does not
|
||||
* change login state; readiness still requires peer confirmation.
|
||||
*/
|
||||
reconcileLoginState(state: QqHookLoginState): void {
|
||||
this.applyLoginState({
|
||||
loggedIn: state.loggedIn,
|
||||
uin: state.uin || state.uinNumber.toString(),
|
||||
uinNumber: state.uinNumber,
|
||||
});
|
||||
async reconcileLoginIdentity(uin: string): Promise<void> {
|
||||
if (!isRealUin(uin)) {
|
||||
throw new Error(`invalid QQ login identity hint: ${JSON.stringify(uin)}`);
|
||||
}
|
||||
await this.sendAckOnly(PipeOp.loginIdentityHint, BigInt(uin), 'login identity hint');
|
||||
}
|
||||
|
||||
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
|
||||
@@ -435,12 +524,12 @@ export class QqHookClient extends EventEmitter {
|
||||
return withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
|
||||
}
|
||||
|
||||
static controlPipeName(pid: number): string {
|
||||
return mojoPipeName(pid, 'control');
|
||||
static controlPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string {
|
||||
return mojoPipeName(pid, 'control', runtimeDir);
|
||||
}
|
||||
|
||||
static recvPipeName(pid: number): string {
|
||||
return mojoPipeName(pid, 'recv');
|
||||
static recvPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string {
|
||||
return mojoPipeName(pid, 'recv', runtimeDir);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -449,7 +538,7 @@ export class QqHookClient extends EventEmitter {
|
||||
* opening the pipe, so probing cannot disturb the first real client connect.
|
||||
*/
|
||||
static async probePipe(pid: number): Promise<boolean> {
|
||||
const live = await QqHookClient.listLivePipes();
|
||||
const live = await QqHookClient.listLivePipes([pid]);
|
||||
return live.has(pid);
|
||||
}
|
||||
|
||||
@@ -458,20 +547,24 @@ export class QqHookClient extends EventEmitter {
|
||||
* in a single filesystem listing. The HookManager's pipe-watcher uses this
|
||||
* to drive connect/reconnect decisions without per-PID stat calls.
|
||||
*/
|
||||
static async listLivePipes(): Promise<Set<number>> {
|
||||
static async listLivePipes(pids: readonly number[] = []): Promise<Set<number>> {
|
||||
const result = new Set<number>();
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const names = await fs.readdir('\\\\.\\pipe\\');
|
||||
for (const name of names) {
|
||||
const m = /^mojo\.(\d+)\.control$/i.exec(name);
|
||||
if (m) result.add(Number(m[1]));
|
||||
}
|
||||
if (process.platform === 'win32') {
|
||||
const names = await fs.readdir('\\\\.\\pipe\\');
|
||||
for (const name of names) {
|
||||
const m = /^mojo\.(\d+)\.control$/i.exec(name);
|
||||
if (m) result.add(Number(m[1]));
|
||||
}
|
||||
} else {
|
||||
const runtimeDirs = new Set<string>();
|
||||
if (pids.length === 0) {
|
||||
runtimeDirs.add(resolveHookRuntimeDir());
|
||||
} else {
|
||||
return await listLiveLinuxPipePids();
|
||||
for (const pid of pids) runtimeDirs.add(resolveHookRuntimeDir(pid));
|
||||
}
|
||||
for (const runtimeDir of runtimeDirs) {
|
||||
for (const pid of await listLiveLinuxPipePids(runtimeDir)) result.add(pid);
|
||||
}
|
||||
} catch {
|
||||
/* directory missing or inaccessible — treat as no live pipes */
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -528,18 +621,7 @@ export class QqHookClient extends EventEmitter {
|
||||
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
|
||||
await this.connect();
|
||||
|
||||
// Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would
|
||||
// misbehave once the integer exceeds Number.MAX_SAFE_INTEGER (the
|
||||
// postfix increment loses precision before the shift), letting two
|
||||
// distinct requests collide on the same id. Skip 0 because zero is
|
||||
// used as a sentinel by the wire protocol.
|
||||
let requestId = this.nextRequestId;
|
||||
while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) {
|
||||
requestId = (requestId + 1) >>> 0;
|
||||
if (requestId === 0) requestId = 1;
|
||||
}
|
||||
this.nextRequestId = (requestId + 1) >>> 0;
|
||||
if (this.nextRequestId === 0) this.nextRequestId = 1;
|
||||
const requestId = this.allocateRequestId();
|
||||
const startedAt = Date.now();
|
||||
const bodyBytes = toBuffer(body);
|
||||
const payload = encodeFrame({
|
||||
@@ -763,12 +845,49 @@ export class QqHookClient extends EventEmitter {
|
||||
return writePromise;
|
||||
}
|
||||
|
||||
private allocateRequestId(): number {
|
||||
// Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would lose
|
||||
// precision past Number.MAX_SAFE_INTEGER. Zero remains the wire sentinel.
|
||||
let requestId = this.nextRequestId;
|
||||
while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) {
|
||||
requestId = (requestId + 1) >>> 0;
|
||||
if (requestId === 0) requestId = 1;
|
||||
}
|
||||
this.nextRequestId = (requestId + 1) >>> 0;
|
||||
if (this.nextRequestId === 0) this.nextRequestId = 1;
|
||||
return requestId;
|
||||
}
|
||||
|
||||
private async sendAckOnly(op: PipeOp, value0: bigint, label: string): Promise<number> {
|
||||
await this.connect();
|
||||
const requestId = this.allocateRequestId();
|
||||
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
|
||||
ackDeferred.promise.catch(() => { /* observed by the await below */ });
|
||||
this.pendingAcks.set(requestId, {
|
||||
resolve: ackDeferred.resolve,
|
||||
reject: ackDeferred.reject,
|
||||
wantReply: false,
|
||||
});
|
||||
try {
|
||||
await this.writeControl(encodeFrame({ op, requestId, value0 }));
|
||||
await withTimeout(
|
||||
ackDeferred.promise,
|
||||
this.defaultAckTimeoutMs,
|
||||
`${label} ack ${requestId}`,
|
||||
);
|
||||
return requestId;
|
||||
} catch (error) {
|
||||
this.pendingAcks.delete(requestId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async connectPipe(kind: 'control' | 'recv'): Promise<QqHookHello> {
|
||||
return runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
const pipeName = kind === 'control'
|
||||
? QqHookClient.controlPipeName(this.pid)
|
||||
: QqHookClient.recvPipeName(this.pid);
|
||||
? QqHookClient.controlPipeName(this.pid, this.runtimeDir)
|
||||
: QqHookClient.recvPipeName(this.pid, this.runtimeDir);
|
||||
let phase: 'connect' | 'hello' = 'connect';
|
||||
runtimeLog.trace(
|
||||
'hook_pipe_start pid=%d kind=%s pipeName=%j',
|
||||
@@ -830,7 +949,7 @@ export class QqHookClient extends EventEmitter {
|
||||
reader.push(chunk);
|
||||
} catch (error) {
|
||||
this.emit('error', error);
|
||||
socket.destroy(error instanceof Error ? error : undefined);
|
||||
socket.destroy();
|
||||
}
|
||||
});
|
||||
socket.on('error', error => {
|
||||
@@ -951,7 +1070,11 @@ export class QqHookClient extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
if (frame.op === PipeOp.error) {
|
||||
const error = new HookPipeRequestError(frame.msg || `pipe error ${frame.status}`);
|
||||
const error = new HookPipeRequestError(
|
||||
frame.msg || `pipe error ${frame.status}`,
|
||||
frame.status,
|
||||
frame.requestId,
|
||||
);
|
||||
const ack = this.pendingAcks.get(frame.requestId);
|
||||
if (ack) {
|
||||
this.pendingAcks.delete(frame.requestId);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { exec } from 'child_process';
|
||||
import net from 'net';
|
||||
import http from 'http';
|
||||
import https from 'https';
|
||||
import { promisify } from 'util';
|
||||
@@ -8,9 +7,6 @@ import { promisify } from 'util';
|
||||
const execAsync = promisify(exec);
|
||||
const log = createLogger('LoginProbe');
|
||||
|
||||
const PORT_RANGE_START = 9210;
|
||||
const PORT_RANGE_END = 9219;
|
||||
const PROBE_TIMEOUT_MS = 1000;
|
||||
const CONNECTION_TIMEOUT_MS = 500;
|
||||
const COMMAND_TIMEOUT_MS = 1500;
|
||||
const OVERALL_PROBE_TIMEOUT_MS = 5000;
|
||||
@@ -28,102 +24,11 @@ export interface QqPortLoginInfo {
|
||||
uin: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
loggedIn: boolean;
|
||||
/** The local QQ endpoint exposed an account identity. This does not prove
|
||||
* the native protocol session is ready to send or receive packets. */
|
||||
identityKnown: boolean;
|
||||
}
|
||||
|
||||
interface JwtPayload {
|
||||
errCode: number;
|
||||
errMsg: string;
|
||||
port: number;
|
||||
uin?: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
data?: {
|
||||
uin?: string;
|
||||
url?: string;
|
||||
};
|
||||
iat: number;
|
||||
}
|
||||
|
||||
function decodeJwt(token: string): JwtPayload | null {
|
||||
try {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) return null;
|
||||
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
|
||||
return JSON.parse(payload);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
|
||||
return new Promise((resolve) => {
|
||||
const client = new net.Socket();
|
||||
const link = 'tencent://';
|
||||
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
|
||||
|
||||
let responseData = '';
|
||||
let timer: NodeJS.Timeout;
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
client.removeAllListeners();
|
||||
client.destroy();
|
||||
};
|
||||
|
||||
timer = setTimeout(() => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
}, PROBE_TIMEOUT_MS);
|
||||
|
||||
client.setTimeout(CONNECTION_TIMEOUT_MS);
|
||||
|
||||
client.connect(port, '127.0.0.1', () => {
|
||||
client.write(payload);
|
||||
});
|
||||
|
||||
client.on('data', (data) => {
|
||||
responseData += data.toString();
|
||||
});
|
||||
|
||||
client.on('close', () => {
|
||||
cleanup();
|
||||
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
|
||||
if (!jwtMatch) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const decoded = decodeJwt(jwtMatch[0]);
|
||||
if (!decoded || decoded.errCode !== 0) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const uin = decoded.uin || decoded.data?.uin || '';
|
||||
resolve({
|
||||
port,
|
||||
uin,
|
||||
uid: decoded.uid,
|
||||
nickName: decoded.nickName,
|
||||
loggedIn: uin.length > 0,
|
||||
});
|
||||
});
|
||||
|
||||
client.on('error', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
|
||||
client.on('timeout', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the
|
||||
* probe reads are modelled; QQ sends more but they're irrelevant here. */
|
||||
interface PtloginUin {
|
||||
@@ -194,7 +99,7 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
|
||||
port,
|
||||
uin: String(account.uin || account.account || ''),
|
||||
nickName: account.nickname || '',
|
||||
loggedIn: true,
|
||||
identityKnown: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -264,7 +169,7 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
|
||||
if (ports.length === 0) {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return { port: 0, uin: '', loggedIn: false };
|
||||
return { port: 0, uin: '', identityKnown: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -294,17 +199,13 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
|
||||
return {
|
||||
port: ports[0] || 0,
|
||||
uin: '',
|
||||
loggedIn: false,
|
||||
identityKnown: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const deepLinkPorts = ports.filter(p => p >= PORT_RANGE_START && p <= PORT_RANGE_END);
|
||||
for (const port of deepLinkPorts) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
}
|
||||
|
||||
// Background discovery must remain passive. Interactive application
|
||||
// endpoints are deliberately excluded from automatic probing.
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { HookPacketClient } from '../src/hook-packet-client';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
type QqHookClient,
|
||||
} from '../src/qq-hook-client';
|
||||
|
||||
function fakeClient(send: QqHookClient['send']): QqHookClient {
|
||||
return {
|
||||
isLoggedIn: true,
|
||||
send,
|
||||
} as unknown as QqHookClient;
|
||||
}
|
||||
|
||||
describe('HookPacketClient outbound health', () => {
|
||||
it('reports native connection loss once and recovers after a successful request', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValueOnce(new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
1,
|
||||
))
|
||||
.mockRejectedValueOnce(new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
2,
|
||||
))
|
||||
.mockResolvedValueOnce({
|
||||
requestId: 3,
|
||||
error: 0,
|
||||
message: '',
|
||||
body: Buffer.from('ok'),
|
||||
});
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: false, gotResponse: false });
|
||||
await sender.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: true, gotResponse: true });
|
||||
|
||||
expect(healthChanged.mock.calls).toEqual([[false], [true]]);
|
||||
});
|
||||
|
||||
it('does not classify ordinary request rejection as connection loss', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi.fn<QqHookClient['send']>().mockRejectedValue(
|
||||
new HookPipeRequestError('This request is not valid.', -38, 1),
|
||||
);
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: false, gotResponse: false });
|
||||
|
||||
expect(healthChanged).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { resolveHookRuntimeDir } from '../src/hook-runtime-dir';
|
||||
|
||||
function procReader(files: Record<string, string>) {
|
||||
return (file: string): string => {
|
||||
const value = files[file];
|
||||
if (value === undefined) throw new Error(`missing fixture: ${file}`);
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
describe('resolveHookRuntimeDir — Linux target process ownership', () => {
|
||||
it('uses the QQ process runtime directory instead of the supervisor user directory', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0XDG_RUNTIME_DIR=/run/user/1000\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/run/user/1000');
|
||||
});
|
||||
|
||||
it('falls back to the QQ process uid when its environment has no runtime directory', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'HOME=/home/rikka\0',
|
||||
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/tmp/snowluma-1000');
|
||||
});
|
||||
|
||||
it('fails visibly when target ownership cannot be determined', () => {
|
||||
expect(() => resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => { throw new Error('permission denied'); },
|
||||
})).toThrow(/cannot resolve hook runtime directory.*permission denied/);
|
||||
});
|
||||
|
||||
it('uses the current convention when the target disappears during discovery', () => {
|
||||
const gone = Object.assign(new Error('process disappeared'), { code: 'ENOENT' });
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: { XDG_RUNTIME_DIR: '/run/user/0' },
|
||||
ownUid: 0,
|
||||
readText: () => { throw gone; },
|
||||
})).toBe('/run/user/0');
|
||||
});
|
||||
|
||||
it('honours an explicit runtime directory inherited by the QQ process', () => {
|
||||
expect(resolveHookRuntimeDir(46301, {
|
||||
platform: 'linux',
|
||||
env: {},
|
||||
ownUid: 0,
|
||||
readText: procReader({
|
||||
'/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0',
|
||||
'/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n',
|
||||
}),
|
||||
})).toBe('/srv/snowluma-hook');
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,12 @@ import { afterEach, describe, it, expect, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookSession } from '../src/hook-session';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
type QqHookClient,
|
||||
type QqHookPacket,
|
||||
} from '../src/qq-hook-client';
|
||||
import type { QqPortLoginInfo } from '../src/qq-port-probe';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
@@ -33,7 +38,11 @@ class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
shouldFailConnect = false;
|
||||
nativeReadyOnIdentityHint = false;
|
||||
identityHintFailures = 0;
|
||||
sendError: Error | null = null;
|
||||
readonly sentPackets: Array<{ serviceCmd: string; body: Buffer }> = [];
|
||||
readonly loginIdentityHints: string[] = [];
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
@@ -46,7 +55,16 @@ class FakeClient extends EventEmitter {
|
||||
this.loginState = { ...state };
|
||||
this.emit('loginState', { ...this.loginState });
|
||||
}
|
||||
async reconcileLoginIdentity(uin: string): Promise<void> {
|
||||
this.loginIdentityHints.push(uin);
|
||||
if (this.identityHintFailures > 0) {
|
||||
this.identityHintFailures--;
|
||||
throw new Error('identity hint unavailable');
|
||||
}
|
||||
if (this.nativeReadyOnIdentityHint) this.fireLogin(uin);
|
||||
}
|
||||
async send(serviceCmd: string, body: Buffer) {
|
||||
if (this.sendError) throw this.sendError;
|
||||
this.sentPackets.push({ serviceCmd, body: Buffer.from(body) });
|
||||
return {
|
||||
requestId: this.sentPackets.length,
|
||||
@@ -76,6 +94,8 @@ function makeSession(opts: {
|
||||
clientFailsConnect?: boolean;
|
||||
onPacket?: PacketSink;
|
||||
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
|
||||
nativeReadyOnIdentityHint?: boolean;
|
||||
identityHintFailures?: number;
|
||||
} = {}) {
|
||||
const pid = opts.pid ?? 1234;
|
||||
let pipeLive = opts.pipeLive ?? false;
|
||||
@@ -84,15 +104,17 @@ 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 }));
|
||||
// Default probe exposes no identity so the reconcile safety net is inert
|
||||
// unless a test opts into a known account.
|
||||
const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', identityKnown: false }));
|
||||
|
||||
const session = new HookSession(pid, {
|
||||
injector,
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
if (opts.clientFailsConnect) c.shouldFailConnect = true;
|
||||
c.nativeReadyOnIdentityHint = opts.nativeReadyOnIdentityHint ?? false;
|
||||
c.identityHintFailures = opts.identityHintFailures ?? 0;
|
||||
clients.push(c);
|
||||
// Cast: FakeClient mirrors only the surface HookSession touches.
|
||||
return c as unknown as QqHookClient;
|
||||
@@ -622,6 +644,40 @@ describe('HookSession — process gone', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — dispose', () => {
|
||||
it('emits disconnected(true) while logged in so BridgeManager can detach the PID', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
ctx.session.dispose();
|
||||
|
||||
expect(discSpy).toHaveBeenCalledOnce();
|
||||
expect(discSpy).toHaveBeenCalledWith(true);
|
||||
expect(ctx.session.isDisposed).toBe(true);
|
||||
});
|
||||
|
||||
it('does not emit disconnected when disposed before login', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
ctx.session.dispose();
|
||||
|
||||
expect(discSpy).not.toHaveBeenCalled();
|
||||
expect(ctx.session.isDisposed).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
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
|
||||
@@ -810,10 +866,11 @@ describe('HookSession — packet forwarding', () => {
|
||||
});
|
||||
|
||||
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
|
||||
it('keeps the packet sender usable when login is reconciled by the active probe', async () => {
|
||||
it('keeps the packet sender usable only after native readiness confirms the identity hint', async () => {
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
|
||||
nativeReadyOnIdentityHint: true,
|
||||
});
|
||||
let sender: PacketSender | undefined;
|
||||
ctx.session.on('login', (_uin: string, nextSender: PacketSender) => {
|
||||
@@ -839,13 +896,12 @@ 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".
|
||||
it('treats a port-probed account as an identity hint, not native login proof', async () => {
|
||||
// Account identity does not prove request readiness. The bridge must wait
|
||||
// for a login-state confirmation instead of synthesizing one.
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
@@ -853,18 +909,89 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush(); // connect (not logged in via frame) → starts reconcile
|
||||
await flush(); // immediate probe resolves → handleLoginState
|
||||
await flush(); // immediate probe resolves → forwards identity hint
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
expect(loginSpy.mock.calls[0]![0]).toBe('10001');
|
||||
expect(ctx.session.status).toBe('online');
|
||||
expect(ctx.session.uin).toBe('10001');
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
expect(ctx.session.uin).toBe('0');
|
||||
});
|
||||
|
||||
it('forwards the same identity at most once per pipe connection', async () => {
|
||||
vi.useFakeTimers();
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
|
||||
});
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await vi.advanceTimersByTimeAsync(9000);
|
||||
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps observing identity after acknowledgement and forwards an account change', async () => {
|
||||
vi.useFakeTimers();
|
||||
let uin = '10001';
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin, identityKnown: true }),
|
||||
});
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
|
||||
uin = '20002';
|
||||
await vi.advanceTimersByTimeAsync(29_999);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '20002']);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('retries identity forwarding failures with a strict bound', async () => {
|
||||
vi.useFakeTimers();
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
|
||||
identityHintFailures: 3,
|
||||
});
|
||||
try {
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(9000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001', '10001']);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(ctx.currentClient().loginIdentityHints).toHaveLength(3);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
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 }),
|
||||
probeLogin: async () => ({ port: 0, uin: '', identityKnown: false }),
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
@@ -879,7 +1006,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
it('ignores a probe with a non-real uin (0)', async () => {
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '0', loggedIn: true }),
|
||||
probeLogin: async () => ({ port: 4301, uin: '0', identityKnown: true }),
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
@@ -908,10 +1035,11 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
it('detects a login that lands on a LATER interval probe', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let loggedIn = false;
|
||||
let identityKnown = false;
|
||||
const ctx = makeSession({
|
||||
pipeLive: true,
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn }),
|
||||
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown }),
|
||||
nativeReadyOnIdentityHint: true,
|
||||
});
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
@@ -921,7 +1049,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet)
|
||||
expect(loginSpy).not.toHaveBeenCalled();
|
||||
|
||||
loggedIn = true; // QQ finishes auto-login
|
||||
identityKnown = true; // QQ exposes the restored identity
|
||||
await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
@@ -934,7 +1062,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
|
||||
it('does not double-emit when the pushed frame logs in first', async () => {
|
||||
// Pushed-frame login wins; a subsequent probe with the same uin must not
|
||||
// re-emit (handleLoginState dedups), and the reconcile timer is stopped.
|
||||
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', loggedIn: true }));
|
||||
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', identityKnown: true }));
|
||||
const ctx = makeSession({ pipeLive: true, probeLogin });
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
@@ -974,6 +1102,39 @@ describe('HookSession — end-to-end receive health (#233)', () => {
|
||||
ctx.currentClient().firePacket({ seq, error: 0, cmd, uin, body: Buffer.alloc(0) });
|
||||
}
|
||||
|
||||
it('reports native outbound loss as unhealthy and recovers on the next successful request', async () => {
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
let sender: PacketSender | undefined;
|
||||
ctx.session.on('login', (_uin: string, nextSender: PacketSender) => {
|
||||
sender = nextSender;
|
||||
});
|
||||
|
||||
try {
|
||||
// Re-emit on a new account epoch so the test captures the session sender.
|
||||
ctx.currentClient().fireLogin('20002');
|
||||
ctx.currentClient().sendError = new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
1,
|
||||
);
|
||||
|
||||
await sender!.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
expect(ctx.session.receiveHealthy).toBe(false);
|
||||
expect(healthChanges).toEqual([false]);
|
||||
|
||||
// Incoming traffic alone must not conceal a still-broken send path.
|
||||
firePacket(ctx, HEARTBEAT_CMD, '20002');
|
||||
expect(ctx.session.receiveHealthy).toBe(false);
|
||||
|
||||
ctx.currentClient().sendError = null;
|
||||
await sender!.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
expect(ctx.session.receiveHealthy).toBe(true);
|
||||
expect(healthChanges).toEqual([false, true]);
|
||||
} finally {
|
||||
ctx.session.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('becomes unhealthy only after an observed QQ heartbeat stays silent, then recovers on the next packet', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
const { ctx, healthChanges } = await startReceiveSession();
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { existsSyncMock, listPidsMock } = vi.hoisted(() => ({
|
||||
existsSyncMock: vi.fn<(target: string) => boolean>(() => false),
|
||||
listPidsMock: vi.fn(() => new Set<number>()),
|
||||
}));
|
||||
|
||||
vi.mock('fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('fs')>();
|
||||
return {
|
||||
...actual,
|
||||
existsSync: (target: Parameters<typeof actual.existsSync>[0]) =>
|
||||
existsSyncMock(String(target)),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../src/qq-hook-client', () => ({
|
||||
listSnowlumaPipePidsSync: listPidsMock,
|
||||
}));
|
||||
|
||||
const INJECTOR_DIR = path.dirname(fileURLToPath(new URL('../src/injector.ts', import.meta.url)));
|
||||
const ORIGINAL_PLATFORM = process.platform;
|
||||
const ORIGINAL_ARCH = process.arch;
|
||||
|
||||
const HANDLE = {
|
||||
base: 0x7fff0000n,
|
||||
entry: 0x7fff1234n,
|
||||
exceptionTable: 0x7fff5678n,
|
||||
size: 8192,
|
||||
};
|
||||
|
||||
function setPlatform(platform: NodeJS.Platform, arch: string): void {
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: arch, configurable: true });
|
||||
}
|
||||
|
||||
function restorePlatform(): void {
|
||||
Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
|
||||
}
|
||||
|
||||
function nativeSearchDirs(cwd = process.cwd()): string[] {
|
||||
return [
|
||||
path.resolve(INJECTOR_DIR, 'native'),
|
||||
path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(cwd, 'dist', 'native'),
|
||||
path.resolve(cwd, 'packages', 'runtime', 'native'),
|
||||
];
|
||||
}
|
||||
|
||||
function nativeCandidate(fileName: string, dirIndex: number, cwd = process.cwd()): string {
|
||||
return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName);
|
||||
}
|
||||
|
||||
function allowExisting(paths: readonly string[]): void {
|
||||
const allowed = new Set(paths);
|
||||
existsSyncMock.mockImplementation((target) => allowed.has(target));
|
||||
}
|
||||
|
||||
function fakeAddon(overrides: {
|
||||
getAllMainProcess?: number[];
|
||||
loadModuleManual?: (pid: number, dylibPath: string) => unknown;
|
||||
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
|
||||
} = {}) {
|
||||
return {
|
||||
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []),
|
||||
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
|
||||
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)),
|
||||
};
|
||||
}
|
||||
|
||||
function installDlopen(addon: object) {
|
||||
return vi.spyOn(process, 'dlopen').mockImplementation((mod) => {
|
||||
(mod as { exports: object }).exports = addon;
|
||||
});
|
||||
}
|
||||
|
||||
async function loadInjector() {
|
||||
return import('../src/injector');
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
existsSyncMock.mockReset();
|
||||
existsSyncMock.mockReturnValue(false);
|
||||
listPidsMock.mockReset();
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
restorePlatform();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('resolveHookNativePath', () => {
|
||||
it('returns null after probing every search directory', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return false;
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBeNull();
|
||||
expect(probed).toEqual([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.node', 1),
|
||||
nativeCandidate('snowluma-linux-x64.node', 2),
|
||||
nativeCandidate('snowluma-linux-x64.node', 3),
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns the first existing candidate and stops scanning', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const winner = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
const later = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return target === winner || target === later;
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
expect(probed).toEqual([winner]);
|
||||
});
|
||||
|
||||
it('skips missing earlier directories for the injectable .so', async () => {
|
||||
setPlatform('linux', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-linux-arm64.so', 2);
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('so')).toBe(winner);
|
||||
});
|
||||
|
||||
it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const winner = nativeCandidate('snowluma-win32-x64.dll', 3);
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('dll')).toBe(winner);
|
||||
});
|
||||
|
||||
it('uses the generic platform-arch name on win32 arm64', async () => {
|
||||
setPlatform('win32', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-win32-arm64.node', 1);
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
|
||||
it('re-reads process.cwd() for the dist/native fallback', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
|
||||
const winner = path.join('/tmp/sl-injector-cwd', 'dist', 'native', 'snowluma-darwin-arm64.node');
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getNativeHookAddon / getNativeHookLoadError', () => {
|
||||
it('starts with a null load error before any probe', async () => {
|
||||
const { getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null and records a missing-binary error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const dlopen = vi.spyOn(process, 'dlopen');
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('dlopens the resolved .node once and caches the addon', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
const addon = fakeAddon();
|
||||
const dlopen = installDlopen(addon);
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
const first = getNativeHookAddon();
|
||||
const second = getNativeHookAddon();
|
||||
|
||||
expect(first).toBe(addon);
|
||||
expect(second).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
expect(dlopen).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen.mock.calls[0]![1]).toBe(nodePath);
|
||||
});
|
||||
|
||||
it('stores Error.message when process.dlopen throws', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw new Error('not a valid Node addon');
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('not a valid Node addon');
|
||||
});
|
||||
|
||||
it('stringifies a non-Error dlopen failure', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw 42;
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('42');
|
||||
});
|
||||
|
||||
it('retries after a failed load when a binary later appears', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
|
||||
allowExisting([nodePath]);
|
||||
expect(getNativeHookAddon()).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('listHookProcesses', () => {
|
||||
it('on darwin maps sorted pipe pids without opening the native addon', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set([42, 7, 15]));
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] }));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 7, name: 'qq', path: '' },
|
||||
{ pid: 15, name: 'qq', path: '' },
|
||||
{ pid: 42, name: 'qq', path: '' },
|
||||
]);
|
||||
expect(listPidsMock).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('on darwin returns an empty list when no control sockets exist', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
});
|
||||
|
||||
it('on non-darwin returns [] when the addon cannot be loaded', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
});
|
||||
|
||||
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
installDlopen(fakeAddon({
|
||||
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
|
||||
}));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 2, name: 'qq', path: '' },
|
||||
{ pid: 8, name: 'qq', path: '' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('on win32 names processes QQ.exe', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
|
||||
installDlopen(fakeAddon({ getAllMainProcess: [9] }));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 9, name: 'QQ.exe', path: '' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('injectHookProcess', () => {
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow('No hook native addon found for linux-x64');
|
||||
});
|
||||
|
||||
it('throws when the addon exists but the injectable is missing', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
installDlopen(fakeAddon());
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64');
|
||||
});
|
||||
|
||||
it('awaits a thenable loadModuleManual handle', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
const soPath = nativeCandidate('snowluma-linux-x64.so', 0);
|
||||
allowExisting([nodePath, soPath]);
|
||||
const addon = fakeAddon({
|
||||
loadModuleManual: () => Promise.resolve(HANDLE),
|
||||
});
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledTimes(1);
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath);
|
||||
});
|
||||
|
||||
it('accepts a synchronous loadModuleManual return value', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2);
|
||||
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3);
|
||||
allowExisting([nodePath, soPath]);
|
||||
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(77)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath);
|
||||
});
|
||||
|
||||
it('injects snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-win32-x64.node', 0);
|
||||
const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0);
|
||||
allowExisting([nodePath, dllPath]);
|
||||
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(5150)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath);
|
||||
});
|
||||
|
||||
it('propagates a rejected loadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.so', 0),
|
||||
]);
|
||||
installDlopen(fakeAddon({
|
||||
loadModuleManual: () => Promise.reject(new Error('map failed')),
|
||||
}));
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(7)).rejects.toThrow('map failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('unloadHookProcess', () => {
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
expect(() => unloadHookProcess(4242, HANDLE)).toThrow('No hook native addon found for linux-x64');
|
||||
});
|
||||
|
||||
it('forwards pid and handle to unloadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
expect(unloadHookProcess(4242, HANDLE)).toBeUndefined();
|
||||
expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1);
|
||||
expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { QqHookClient } from '../src/qq-hook-client';
|
||||
import { packetTimeoutMs } from '../src/packet-timeout';
|
||||
|
||||
const PACKET = 'SNOWLUMA_PACKET_TIMEOUT_MS';
|
||||
const ACK = 'SNOWLUMA_HOOK_ACK_TIMEOUT_MS';
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env[PACKET];
|
||||
delete process.env[ACK];
|
||||
});
|
||||
|
||||
describe('packet and hook ack timeouts', () => {
|
||||
it('keeps the 15 second packet default', () => {
|
||||
expect(packetTimeoutMs({})).toBe(15_000);
|
||||
});
|
||||
|
||||
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
|
||||
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
|
||||
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
|
||||
});
|
||||
|
||||
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
|
||||
process.env[ACK] = '1200';
|
||||
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
|
||||
expect(client.defaultAckTimeoutMs).toBe(1200);
|
||||
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
|
||||
expect(explicit.defaultAckTimeoutMs).toBe(50);
|
||||
});
|
||||
});
|
||||
@@ -30,6 +30,27 @@ function captureEvents(watcher: PipeWatcher): EventRow[] {
|
||||
}
|
||||
|
||||
describe('PipeWatcher', () => {
|
||||
it('passes the current process snapshot to pipe discovery', async () => {
|
||||
const processes = [
|
||||
{ pid: 1234, name: 'qq', path: '/opt/QQ/qq' },
|
||||
{ pid: 5678, name: 'qq', path: '/opt/QQ/qq' },
|
||||
];
|
||||
let observed: readonly HookProcessBaseInfo[] | undefined;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
listLivePipes: async current => {
|
||||
observed = current;
|
||||
return new Set();
|
||||
},
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
|
||||
expect(observed).toEqual(processes);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
@@ -193,6 +214,38 @@ describe('PipeWatcher', () => {
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('preserves live sessions when pipe discovery temporarily fails', async () => {
|
||||
let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
let failPipeDiscovery = false;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
listLivePipes: async () => {
|
||||
if (failPipeDiscovery) throw new Error('permission denied');
|
||||
return new Set([1234]);
|
||||
},
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
const events = captureEvents(watcher);
|
||||
|
||||
failPipeDiscovery = true;
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
processes = [];
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
expect(watcher.isPipeLive(1234)).toBe(false);
|
||||
watcher.stop();
|
||||
});
|
||||
|
||||
it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => {
|
||||
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
let live = new Set<number>([1234]);
|
||||
|
||||
@@ -15,6 +15,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
HEADER_SIZE,
|
||||
listLiveLinuxPipePids,
|
||||
MAX_PIPE_BODY_BYTES,
|
||||
MAX_PIPE_CMD_BYTES,
|
||||
MAX_PIPE_MSG_BYTES,
|
||||
PIPE_MAGIC,
|
||||
PIPE_VERSION,
|
||||
PipeOp,
|
||||
@@ -147,6 +150,205 @@ describe('listLiveLinuxPipePids', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('QqHookClient — pipe frame limits', () => {
|
||||
it('forwards a probed account as a native identity hint without changing login state', async () => {
|
||||
const pid = 778819;
|
||||
const writes: Buffer[] = [];
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
writes.push(Buffer.from(payload));
|
||||
const requestId = payload.readUInt32LE(8);
|
||||
queueMicrotask(() => socket.emit('data', pipeFrame({
|
||||
op: PipeOp.sendAck,
|
||||
requestId,
|
||||
})));
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
try {
|
||||
await client.reconcileLoginIdentity('10001');
|
||||
|
||||
expect(writes).toHaveLength(1);
|
||||
expect(writes[0]!.readUInt16LE(6)).toBe(PipeOp.loginIdentityHint);
|
||||
expect(writes[0]!.readBigUInt64LE(32)).toBe(10001n);
|
||||
expect(client.getLoginState()).toEqual({
|
||||
loggedIn: false,
|
||||
uin: '0',
|
||||
uinNumber: 0n,
|
||||
});
|
||||
} finally {
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
['command', 20, MAX_PIPE_CMD_BYTES],
|
||||
['message', 24, MAX_PIPE_MSG_BYTES],
|
||||
['body', 28, MAX_PIPE_BODY_BYTES],
|
||||
] as const)(
|
||||
'rejects an oversized inbound %s before waiting for its payload',
|
||||
async (name, lengthOffset, limit) => {
|
||||
const pid = 778830;
|
||||
let socket: net.Socket | null = null;
|
||||
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
|
||||
queueMicrotask(() => {
|
||||
socket!.emit('connect');
|
||||
const header = Buffer.alloc(HEADER_SIZE);
|
||||
header.writeUInt32LE(PIPE_MAGIC, 0);
|
||||
header.writeUInt16LE(PIPE_VERSION, 4);
|
||||
header.writeUInt16LE(PipeOp.hello, 6);
|
||||
header.writeUInt32LE(limit + 1, lengthOffset);
|
||||
socket!.emit('data', header);
|
||||
});
|
||||
return socket;
|
||||
}) as typeof net.createConnection);
|
||||
const client = new QqHookClient(pid);
|
||||
const connecting = client.connect().catch(() => undefined);
|
||||
try {
|
||||
const error = await new Promise<Error>((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => reject(new Error('oversized frame was not rejected')),
|
||||
100,
|
||||
);
|
||||
client.once('error', (reason: unknown) => {
|
||||
clearTimeout(timer);
|
||||
resolve(reason instanceof Error ? reason : new Error(String(reason)));
|
||||
});
|
||||
});
|
||||
|
||||
expect(error.message).toBe(
|
||||
`pipe frame ${name} length ${limit + 1} exceeds limit ${limit}`,
|
||||
);
|
||||
expect(socket?.destroyed).toBe(true);
|
||||
} finally {
|
||||
client.close();
|
||||
await connecting;
|
||||
createConnection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects an oversized outbound command before writing to the pipe', async () => {
|
||||
const pid = 778831;
|
||||
const onWrite = vi.fn();
|
||||
const connection = mockControlPipe(pid, onWrite);
|
||||
const client = new QqHookClient(pid);
|
||||
try {
|
||||
await client.connect();
|
||||
|
||||
await expect(client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES + 1), Buffer.alloc(0), {
|
||||
ackTimeoutMs: 25,
|
||||
})).rejects.toThrow(
|
||||
`pipe frame command length ${MAX_PIPE_CMD_BYTES + 1} exceeds limit ${MAX_PIPE_CMD_BYTES}`,
|
||||
);
|
||||
expect(onWrite).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects an oversized outbound body before writing to the pipe', async () => {
|
||||
const pid = 778832;
|
||||
const onWrite = vi.fn();
|
||||
const connection = mockControlPipe(pid, onWrite);
|
||||
const client = new QqHookClient(pid);
|
||||
try {
|
||||
await client.connect();
|
||||
|
||||
await expect(client.sendNoReply(
|
||||
'test.command',
|
||||
Buffer.alloc(MAX_PIPE_BODY_BYTES + 1),
|
||||
)).rejects.toThrow(
|
||||
`pipe frame body length ${MAX_PIPE_BODY_BYTES + 1} exceeds limit ${MAX_PIPE_BODY_BYTES}`,
|
||||
);
|
||||
expect(onWrite).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts values exactly at the command limit', async () => {
|
||||
const pid = 778833;
|
||||
const connection = mockControlPipe(pid, (socket, payload) => {
|
||||
const requestId = payload.readUInt32LE(8);
|
||||
queueMicrotask(() => socket.emit('data', pipeFrame({
|
||||
op: PipeOp.sendAck,
|
||||
requestId,
|
||||
})));
|
||||
});
|
||||
const client = new QqHookClient(pid);
|
||||
try {
|
||||
await expect(client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES), Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ requestId: 1 });
|
||||
} finally {
|
||||
client.close();
|
||||
connection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('parses fragmented and coalesced frames without losing boundaries', async () => {
|
||||
const pid = 778834;
|
||||
const states: string[] = [];
|
||||
const wire = Buffer.concat([
|
||||
pipeFrame({ op: PipeOp.hello, value0: BigInt(pid), message: 'control' }),
|
||||
pipeFrame({ op: PipeOp.loginState, status: 1, value0: 10001n, message: '10001' }),
|
||||
pipeFrame({ op: PipeOp.loginState, status: 1, value0: 10002n, message: '10002' }),
|
||||
]);
|
||||
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
const socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('connect');
|
||||
queueMicrotask(() => {
|
||||
const cuts = [1, 7, 39, 40, 44, 83, wire.length - 1, wire.length];
|
||||
let offset = 0;
|
||||
for (const end of cuts) {
|
||||
if (end > offset) socket.emit('data', wire.subarray(offset, end));
|
||||
offset = end;
|
||||
}
|
||||
});
|
||||
});
|
||||
return socket;
|
||||
}) as typeof net.createConnection);
|
||||
const client = new QqHookClient(pid);
|
||||
client.on('loginState', state => states.push(state.uin));
|
||||
try {
|
||||
const hello = await client.connect();
|
||||
|
||||
expect(hello).toMatchObject({ pipeName: 'control', pid });
|
||||
expect(states).toEqual(['10001', '10002']);
|
||||
} finally {
|
||||
client.close();
|
||||
createConnection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts an inbound message exactly at the native limit', async () => {
|
||||
const pid = 778835;
|
||||
const message = 'x'.repeat(MAX_PIPE_MSG_BYTES);
|
||||
const frame = pipeFrame({ op: PipeOp.hello, value0: BigInt(pid), message });
|
||||
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
|
||||
const socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
|
||||
queueMicrotask(() => {
|
||||
socket.emit('connect');
|
||||
queueMicrotask(() => {
|
||||
for (let offset = 0; offset < frame.length; offset += 1024) {
|
||||
socket.emit('data', frame.subarray(offset, offset + 1024));
|
||||
}
|
||||
});
|
||||
});
|
||||
return socket;
|
||||
}) as typeof net.createConnection);
|
||||
const client = new QqHookClient(pid);
|
||||
try {
|
||||
await expect(client.connect()).resolves.toMatchObject({ pipeName: message, pid });
|
||||
} finally {
|
||||
client.close();
|
||||
createConnection.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('QqHookClient — runtime TRACE', () => {
|
||||
it('records control and receive pipe hello lifecycles under the parent request', async () => {
|
||||
const pid = 778820;
|
||||
@@ -486,10 +688,19 @@ describe('QqHookClient — packet TRACE', () => {
|
||||
message: 'send ack 1 timed out after 25 ms',
|
||||
});
|
||||
|
||||
await expect(client.sendAndWait(
|
||||
const requestError = await client.sendAndWait(
|
||||
'Pipe.Error',
|
||||
Buffer.from([0xff]),
|
||||
)).rejects.toThrow('send ack 2 timed out after 25 ms');
|
||||
).then(
|
||||
() => null,
|
||||
(error: unknown) => error,
|
||||
);
|
||||
expect(requestError).toMatchObject({
|
||||
name: 'HookPipeRequestError',
|
||||
message: 'send ack 2 timed out after 25 ms',
|
||||
status: 12,
|
||||
requestId: 2,
|
||||
});
|
||||
|
||||
expect(traceMessages(entries)).toEqual(expect.arrayContaining([
|
||||
expect.stringMatching(/^packet_terminal serviceCmd="Ack\.Timeout" requestId=1 outcome=timeout reason=ack_timeout error="send ack 1 timed out after 25 ms" elapsedMs=\d+$/),
|
||||
|
||||
@@ -0,0 +1,695 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { getLogLevel, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
|
||||
|
||||
const execMock = vi.hoisted(() => vi.fn());
|
||||
const httpGetMock = vi.hoisted(() => vi.fn());
|
||||
const httpsGetMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('child_process', () => ({ exec: execMock }));
|
||||
vi.mock('http', () => ({
|
||||
default: { get: httpGetMock },
|
||||
get: httpGetMock,
|
||||
}));
|
||||
vi.mock('https', () => ({
|
||||
default: { get: httpsGetMock },
|
||||
get: httpsGetMock,
|
||||
}));
|
||||
|
||||
import { probeQqLoginInfo } from '../src/qq-port-probe';
|
||||
|
||||
const originalPlatform = process.platform;
|
||||
const EXEC_OPTIONS = { timeout: 1500, killSignal: 'SIGKILL' };
|
||||
const PTLOGIN_HEADERS = {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
};
|
||||
|
||||
type ExecCallback = (error: Error | null, result?: { stdout: string; stderr: string }) => void;
|
||||
type RequestLike = EventEmitter & { destroy: ReturnType<typeof vi.fn> };
|
||||
|
||||
function setPlatform(platform: string): void {
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
}
|
||||
|
||||
function mockExec(replies: Record<string, string | Error>): void {
|
||||
execMock.mockImplementation((command: string, _options: unknown, callback: ExecCallback) => {
|
||||
const reply = replies[command];
|
||||
if (reply === undefined) {
|
||||
callback(new Error(`unexpected command ${command}`));
|
||||
return;
|
||||
}
|
||||
if (reply instanceof Error) {
|
||||
callback(reply);
|
||||
return;
|
||||
}
|
||||
callback(null, { stdout: reply, stderr: '' });
|
||||
});
|
||||
}
|
||||
|
||||
function execCommands(): string[] {
|
||||
return execMock.mock.calls.map((call) => String(call[0]));
|
||||
}
|
||||
|
||||
function ssLine(port: number, pid: number, owner: 'comma' | 'paren' = 'comma'): string {
|
||||
const tag = owner === 'comma' ? `pid=${pid},fd=9` : `pid=${pid}`;
|
||||
return `LISTEN 0 128 127.0.0.1:${port} 0.0.0.0:* users:(("qq",${tag}))`;
|
||||
}
|
||||
|
||||
function netstatLine(localAddr: string, pid: number): string {
|
||||
return ` TCP ${localAddr} 0.0.0.0:0 LISTENING ${pid}`;
|
||||
}
|
||||
|
||||
function jsonp(accounts: unknown[]): string {
|
||||
return `ptui_getuins_CB(${JSON.stringify(accounts)});`;
|
||||
}
|
||||
|
||||
function requestStub(): RequestLike {
|
||||
const req = new EventEmitter() as RequestLike;
|
||||
req.destroy = vi.fn();
|
||||
return req;
|
||||
}
|
||||
|
||||
function replyBody(body: string | ReadonlyArray<string | Buffer>) {
|
||||
return (_url: string, _options: unknown, onResponse: (res: EventEmitter) => void): RequestLike => {
|
||||
const req = requestStub();
|
||||
const res = new EventEmitter();
|
||||
onResponse(res);
|
||||
const chunks = typeof body === 'string' ? [body] : body;
|
||||
for (const chunk of chunks) res.emit('data', chunk);
|
||||
res.emit('end');
|
||||
return req;
|
||||
};
|
||||
}
|
||||
|
||||
function replyError(error: Error) {
|
||||
return (): RequestLike => {
|
||||
const req = requestStub();
|
||||
queueMicrotask(() => req.emit('error', error));
|
||||
return req;
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
execMock.mockReset();
|
||||
httpGetMock.mockReset();
|
||||
httpsGetMock.mockReset();
|
||||
setPlatform('linux');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setPlatform(originalPlatform);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('probeQqLoginInfo — unix listing', () => {
|
||||
it('returns null when ss cannot list sockets', async () => {
|
||||
mockExec({ 'ss -tlnp': new Error('ss: not found') });
|
||||
|
||||
await expect(probeQqLoginInfo(3310)).resolves.toBeNull();
|
||||
expect(execCommands()).toEqual(['ss -tlnp']);
|
||||
expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS);
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports a logged-out identity when the PID has no sockets and pgrep is below 6', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': 'State Recv-Q Send-Q Local Address:Port Peer Address:Port\n',
|
||||
'pgrep -c qq': '5\n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(3311)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
expect(execCommands()).toEqual(['ss -tlnp', 'pgrep -c qq']);
|
||||
expect(execMock.mock.calls[1]?.[1]).toEqual(EXEC_OPTIONS);
|
||||
});
|
||||
|
||||
it('treats a pgrep count of 0 as logged out', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': '0\n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(3312)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('treats a non-numeric pgrep count as 0 and therefore logged out', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': 'qq: no process found\n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(3313)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null when there are no sockets and pgrep is 6 or higher', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': '6\n',
|
||||
});
|
||||
await expect(probeQqLoginInfo(3314)).resolves.toBeNull();
|
||||
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': '9\n',
|
||||
});
|
||||
await expect(probeQqLoginInfo(3315)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('does not treat a failed pgrep as logged out', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': new Error('pgrep: exit 1'),
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(3316)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('uses the first listening port as a logged-out hint when no Ptlogin port is present', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': [
|
||||
ssLine(9218, 4410),
|
||||
ssLine(18000, 4410),
|
||||
].join('\n'),
|
||||
'pgrep -c qq': ' 4 \n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(4410)).resolves.toEqual({
|
||||
port: 9218,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns null for non-Ptlogin ports when the QQ process count is ambiguous', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': ssLine(9218, 4411),
|
||||
'pgrep -c qq': '7\n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(4411)).resolves.toBeNull();
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('collects unique ports from ss lines that name the PID with either pid=N, or pid=N)', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': [
|
||||
'LISTEN 0 128 127.0.0.1:4301users:(("qq",pid=4412,fd=1))',
|
||||
ssLine(4301, 4412, 'comma'),
|
||||
ssLine(4301, 4412, 'comma'),
|
||||
ssLine(4305, 4412, 'paren'),
|
||||
ssLine(4305, 9999, 'comma'),
|
||||
'ESTAB 0 0 127.0.0.1:4307 127.0.0.1:443 users:(("qq",pid=4412,fd=4))',
|
||||
].join('\n'),
|
||||
});
|
||||
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '10001', nickname: 'Ada' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(4412)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '10001',
|
||||
nickName: 'Ada',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock).toHaveBeenCalledTimes(2);
|
||||
expect(httpsGetMock.mock.calls[0]?.[0]).toBe(
|
||||
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('probeQqLoginInfo — Ptlogin identity', () => {
|
||||
it('reads a single account from an odd Ptlogin port over https', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5501) });
|
||||
httpsGetMock.mockImplementation(replyBody(jsonp([{
|
||||
uin: 319427101,
|
||||
account: 1,
|
||||
nickname: 'Snow',
|
||||
extra: 'ignored',
|
||||
}])));
|
||||
|
||||
await expect(probeQqLoginInfo(5501)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '319427101',
|
||||
nickName: 'Snow',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(httpsGetMock).toHaveBeenCalledTimes(2);
|
||||
expect(httpsGetMock.mock.calls[0]?.[1]).toEqual({
|
||||
headers: PTLOGIN_HEADERS,
|
||||
timeout: 500,
|
||||
rejectUnauthorized: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('reads a single account from an even Ptlogin port over http', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4302, 5502) });
|
||||
httpGetMock.mockImplementation(replyBody(jsonp([{
|
||||
account: '2880036470',
|
||||
}])));
|
||||
|
||||
await expect(probeQqLoginInfo(5502)).resolves.toEqual({
|
||||
port: 4302,
|
||||
uin: '2880036470',
|
||||
nickName: '',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
expect(httpGetMock).toHaveBeenCalledTimes(2);
|
||||
expect(httpGetMock.mock.calls[0]?.[0]).toBe(
|
||||
'http://127.0.0.1:4302/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
);
|
||||
expect(httpGetMock.mock.calls[0]?.[1]).toEqual({
|
||||
headers: PTLOGIN_HEADERS,
|
||||
timeout: 500,
|
||||
});
|
||||
});
|
||||
|
||||
it('probes every documented odd Ptlogin port over https', async () => {
|
||||
for (const port of [4301, 4303, 4305, 4307, 4309]) {
|
||||
execMock.mockReset();
|
||||
httpsGetMock.mockReset();
|
||||
httpGetMock.mockReset();
|
||||
mockExec({ 'ss -tlnp': ssLine(port, 5510) });
|
||||
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '70001', nickname: 'Odd' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5510)).resolves.toEqual({
|
||||
port,
|
||||
uin: '70001',
|
||||
nickName: 'Odd',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(String(httpsGetMock.mock.calls[0]?.[0])).toBe(
|
||||
`https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('probes every documented even Ptlogin port over http when no odd port is listening', async () => {
|
||||
for (const port of [4302, 4304, 4306, 4308, 4310]) {
|
||||
execMock.mockReset();
|
||||
httpsGetMock.mockReset();
|
||||
httpGetMock.mockReset();
|
||||
mockExec({ 'ss -tlnp': ssLine(port, 5511) });
|
||||
httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '70002', nickname: 'Even' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5511)).resolves.toEqual({
|
||||
port,
|
||||
uin: '70002',
|
||||
nickName: 'Even',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
expect(String(httpGetMock.mock.calls[0]?.[0])).toBe(
|
||||
`http://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('prefers odd Ptlogin ports and never falls through to even ones', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': [ssLine(4302, 5520), ssLine(4301, 5520)].join('\n'),
|
||||
});
|
||||
httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED')));
|
||||
|
||||
await expect(probeQqLoginInfo(5520)).resolves.toBeNull();
|
||||
expect(httpsGetMock).toHaveBeenCalled();
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(execCommands()).toEqual(['ss -tlnp']);
|
||||
});
|
||||
|
||||
it('tries the next odd Ptlogin port after the first one fails', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': [ssLine(4301, 5521), ssLine(4305, 5521)].join('\n'),
|
||||
});
|
||||
httpsGetMock
|
||||
.mockImplementationOnce(replyBody('<html>nope</html>'))
|
||||
.mockImplementationOnce(replyBody('<html>nope</html>'))
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }])))
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5521)).resolves.toEqual({
|
||||
port: 4305,
|
||||
uin: '188888',
|
||||
nickName: 'Next',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock.mock.calls.map((call) => call[0])).toEqual([
|
||||
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
]);
|
||||
});
|
||||
|
||||
it('stops after the first Ptlogin port that yields a single account', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': [ssLine(4303, 5522), ssLine(4309, 5522)].join('\n'),
|
||||
});
|
||||
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '42', nickname: 'First' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5522)).resolves.toEqual({
|
||||
port: 4303,
|
||||
uin: '42',
|
||||
nickName: 'First',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('uses account when uin is missing or empty, including a numeric 0 uin', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5530) });
|
||||
httpsGetMock
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: 0, account: 314159, nickname: 'Zero' }])))
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '', account: '314159', nickname: 'Zero' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5530)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '314159',
|
||||
nickName: 'Zero',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns an empty uin when the single account has neither uin nor account', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5531) });
|
||||
httpsGetMock.mockImplementation(replyBody('[{"nickname":"Anon"}]'));
|
||||
|
||||
await expect(probeQqLoginInfo(5531)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '',
|
||||
nickName: 'Anon',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the shorter of the two pt_get_uins snapshots', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5540) });
|
||||
httpsGetMock
|
||||
.mockImplementationOnce(replyBody(jsonp([
|
||||
{ uin: '11', nickname: 'A' },
|
||||
{ uin: '22', nickname: 'B' },
|
||||
])))
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '33', nickname: 'Cora' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5540)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '33',
|
||||
nickName: 'Cora',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the first snapshot when both pt_get_uins calls have one account', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5541) });
|
||||
httpsGetMock
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '100', nickname: 'Left' }])))
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '200', nickname: 'Right' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5541)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '100',
|
||||
nickName: 'Left',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts a single account from the second fetch when the first fetch is unusable', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5542) });
|
||||
httpsGetMock
|
||||
.mockImplementationOnce(replyError(new Error('ECONNRESET')))
|
||||
.mockImplementationOnce(replyBody(jsonp([{ uin: '9090', nickname: 'Retry' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(5542)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '9090',
|
||||
nickName: 'Retry',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null for an empty pt_get_uins array and does not consult pgrep', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5550) });
|
||||
httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([]);'));
|
||||
|
||||
await expect(probeQqLoginInfo(5550)).resolves.toBeNull();
|
||||
expect(execCommands()).toEqual(['ss -tlnp']);
|
||||
});
|
||||
|
||||
it('returns null when both snapshots have more than one account', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4304, 5551) });
|
||||
httpGetMock.mockImplementation(replyBody(jsonp([
|
||||
{ uin: '1' },
|
||||
{ uin: '2' },
|
||||
])));
|
||||
|
||||
await expect(probeQqLoginInfo(5551)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when both fetches fail to parse a pt_get_uins body', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5552) });
|
||||
httpsGetMock.mockImplementation(replyBody('not-jsonp'));
|
||||
|
||||
await expect(probeQqLoginInfo(5552)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when both fetches error', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5553) });
|
||||
httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED')));
|
||||
|
||||
await expect(probeQqLoginInfo(5553)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('destroys the request and returns null when both fetches time out', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5554) });
|
||||
const seen: RequestLike[] = [];
|
||||
httpsGetMock.mockImplementation(() => {
|
||||
const req = requestStub();
|
||||
seen.push(req);
|
||||
queueMicrotask(() => req.emit('timeout'));
|
||||
return req;
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(5554)).resolves.toBeNull();
|
||||
expect(seen).toHaveLength(2);
|
||||
expect(seen[0]?.destroy).toHaveBeenCalledTimes(1);
|
||||
expect(seen[1]?.destroy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('joins chunked pt_get_uins bodies including Buffer pieces', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5560) });
|
||||
httpsGetMock.mockImplementation(replyBody([
|
||||
'ptui_getuins_CB([',
|
||||
Buffer.from('{"uin":"10001","nickname":"Ada"}'),
|
||||
']);',
|
||||
]));
|
||||
|
||||
await expect(probeQqLoginInfo(5560)).resolves.toEqual({
|
||||
port: 4301,
|
||||
uin: '10001',
|
||||
nickName: 'Ada',
|
||||
identityKnown: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('treats a nickname that closes the JSONP array early as unusable', async () => {
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 5561) });
|
||||
httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([{"nickname":"a]b","uin":"1"}]);'));
|
||||
|
||||
await expect(probeQqLoginInfo(5561)).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('probeQqLoginInfo — win32 listing', () => {
|
||||
beforeEach(() => {
|
||||
setPlatform('win32');
|
||||
});
|
||||
|
||||
it('returns null when netstat cannot list sockets', async () => {
|
||||
mockExec({ 'netstat -ano': new Error('netstat: access denied') });
|
||||
|
||||
await expect(probeQqLoginInfo(6610)).resolves.toBeNull();
|
||||
expect(execCommands()).toEqual(['netstat -ano']);
|
||||
expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS);
|
||||
});
|
||||
|
||||
it('counts QQ.exe rows from tasklist when netstat lists no sockets for the PID', async () => {
|
||||
mockExec({
|
||||
'netstat -ano': [
|
||||
'Active Connections',
|
||||
'',
|
||||
' Proto Local Address Foreign Address State PID',
|
||||
netstatLine('127.0.0.1:4301', 1),
|
||||
].join('\n'),
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh': [
|
||||
'QQ.exe 100 Console 1 10,000 K',
|
||||
'QQ.exe 101 Console 1 11,000 K',
|
||||
'explorer.exe 200 Console 1 9,000 K',
|
||||
].join('\n'),
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(6611)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
expect(execCommands()).toEqual([
|
||||
'netstat -ano',
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh',
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns null when tasklist reports 6 or more QQ.exe rows and the PID has no sockets', async () => {
|
||||
mockExec({
|
||||
'netstat -ano': '',
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh': [
|
||||
'QQ.exe 1',
|
||||
'QQ.exe 2',
|
||||
'QQ.exe 3',
|
||||
'qq.exe 4',
|
||||
'QQ.EXE 5',
|
||||
'QQ.exe 6',
|
||||
].join('\n'),
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(6612)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('does not treat a failed tasklist as logged out', async () => {
|
||||
mockExec({
|
||||
'netstat -ano': '',
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh': new Error('tasklist: exit 1'),
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(6613)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('parses netstat rows for the owning PID and skips short or portless lines', async () => {
|
||||
mockExec({
|
||||
'netstat -ano': [
|
||||
'Active Connections',
|
||||
' TCP 127.0.0.1:4301 LISTENING',
|
||||
' TCP 127.0.0.1 0.0.0.0:0 LISTENING 6620',
|
||||
netstatLine('10.0.0.8:18000', 1),
|
||||
netstatLine('127.0.0.1:4303', 6620),
|
||||
netstatLine('[::1]:4303', 6620),
|
||||
netstatLine('127.0.0.1:9218', 6620),
|
||||
].join('\n'),
|
||||
});
|
||||
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '20002', nickname: 'Win' }])));
|
||||
|
||||
await expect(probeQqLoginInfo(6620)).resolves.toEqual({
|
||||
port: 4303,
|
||||
uin: '20002',
|
||||
nickName: 'Win',
|
||||
identityKnown: true,
|
||||
});
|
||||
expect(httpsGetMock).toHaveBeenCalledTimes(2);
|
||||
expect(httpsGetMock.mock.calls[0]?.[0]).toBe(
|
||||
'https://127.0.0.1:4303/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the first netstat port as a logged-out hint when no Ptlogin port is present', async () => {
|
||||
mockExec({
|
||||
'netstat -ano': [
|
||||
netstatLine('127.0.0.1:18000', 6630),
|
||||
netstatLine('127.0.0.1:18001', 6630),
|
||||
].join('\n'),
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh': 'QQ.exe 100\n',
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(6630)).resolves.toEqual({
|
||||
port: 18000,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
expect(httpGetMock).not.toHaveBeenCalled();
|
||||
expect(httpsGetMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('probeQqLoginInfo — overall deadline', () => {
|
||||
it('returns null and warns after 5000ms if listing never finishes', async () => {
|
||||
vi.useFakeTimers();
|
||||
execMock.mockImplementation(() => undefined);
|
||||
const previousLevel = getLogLevel();
|
||||
setLogLevel('info');
|
||||
const warnings: string[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => {
|
||||
if (entry.scope === 'LoginProbe' && entry.level === 'warn') {
|
||||
warnings.push(entry.message);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
const pending = probeQqLoginInfo(9001);
|
||||
let settled: unknown = 'pending';
|
||||
void pending.then((value) => {
|
||||
settled = value;
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(4999);
|
||||
expect(settled).toBe('pending');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(pending).resolves.toBeNull();
|
||||
expect(warnings).toEqual(['login check timed out: PID=9001']);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not warn when the probe finishes before the deadline', async () => {
|
||||
mockExec({
|
||||
'ss -tlnp': '',
|
||||
'pgrep -c qq': '2\n',
|
||||
});
|
||||
const previousLevel = getLogLevel();
|
||||
setLogLevel('info');
|
||||
const warnings: string[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => {
|
||||
if (entry.scope === 'LoginProbe') warnings.push(entry.message);
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(probeQqLoginInfo(9002)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
expect(warnings).toEqual([]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
it('abandons a hung Ptlogin fetch at the overall deadline', async () => {
|
||||
vi.useFakeTimers();
|
||||
mockExec({ 'ss -tlnp': ssLine(4301, 9003) });
|
||||
httpsGetMock.mockImplementation(() => requestStub());
|
||||
|
||||
const pending = probeQqLoginInfo(9003);
|
||||
await vi.advanceTimersByTimeAsync(5000);
|
||||
await expect(pending).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,15 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const execMock = vi.hoisted(() => vi.fn());
|
||||
const socketCtorMock = vi.hoisted(() => vi.fn(function MockSocket() {
|
||||
throw new Error('interactive QQ probe must not run');
|
||||
}));
|
||||
|
||||
vi.mock('child_process', () => ({ exec: execMock }));
|
||||
vi.mock('net', () => ({
|
||||
default: { Socket: socketCtorMock },
|
||||
Socket: socketCtorMock,
|
||||
}));
|
||||
|
||||
import { probeQqLoginInfo } from '../src/qq-port-probe';
|
||||
|
||||
@@ -10,6 +17,7 @@ describe('probeQqLoginInfo — bounded execution', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
execMock.mockReset();
|
||||
socketCtorMock.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -33,7 +41,23 @@ describe('probeQqLoginInfo — bounded execution', () => {
|
||||
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
loggedIn: false,
|
||||
identityKnown: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps background identity discovery passive', async () => {
|
||||
execMock
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, {
|
||||
stdout: 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n',
|
||||
stderr: '',
|
||||
});
|
||||
})
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, { stdout: '8\n', stderr: '' });
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
|
||||
expect(socketCtorMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.13.0",
|
||||
"version": "1.14.22",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
@@ -20,6 +20,10 @@
|
||||
"types": "./src/coerce.ts",
|
||||
"default": "./src/coerce.ts"
|
||||
},
|
||||
"./env": {
|
||||
"types": "./src/env.ts",
|
||||
"default": "./src/env.ts"
|
||||
},
|
||||
"./single-flight-cache": {
|
||||
"types": "./src/single-flight-cache.ts",
|
||||
"default": "./src/single-flight-cache.ts"
|
||||
@@ -63,6 +67,10 @@
|
||||
"./uin": {
|
||||
"types": "./src/uin.ts",
|
||||
"default": "./src/uin.ts"
|
||||
},
|
||||
"./access-token": {
|
||||
"types": "./src/access-token.ts",
|
||||
"default": "./src/access-token.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
@@ -73,5 +81,10 @@
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"@zxcvbn-ts/core": "^4.1.2",
|
||||
"@zxcvbn-ts/language-common": "^4.1.3",
|
||||
"@zxcvbn-ts/language-en": "^4.1.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { ZxcvbnFactory } from '@zxcvbn-ts/core';
|
||||
import { adjacencyGraphs, dictionary } from '@zxcvbn-ts/language-common';
|
||||
import { translations } from '@zxcvbn-ts/language-en';
|
||||
|
||||
export const ACCESS_TOKEN_MIN_LENGTH = 16;
|
||||
export const ACCESS_TOKEN_MIN_SCORE = 3;
|
||||
|
||||
export type AccessTokenAssessmentReason =
|
||||
| 'empty'
|
||||
| 'too-short'
|
||||
| 'guessable'
|
||||
| 'acceptable';
|
||||
|
||||
export interface AccessTokenAssessment {
|
||||
acceptable: boolean;
|
||||
reason: AccessTokenAssessmentReason;
|
||||
score: number;
|
||||
}
|
||||
|
||||
const checker = new ZxcvbnFactory({
|
||||
translations,
|
||||
graphs: adjacencyGraphs,
|
||||
dictionary,
|
||||
});
|
||||
|
||||
function normalizeUserInputs(values: readonly (string | number)[]): Array<string | number> {
|
||||
const unique = new Set<string | number>(['SnowLuma', 'OneBot']);
|
||||
for (const value of values) {
|
||||
if (typeof value === 'number') {
|
||||
if (Number.isFinite(value)) unique.add(value);
|
||||
continue;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (trimmed) unique.add(trimmed.slice(0, 256));
|
||||
}
|
||||
return [...unique].slice(0, 24);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a newly chosen OneBot access token against the shared product
|
||||
* policy. Callers decide whether an empty token is permitted in their own
|
||||
* trust context; an empty value is never considered strong here.
|
||||
*/
|
||||
export function assessAccessToken(
|
||||
token: string,
|
||||
userInputs: readonly (string | number)[] = [],
|
||||
): AccessTokenAssessment {
|
||||
if (!token) return { acceptable: false, reason: 'empty', score: 0 };
|
||||
if (token.length < ACCESS_TOKEN_MIN_LENGTH) {
|
||||
return { acceptable: false, reason: 'too-short', score: 0 };
|
||||
}
|
||||
|
||||
const score = checker.check(token, normalizeUserInputs(userInputs)).score;
|
||||
if (score < ACCESS_TOKEN_MIN_SCORE) {
|
||||
return { acceptable: false, reason: 'guessable', score };
|
||||
}
|
||||
return { acceptable: true, reason: 'acceptable', score };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { createLogger } from './logger';
|
||||
|
||||
const log = createLogger('Env');
|
||||
|
||||
/** Node's setTimeout delay is a signed 32-bit integer. */
|
||||
const MAX_POSITIVE_INT = 2_147_483_647;
|
||||
|
||||
/** Read a positive integer environment variable.
|
||||
*
|
||||
* A blank value is absent and returns `fallback`. A present but unusable
|
||||
* value is ignored, with a warning, and also returns `fallback`.
|
||||
*/
|
||||
export function positiveIntEnv(
|
||||
name: string,
|
||||
fallback: number,
|
||||
options?: { max?: number; env?: NodeJS.ProcessEnv },
|
||||
): number {
|
||||
const max = options?.max ?? MAX_POSITIVE_INT;
|
||||
const raw = (options?.env ?? process.env)[name];
|
||||
if (typeof raw !== 'string' || !raw.trim()) return fallback;
|
||||
const value = raw.trim();
|
||||
const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN;
|
||||
if (!Number.isSafeInteger(parsed) || parsed > max) {
|
||||
log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max);
|
||||
return fallback;
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
@@ -506,7 +506,13 @@ class FileWriter {
|
||||
}
|
||||
|
||||
if (!this.quota.reserve(this.file.path, bytes)) return false;
|
||||
this.file.stream.write(data);
|
||||
try {
|
||||
this.file.stream.write(data);
|
||||
} catch (error) {
|
||||
this.disabled = true;
|
||||
this.quota.writeFailed(this.file.path, error);
|
||||
return false;
|
||||
}
|
||||
this.file.bytes += bytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -214,13 +214,12 @@ function emit(
|
||||
level: LogLevel,
|
||||
options: LogOptions,
|
||||
args: unknown[],
|
||||
forceInitialCredentials = false,
|
||||
): void {
|
||||
// Console / subscriber and file filters are independent. If no destination
|
||||
// accepts the record, stop before formatting or building a LogEntry.
|
||||
const passesConsole = forceInitialCredentials || shouldLog(level);
|
||||
const passesConsole = shouldLog(level);
|
||||
const passesFile = level !== 'trace'
|
||||
&& (forceInitialCredentials || shouldLogToFile(level));
|
||||
&& shouldLogToFile(level);
|
||||
if (!passesConsole && !passesFile) return;
|
||||
|
||||
// `trace` is the high-volume full-chain diagnostic stream, intentionally
|
||||
@@ -239,7 +238,7 @@ function emit(
|
||||
|
||||
const reqId = currentRequestId();
|
||||
const formattedMessage = format(...realArgs);
|
||||
const message = level === 'trace' || forceInitialCredentials
|
||||
const message = level === 'trace'
|
||||
? formattedMessage
|
||||
: redactLogMessage(formattedMessage);
|
||||
const line = render(level, options, message, reqId);
|
||||
@@ -265,7 +264,13 @@ function emit(
|
||||
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
const consoleLine = line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n';
|
||||
try {
|
||||
stream.write(consoleLine);
|
||||
} catch {
|
||||
// A full Docker json-file log volume can make stdout/stderr throw.
|
||||
// Logging must not take down message handling or the WebUI.
|
||||
}
|
||||
}
|
||||
|
||||
// File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL,
|
||||
@@ -364,12 +369,17 @@ export function runWithTraceRequest<T>(fn: () => T): T {
|
||||
}
|
||||
|
||||
export function logInitialWebuiCredentials(password: string): void {
|
||||
emit(
|
||||
// This is deliberately not a LogEntry: application logs can be retained on
|
||||
// disk, exported through WebUI, and delivered to subscribers. First-run
|
||||
// credentials must only cross the process terminal boundary.
|
||||
const line = render(
|
||||
'info',
|
||||
{ scope: 'WebUI' },
|
||||
['initial credentials: user=admin password=%s', password],
|
||||
true,
|
||||
format('initial credentials: user=admin password=%s', password),
|
||||
);
|
||||
// Keep the same terminal control-character policy as regular console logs.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
process.stdout.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
|
||||
}
|
||||
|
||||
// Request-correlation primitives remain available for callers that already own
|
||||
|
||||
@@ -7,8 +7,8 @@ export interface RuntimeConfig {
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
* Defaults to false; the Docker image flips it on in supervisord.conf. */
|
||||
hookAutoLoad?: boolean;
|
||||
/** WebUI listener bind address. '0.0.0.0' = all interfaces (default),
|
||||
* '127.0.0.1' = localhost-only. Listener-level: change needs a restart. */
|
||||
/** WebUI listener bind address. '127.0.0.1' = localhost-only (default),
|
||||
* '0.0.0.0' = all IPv4 interfaces. Listener-level: change needs a restart. */
|
||||
webuiHost?: string;
|
||||
/** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this
|
||||
* only flips serving on/off. Listener-level: change needs a restart. */
|
||||
@@ -28,7 +28,7 @@ const CONFIG_DIR = 'config';
|
||||
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||
|
||||
const DEFAULT_WEBUI_PORT = 5099;
|
||||
const DEFAULT_WEBUI_HOST = '0.0.0.0';
|
||||
const DEFAULT_WEBUI_HOST = '127.0.0.1';
|
||||
export const DEFAULT_LOG_MAX_TOTAL_MB = 1024;
|
||||
export const DEFAULT_LOG_RETAIN_DAYS = 7;
|
||||
export const DEFAULT_LOG_PER_UIN = false;
|
||||
@@ -108,6 +108,9 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
|
||||
);
|
||||
if (logPerUin !== undefined) out.logPerUin = logPerUin;
|
||||
|
||||
const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS');
|
||||
if (webuiTls !== undefined) out.webuiTls = { enabled: webuiTls };
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
ACCESS_TOKEN_MIN_LENGTH,
|
||||
ACCESS_TOKEN_MIN_SCORE,
|
||||
assessAccessToken,
|
||||
} from '../src/access-token';
|
||||
|
||||
describe('access token strength', () => {
|
||||
it('requires the configured minimum length', () => {
|
||||
expect(assessAccessToken('a'.repeat(ACCESS_TOKEN_MIN_LENGTH - 1))).toMatchObject({
|
||||
acceptable: false,
|
||||
reason: 'too-short',
|
||||
});
|
||||
});
|
||||
|
||||
it('scores system and user-specific words as guessable', () => {
|
||||
expect(assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001']))
|
||||
.toMatchObject({ acceptable: false, reason: 'guessable' });
|
||||
});
|
||||
|
||||
it('accepts a sufficiently long, hard-to-guess token', () => {
|
||||
const result = assessAccessToken('E5xqVb7_9pLt2QwR4M8kZ1nY', ['SnowLuma', 'OneBot']);
|
||||
|
||||
expect(result.acceptable).toBe(true);
|
||||
expect(result.reason).toBe('acceptable');
|
||||
expect(result.score).toBeGreaterThanOrEqual(ACCESS_TOKEN_MIN_SCORE);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { positiveIntEnv } from '../src/env';
|
||||
|
||||
describe('positiveIntEnv', () => {
|
||||
it('returns the fallback when the variable is absent or blank', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(15);
|
||||
});
|
||||
|
||||
it('reads a positive integer and honors the max', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } })).toBe(2500);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: '80' },
|
||||
})).toBe(80);
|
||||
});
|
||||
|
||||
it('ignores zero, negatives, fractions, and values above the max', () => {
|
||||
for (const raw of ['0', '-5', '1.5', 'nope', '70000']) {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: raw },
|
||||
})).toBe(15);
|
||||
}
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -60,6 +60,13 @@ describe('logger UIN slot padding', () => {
|
||||
expect(() => createLogger('Test').info('no uin')).not.toThrow();
|
||||
});
|
||||
|
||||
it('does not throw when the console stream cannot accept the line', () => {
|
||||
vi.mocked(process.stderr.write).mockImplementation(() => {
|
||||
throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' });
|
||||
});
|
||||
expect(() => createLogger('Test').error('disk is full')).not.toThrow();
|
||||
});
|
||||
|
||||
it('keeps structured subscriber lines plain while terminal output stays colored', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => captured.push(entry));
|
||||
@@ -289,25 +296,26 @@ describe('file output gating', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps bootstrap notices visible and persisted above configured thresholds', async () => {
|
||||
it('prints bootstrap credentials only to the current process terminal', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('error');
|
||||
fresh.setLogLevel('error');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const snapshotBefore = fresh.getLogSnapshot();
|
||||
const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
|
||||
fresh.logInitialWebuiCredentials('secret');
|
||||
unsubscribe();
|
||||
try {
|
||||
fresh.logInitialWebuiCredentials('secret');
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
level: 'info',
|
||||
scope: 'WebUI',
|
||||
message: 'initial credentials: user=admin password=secret',
|
||||
});
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('initial credentials: user=admin password=secret'),
|
||||
undefined,
|
||||
);
|
||||
expect(stdout).toHaveBeenCalledWith(
|
||||
expect.stringContaining('initial credentials: user=admin password=secret'),
|
||||
);
|
||||
expect(entries).toEqual([]);
|
||||
expect(fresh.getLogSnapshot()).toEqual(snapshotBefore);
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
unsubscribe();
|
||||
stdout.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@ describe('normalizeRuntimeConfig', () => {
|
||||
expect(normalizeRuntimeConfig({})).toEqual({
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
webuiHost: '0.0.0.0',
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: false },
|
||||
trustProxy: '',
|
||||
logMaxTotalMb: 1024,
|
||||
@@ -47,7 +47,7 @@ describe('normalizeRuntimeConfig', () => {
|
||||
trustProxy: 5, // non-string → default
|
||||
});
|
||||
expect(out.webuiPort).toBe(5099);
|
||||
expect(out.webuiHost).toBe('0.0.0.0');
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: false });
|
||||
expect(out.trustProxy).toBe('');
|
||||
});
|
||||
@@ -69,12 +69,12 @@ describe('normalizeRuntimeConfig', () => {
|
||||
|
||||
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
|
||||
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true });
|
||||
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0');
|
||||
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('127.0.0.1');
|
||||
});
|
||||
|
||||
it('rejects a non-object input back to full defaults', () => {
|
||||
expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099);
|
||||
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('0.0.0.0');
|
||||
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('127.0.0.1');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -124,6 +124,17 @@ describe('resolveRuntimeEnvOverrides', () => {
|
||||
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
});
|
||||
|
||||
it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '1' })).toEqual({
|
||||
webuiTls: { enabled: true },
|
||||
});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({
|
||||
webuiTls: { enabled: false },
|
||||
});
|
||||
expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' }))
|
||||
.toThrow(/SNOWLUMA_WEBUI_TLS/);
|
||||
});
|
||||
|
||||
it('ignores an out-of-range / non-numeric port env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.13.0",
|
||||
"version": "1.14.22",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -44,17 +44,18 @@
|
||||
"@snowluma/bridge": "workspace:*",
|
||||
"@snowluma/common": "workspace:*",
|
||||
"@snowluma/onebot": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/protocol": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
"@snowluma/websocket": "workspace:*",
|
||||
"otpauth": "^9.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hono/node-server": "^1.19.14",
|
||||
"@hono/node-server": "^1.19.15",
|
||||
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||
"@types/node": "catalog:",
|
||||
"cross-env": "^10.1.0",
|
||||
"hono": "^4.12.25",
|
||||
"hono": "^4.12.34",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
|
||||
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
|
||||
import {
|
||||
FetchFriendListPage,
|
||||
type FriendListPageCategory,
|
||||
type FriendListPageEntry,
|
||||
} from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
|
||||
import { FetchGroupDetail } from '@snowluma/protocol/oidb-services/contacts/fetch-group-detail';
|
||||
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
|
||||
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
|
||||
import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
|
||||
import {
|
||||
FetchGroupRequests,
|
||||
FetchGroupRequestsByUid,
|
||||
groupRequestOperationType,
|
||||
} from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
|
||||
import {
|
||||
FetchRobotUinRanges,
|
||||
type RobotUinRange,
|
||||
@@ -11,8 +19,13 @@ import {
|
||||
} from '@snowluma/protocol/oidb-services/contacts/fetch-robot-uin-ranges';
|
||||
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
|
||||
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
|
||||
import {
|
||||
fetchQidianCorpInfo as fetchQidianCorpInfoWire,
|
||||
type QidianCorpInfo,
|
||||
} from '@snowluma/protocol/services/qidian/fetch-corp-info';
|
||||
import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark';
|
||||
import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark';
|
||||
import { SendTuwenArk, type SendTuwenArkParams } from '@snowluma/protocol/oidb-services/contacts/send-tuwen-ark';
|
||||
import { SetFriendCategory } from '@snowluma/protocol/oidb-services/contacts/set-friend-category';
|
||||
import { toHex } from '@snowluma/common/hex';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
@@ -30,35 +43,16 @@ import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
const log = createLogger('Bridge.Contacts');
|
||||
|
||||
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
|
||||
|
||||
type FriendPropertySource = {
|
||||
additional?: Array<{
|
||||
type?: number;
|
||||
layer1?: {
|
||||
properties?: Array<{
|
||||
code?: number;
|
||||
value?: string;
|
||||
}>;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
|
||||
interface FriendRosterEntry {
|
||||
friend: FriendInfo;
|
||||
categoryId: number;
|
||||
}
|
||||
|
||||
interface FriendCategoryMeta {
|
||||
categoryId: number;
|
||||
categoryName: string;
|
||||
memberCount: number;
|
||||
sortId: number;
|
||||
// Official client stores group mute as an expire timestamp (internal 60027 /
|
||||
// JS groupShutupExpireTime): 0 = off, 0xFFFFFFFF = permanent, otherwise unix
|
||||
// seconds. `> 0` is wrong — a leftover past expire still looks "on".
|
||||
function isGroupAllMuted(expireTs?: number, nowSec = Math.floor(Date.now() / 1000)): boolean {
|
||||
return (expireTs ?? 0) > nowSec;
|
||||
}
|
||||
|
||||
interface FriendRoster {
|
||||
entries: FriendRosterEntry[];
|
||||
categories: FriendCategoryMeta[];
|
||||
entries: FriendListPageEntry[];
|
||||
categories: FriendListPageCategory[];
|
||||
}
|
||||
|
||||
export interface SetFriendCategoryParams {
|
||||
@@ -67,31 +61,25 @@ export interface SetFriendCategoryParams {
|
||||
categoryName?: string;
|
||||
}
|
||||
|
||||
export function buildFriendProperties(raw: FriendPropertySource): Map<number, string> {
|
||||
const props = new Map<number, string>();
|
||||
for (const additional of raw.additional ?? []) {
|
||||
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
|
||||
for (const property of additional.layer1.properties ?? []) {
|
||||
props.set(property.code ?? 0, property.value ?? '');
|
||||
}
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
export function permissionToRole(permission: number): string {
|
||||
switch (permission) {
|
||||
case 1: return 'owner';
|
||||
case 2: return 'admin';
|
||||
default: return 'member';
|
||||
}
|
||||
}
|
||||
|
||||
export function isRobotUin(uin: number, ranges: readonly RobotUinRange[]): boolean {
|
||||
return Number.isInteger(uin)
|
||||
&& uin > 0
|
||||
&& ranges.some(({ minUin, maxUin }) => uin >= minUin && uin <= maxUin);
|
||||
}
|
||||
|
||||
function normalizeGroupRequestSequence(
|
||||
rawSequence: bigint | number | undefined,
|
||||
groupId: number,
|
||||
): number {
|
||||
const sequence = Number(rawSequence ?? 0);
|
||||
if (!Number.isSafeInteger(sequence) || sequence <= 0) {
|
||||
throw new Error(
|
||||
`invalid group-request sequence: group=${groupId} sequence=${String(rawSequence ?? 0)}`,
|
||||
);
|
||||
}
|
||||
return sequence;
|
||||
}
|
||||
|
||||
const MEMBER_LIST_TTL_MS = 60_000;
|
||||
|
||||
export class ContactsApi {
|
||||
@@ -110,6 +98,9 @@ export class ContactsApi {
|
||||
load: (groupId) => this.fetchGroupMemberListUncached(groupId),
|
||||
});
|
||||
private robotUinRangesPromise_: Promise<RobotUinRangeSnapshot> | null = null;
|
||||
/** groupUin → approval msgseq from a private qun.invite card. Written
|
||||
* only by IncomingPacketPipeline (and tests). OneBot reads get/find. */
|
||||
private readonly groupInviteCardSeqs_ = new Map<number, number>();
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
@@ -151,37 +142,25 @@ export class ContactsApi {
|
||||
return GetGroupRecommendArk.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
/** Send a custom 图文 ark card to a C2C peer or group (0xdc2_34). */
|
||||
sendTuwenArk(params: SendTuwenArkParams): Promise<void> {
|
||||
return SendTuwenArk.invoke(this.ctx, params);
|
||||
}
|
||||
|
||||
private async fetchFriendRoster(): Promise<FriendRoster> {
|
||||
const entries: FriendRosterEntry[] = [];
|
||||
const categories = new Map<number, FriendCategoryMeta>();
|
||||
const entries: FriendListPageEntry[] = [];
|
||||
const categories = new Map<number, FriendListPageCategory>();
|
||||
const seenCookies = new Set<string>();
|
||||
let cookie: Uint8Array | undefined;
|
||||
|
||||
for (;;) {
|
||||
const resp = await FetchFriendListPage.invoke(this.ctx, { cookie });
|
||||
for (const raw of resp.friends ?? []) {
|
||||
const props = buildFriendProperties(raw);
|
||||
entries.push({
|
||||
categoryId: raw.customGroup ?? 0,
|
||||
friend: {
|
||||
uin: raw.uin ?? 0,
|
||||
uid: raw.uid ?? '',
|
||||
nickname: props.get(20002) ?? String(raw.uin ?? 0),
|
||||
remark: props.get(103) ?? '',
|
||||
},
|
||||
});
|
||||
}
|
||||
for (const raw of resp.categories ?? []) {
|
||||
const categoryId = raw.categoryId ?? 0;
|
||||
categories.set(categoryId, {
|
||||
categoryId,
|
||||
categoryName: raw.categoryName ?? '',
|
||||
memberCount: raw.memberCount ?? 0,
|
||||
sortId: raw.sortId ?? 0,
|
||||
});
|
||||
const page = await FetchFriendListPage.invoke(this.ctx, { cookie });
|
||||
entries.push(...page.entries);
|
||||
for (const category of page.categories) {
|
||||
categories.set(category.categoryId, category);
|
||||
}
|
||||
|
||||
const next = resp.cookie;
|
||||
const next = page.cookie;
|
||||
if (!next?.length) break;
|
||||
const key = toHex(next);
|
||||
if (seenCookies.has(key)) {
|
||||
@@ -293,6 +272,11 @@ export class ContactsApi {
|
||||
// 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 || '',
|
||||
// #490: expose the description alongside `memo`. QQ fills in either
|
||||
// field alone, so folding both into `memo` made the description
|
||||
// unreachable whenever an announcement was also set.
|
||||
description: raw.info?.description ?? '',
|
||||
allMuted: isGroupAllMuted(raw.info?.shutUpAllTimestamp),
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroups(groups);
|
||||
@@ -319,10 +303,13 @@ export class ContactsApi {
|
||||
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 + the notice preview (memo). `description` is deliberately
|
||||
// left unset — 0x88D_0 has no description tag, so for a group the bot
|
||||
// hasn't joined there is nothing to report (#490).
|
||||
createTime: Number(r.createTime ?? 0n),
|
||||
level: Number(r.level ?? 0n),
|
||||
memo: r.noticePreview ?? '',
|
||||
allMuted: isGroupAllMuted(r.shutUpAllTimestamp),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -341,23 +328,9 @@ export class ContactsApi {
|
||||
const members: GroupMemberInfo[] = [];
|
||||
let token = '';
|
||||
do {
|
||||
const resp = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
|
||||
for (const raw of resp.members ?? []) {
|
||||
members.push({
|
||||
uin: raw.uin?.uin ?? 0,
|
||||
uid: raw.uin?.uid ?? '',
|
||||
nickname: raw.memberName ?? '',
|
||||
card: raw.memberCard?.memberCard ?? '',
|
||||
isRobot: false,
|
||||
role: permissionToRole(raw.permission ?? 0),
|
||||
level: raw.level?.level ?? 0,
|
||||
title: raw.specialTitle ?? '',
|
||||
joinTime: raw.joinTimestamp ?? 0,
|
||||
lastSentTime: raw.lastMsgTimestamp ?? 0,
|
||||
shutUpTime: raw.shutUpTimestamp ?? 0,
|
||||
});
|
||||
}
|
||||
token = resp.token ?? '';
|
||||
const page = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
|
||||
members.push(...page.members);
|
||||
token = page.token;
|
||||
} while (token);
|
||||
|
||||
const robotSnapshot = await robotSnapshotPromise;
|
||||
@@ -385,44 +358,161 @@ export class ContactsApi {
|
||||
return info;
|
||||
}
|
||||
|
||||
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> {
|
||||
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered });
|
||||
/** 企点企业资料卡(#404 后续 PR)。仅在判断命中的是企点账号后再调用。
|
||||
* best-effort:非企点账号或拉取失败返回 null,不影响上层资料读取。 */
|
||||
async fetchQidianCorpInfo(uin: number): Promise<QidianCorpInfo | null> {
|
||||
return fetchQidianCorpInfoWire(this.ctx, uin);
|
||||
}
|
||||
|
||||
async fetchGroupRequests(
|
||||
filtered = false,
|
||||
count = 50,
|
||||
cursor = 0n,
|
||||
): Promise<GroupRequestInfo[]> {
|
||||
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered, count, cursor });
|
||||
const requests: GroupRequestInfo[] = [];
|
||||
for (const raw of resp.requests ?? []) {
|
||||
const groupId = raw.group?.groupUin ?? 0;
|
||||
const targetUin = raw.target?.uin ?? 0;
|
||||
const invitorUin = raw.invitor?.uin ?? 0;
|
||||
const operatorUin = raw.operatorUser?.uin ?? 0;
|
||||
const targetUid = raw.target?.uid
|
||||
|| this.ctx.identity.findUidByUin(targetUin, groupId)
|
||||
|| this.ctx.identity.findUidByUin(targetUin)
|
||||
|| '';
|
||||
const invitorUid = raw.invitor?.uid
|
||||
|| this.ctx.identity.findUidByUin(invitorUin, groupId)
|
||||
|| this.ctx.identity.findUidByUin(invitorUin)
|
||||
|| '';
|
||||
const operatorUid = raw.operatorUser?.uid
|
||||
|| this.ctx.identity.findUidByUin(operatorUin, groupId)
|
||||
|| this.ctx.identity.findUidByUin(operatorUin)
|
||||
|| '';
|
||||
const notifyType = raw.eventType ?? 0;
|
||||
const operationType = groupRequestOperationType(notifyType);
|
||||
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
|
||||
if (operationType === null) {
|
||||
log.warn(
|
||||
'unsupported group-request notification type: group=%d sequence=%s type=%d',
|
||||
groupId,
|
||||
String(raw.sequence ?? 0n),
|
||||
notifyType,
|
||||
);
|
||||
}
|
||||
requests.push({
|
||||
groupId: raw.group?.groupUin ?? 0,
|
||||
groupId,
|
||||
groupName: raw.group?.groupName ?? '',
|
||||
targetUid: raw.target?.uid ?? '',
|
||||
targetUin: 0,
|
||||
targetUid,
|
||||
targetUin: targetUin
|
||||
|| this.ctx.identity.findUinByUid(targetUid, groupId)
|
||||
|| this.ctx.identity.findUinByUid(targetUid)
|
||||
|| 0,
|
||||
targetName: raw.target?.name ?? '',
|
||||
invitorUid: raw.invitor?.uid ?? '',
|
||||
invitorUin: 0,
|
||||
invitorUid,
|
||||
invitorUin: invitorUin
|
||||
|| this.ctx.identity.findUinByUid(invitorUid, groupId)
|
||||
|| this.ctx.identity.findUinByUid(invitorUid)
|
||||
|| 0,
|
||||
invitorName: raw.invitor?.name ?? '',
|
||||
operatorUid: raw.operatorUser?.uid ?? '',
|
||||
operatorUin: 0,
|
||||
operatorUid,
|
||||
operatorUin: operatorUin
|
||||
|| this.ctx.identity.findUinByUid(operatorUid, groupId)
|
||||
|| this.ctx.identity.findUinByUid(operatorUid)
|
||||
|| 0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence: Number(raw.sequence ?? 0),
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
eventType: raw.eventType ?? 0,
|
||||
notifyType,
|
||||
eventType: operationType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
? raw.operateTransInfo
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroupRequests(requests);
|
||||
return requests;
|
||||
}
|
||||
|
||||
/** UID-form request list retained for correlating incoming UID-only pushes.
|
||||
* Explicit list/actions use fetchGroupRequests(), which matches QQ's native
|
||||
* numeric-account path and does not need profile lookups. */
|
||||
async fetchGroupRequestsByUid(
|
||||
filtered = false,
|
||||
count = 50,
|
||||
cursor = 0n,
|
||||
): Promise<GroupRequestInfo[]> {
|
||||
const resp = await FetchGroupRequestsByUid.invoke(this.ctx, { filtered, count, cursor });
|
||||
const requests: GroupRequestInfo[] = [];
|
||||
for (const raw of resp.requests ?? []) {
|
||||
const groupId = raw.group?.groupUin ?? 0;
|
||||
const targetUid = raw.target?.uid ?? '';
|
||||
const invitorUid = raw.invitor?.uid ?? '';
|
||||
const operatorUid = raw.operatorUser?.uid ?? '';
|
||||
const notifyType = raw.eventType ?? 0;
|
||||
const operationType = groupRequestOperationType(notifyType);
|
||||
const sequence = normalizeGroupRequestSequence(raw.sequence, groupId);
|
||||
if (operationType === null) {
|
||||
log.warn(
|
||||
'unsupported group-request notification type: group=%d sequence=%s type=%d',
|
||||
groupId,
|
||||
String(raw.sequence ?? 0n),
|
||||
notifyType,
|
||||
);
|
||||
}
|
||||
requests.push({
|
||||
groupId,
|
||||
groupName: raw.group?.groupName ?? '',
|
||||
targetUid,
|
||||
targetUin: this.ctx.identity.findUinByUid(targetUid, groupId)
|
||||
?? this.ctx.identity.findUinByUid(targetUid)
|
||||
?? 0,
|
||||
targetName: raw.target?.name ?? '',
|
||||
invitorUid,
|
||||
invitorUin: this.ctx.identity.findUinByUid(invitorUid, groupId)
|
||||
?? this.ctx.identity.findUinByUid(invitorUid)
|
||||
?? 0,
|
||||
invitorName: raw.invitor?.name ?? '',
|
||||
operatorUid,
|
||||
operatorUin: this.ctx.identity.findUinByUid(operatorUid, groupId)
|
||||
?? this.ctx.identity.findUinByUid(operatorUid)
|
||||
?? 0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence,
|
||||
state: raw.state ?? 0,
|
||||
notifyType,
|
||||
eventType: operationType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
|
||||
? raw.operateTransInfo
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroupRequests(requests);
|
||||
return requests;
|
||||
}
|
||||
|
||||
/** Live observation write. IncomingPacketPipeline and tests only. */
|
||||
rememberGroupInviteCardSequence(groupUin: number, sequence: number): void {
|
||||
if (groupUin > 0 && sequence > 0) this.groupInviteCardSeqs_.set(groupUin, sequence);
|
||||
}
|
||||
|
||||
/** 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);
|
||||
return this.groupInviteCardSeqs_.get(groupId);
|
||||
}
|
||||
|
||||
/** Resolve the group for a private invite-card msgseq. Numeric OneBot flags
|
||||
* use this path because the card sequence is absent from 0x10C0. */
|
||||
findGroupInviteCardGroupBySequence(sequence: number): number | undefined {
|
||||
return this.ctx.identity.findGroupInviteCardGroupBySequence(sequence);
|
||||
for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) {
|
||||
if (rememberedSequence === sequence) return groupUin;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
|
||||
|
||||
@@ -4,6 +4,10 @@ import {
|
||||
type AiVoiceCategory as NamespaceAiVoiceCategory,
|
||||
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
|
||||
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import {
|
||||
GetGroupTodoList,
|
||||
type GroupTodoListItem as NamespaceGroupTodoListItem,
|
||||
} from '@snowluma/protocol/oidb-services/extras/get-group-todo-list';
|
||||
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';
|
||||
@@ -35,6 +39,7 @@ export interface PttTransInput {
|
||||
// ─────────────── public types (re-exported from bridge.ts as before) ───
|
||||
|
||||
export type StrangerStatus = NamespaceStrangerStatus;
|
||||
export type GroupTodoListItem = NamespaceGroupTodoListItem;
|
||||
|
||||
export const AiVoiceChatType = {
|
||||
Unknown: 0,
|
||||
@@ -87,7 +92,13 @@ export class ExtrasApi {
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
// ─────────────── Group todo (0xF90) ───────────────
|
||||
// ─────────────── Group todo query / mutations (0x9474 / 0xF90) ───────────────
|
||||
|
||||
async getGroupTodoList(groupId: number): Promise<GroupTodoListItem[]> {
|
||||
const items = await GetGroupTodoList.invoke(this.ctx, { groupId });
|
||||
log.debug('group todo list fetched group=%d count=%d', groupId, items.length);
|
||||
return items;
|
||||
}
|
||||
|
||||
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
|
||||
@@ -104,14 +115,20 @@ export class ExtrasApi {
|
||||
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
|
||||
|
||||
/**
|
||||
* Returns `null` on transport / decode failure rather than throwing,
|
||||
* so the OneBot action can produce a clean retcode without try/catch
|
||||
* gymnastics. Namespace throws on transport failure → swallow here.
|
||||
* Keeps the action response user-safe while retaining the underlying
|
||||
* failure in the service log for diagnosis.
|
||||
*/
|
||||
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
|
||||
try {
|
||||
return await GetStrangerStatus.invoke(this.ctx, { uin });
|
||||
} catch {
|
||||
const status = await GetStrangerStatus.invoke(this.ctx, { uin });
|
||||
if (!status) log.warn('user status query returned no status target=%d', uin);
|
||||
return status;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'user status query failed target=%d: %s',
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,13 +17,116 @@ import { SetFilesetStatus } from '@snowluma/protocol/oidb-services/flash-transfe
|
||||
import { ApplyUpload } from '@snowluma/protocol/oidb-services/flash-transfer/apply-upload';
|
||||
import { PrepareUpload } from '@snowluma/protocol/oidb-services/flash-transfer/prepare-upload';
|
||||
import { SendFlashMsg } from '@snowluma/protocol/oidb-services/flash-transfer/send-flash';
|
||||
import { loadBinarySource, computeHashes } from '@snowluma/protocol/highway/utils';
|
||||
import { FileChunkSource } from '@snowluma/protocol/highway';
|
||||
import {
|
||||
computeHashes,
|
||||
inlineBase64Payload,
|
||||
FLASH_TRANSFER_MAX_BYTES,
|
||||
FLASH_TRANSFER_INLINE_MAX_BYTES,
|
||||
} from '@snowluma/protocol/highway/utils';
|
||||
import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
|
||||
import { hashFlashFileStreaming } from '@snowluma/protocol/highway/hash-file';
|
||||
import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream';
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import type { FlashSliceUploadBody, FlashSliceUploadResp, FlashFileId } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
|
||||
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
||||
import { promises as fsp } from 'node:fs';
|
||||
import { deflateSync } from 'node:zlib';
|
||||
|
||||
const FLASH_SLICE_SIZE = 1024 * 1024;
|
||||
|
||||
const FLASH_IMAGE_EXT = new Set([
|
||||
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'heic', 'avif', 'tiff', 'tif', 'ico', 'dib', 'heif',
|
||||
]);
|
||||
const FLASH_AUDIO_EXT = new Set(['mp3', 'wav', 'aac', 'flac']);
|
||||
const FLASH_VIDEO_EXT = new Set([
|
||||
'mp4', 'avi', 'mkv', 'mov', '3gp', 'mpeg', 'rmvb', 'rm', 'wmv', 'flv', 'asf', 'webm', 'mpg', 'vob', 'm4v', 'f4v',
|
||||
]);
|
||||
const FLASH_ARCHIVE_EXT = new Set(['zip', 'rar', 'tar', 'bz2', 'xz', 'tgz', 'gz', '7z']);
|
||||
const FLASH_MODEL_EXT = new Set(['pt', 'pth', 'onnx', 'model', 'mlmodel']);
|
||||
|
||||
/** 0x93cf f3 粗类:压缩包走 2/6,其余按媒体类 7。 */
|
||||
function flashApplyTypeCode(ext: string): number {
|
||||
if (ext === 'zip') return 6;
|
||||
if (FLASH_ARCHIVE_EXT.has(ext)) return 2;
|
||||
return 7;
|
||||
}
|
||||
|
||||
/**
|
||||
* 0x93d0 / 0x12a9 格式码。与 QQ 客户端按扩展名判定的图标类型一致:
|
||||
* 图片 26、音频 1、视频 2、文档 3、压缩包 4、未知 11。
|
||||
*/
|
||||
function flashFormatCode(ext: string): number {
|
||||
if (FLASH_IMAGE_EXT.has(ext)) return 26;
|
||||
if (FLASH_AUDIO_EXT.has(ext)) return 1;
|
||||
if (FLASH_VIDEO_EXT.has(ext)) return 2;
|
||||
if (ext === 'doc' || ext === 'docx') return 3;
|
||||
if (FLASH_ARCHIVE_EXT.has(ext)) return 4;
|
||||
if (ext === 'apk') return 5;
|
||||
if (ext === 'xls' || ext === 'xlsx') return 6;
|
||||
if (ext === 'ppt' || ext === 'pptx') return 7;
|
||||
if (ext === 'html' || ext === 'htm') return 8;
|
||||
if (ext === 'pdf') return 9;
|
||||
if (ext === 'txt') return 10;
|
||||
if (ext === 'psd') return 12;
|
||||
if (FLASH_MODEL_EXT.has(ext)) return 15;
|
||||
if (ext === 'ttf' || ext === 'otf') return 16;
|
||||
if (ext === 'ipa') return 17;
|
||||
if (ext === 'dmg') return 23;
|
||||
if (ext === 'pkg') return 24;
|
||||
if (ext === 'key') return 18;
|
||||
if (ext === 'note') return 19;
|
||||
if (ext === 'numbers') return 20;
|
||||
if (ext === 'pages') return 21;
|
||||
if (ext === 'sketch') return 22;
|
||||
if (ext === 'exe') return 27;
|
||||
return 11;
|
||||
}
|
||||
|
||||
/** After create returns, 0x93d4 can still omit the main-file fileId for a
|
||||
* few seconds (#364). Re-query on this schedule (first lookup is immediate). */
|
||||
const FLASH_FILE_ID_RETRY_DELAYS_MS = [1000, 2000, 4000, 4000] as const;
|
||||
|
||||
/** Fail cleanly if the staged file changed since the streaming hash pass. */
|
||||
async function assertUnchanged(filePath: string, baseline: { size: number; mtimeMs: number }): Promise<void> {
|
||||
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 flashStageMaxBytes(source: string): number {
|
||||
return inlineBase64Payload(source) !== null
|
||||
? FLASH_TRANSFER_INLINE_MAX_BYTES
|
||||
: FLASH_TRANSFER_MAX_BYTES;
|
||||
}
|
||||
|
||||
interface StagedFlashItem {
|
||||
filePath: string;
|
||||
fileSize: number;
|
||||
fileName: string;
|
||||
fileUuid: string;
|
||||
fileIndex: number;
|
||||
formatCode: number;
|
||||
guardStat: { size: number; mtimeMs: number };
|
||||
cleanup(): Promise<void>;
|
||||
}
|
||||
|
||||
/** One create_flash_task source: a path/URL, or a path plus a display name. */
|
||||
export type FlashTaskFileInput = string | { file: string; name?: string };
|
||||
|
||||
function flashFileDisplayName(override: string | undefined, fallback: string): string {
|
||||
const cleaned = (override ?? '').replace(/[/\\]/g, '_').trim();
|
||||
return cleaned || fallback;
|
||||
}
|
||||
|
||||
function normalizeFlashTaskInputs(
|
||||
files: FlashTaskFileInput | FlashTaskFileInput[],
|
||||
): { file: string; name?: string }[] {
|
||||
const list = Array.isArray(files) ? files : [files];
|
||||
return list.map((item) => (typeof item === 'string' ? { file: item } : item));
|
||||
}
|
||||
|
||||
/** 闪传文件信息(业务层,从 FlashFileEntry 转换)。 */
|
||||
export interface FlashFileInfo {
|
||||
filesetUuid: string;
|
||||
@@ -49,6 +152,99 @@ function entryToInfo(e: FlashFileEntry): FlashFileInfo {
|
||||
};
|
||||
}
|
||||
|
||||
const QFILE_SHARE_ORIGIN = 'https://qfile.qq.com';
|
||||
const QFILE_SHARE_PAGE_MAX_BYTES = 2 * 1024 * 1024;
|
||||
const QFILE_SHARE_TIMEOUT_MS = 20_000;
|
||||
|
||||
function officialQfileShareUrl(input: string): string {
|
||||
const value = input.trim();
|
||||
if (!value) throw new Error('get_fileset_id: share code is empty');
|
||||
|
||||
let code = value;
|
||||
if (/^[a-z][a-z\d+.-]*:/i.test(value) || value.startsWith('//')) {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(value);
|
||||
} catch (error) {
|
||||
throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error });
|
||||
}
|
||||
if (
|
||||
parsed.protocol !== 'https:'
|
||||
|| parsed.hostname !== 'qfile.qq.com'
|
||||
|| parsed.port !== ''
|
||||
|| parsed.username !== ''
|
||||
|| parsed.password !== ''
|
||||
) {
|
||||
throw new Error('get_fileset_id: expected an official QQ share URL');
|
||||
}
|
||||
const match = /^\/q\/([^/]+)\/?$/.exec(parsed.pathname);
|
||||
if (!match) throw new Error('get_fileset_id: expected an official QQ share URL');
|
||||
try {
|
||||
code = decodeURIComponent(match[1]);
|
||||
} catch (error) {
|
||||
throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
const hasForbiddenCharacter = Array.from(code).some((char) => {
|
||||
const codePoint = char.codePointAt(0) ?? 0;
|
||||
return codePoint <= 0x20 || codePoint === 0x7f || '/\\?#'.includes(char);
|
||||
});
|
||||
if (code.length > 256 || hasForbiddenCharacter) {
|
||||
throw new Error('get_fileset_id: invalid share code');
|
||||
}
|
||||
return `${QFILE_SHARE_ORIGIN}/q/${encodeURIComponent(code)}`;
|
||||
}
|
||||
|
||||
async function rejectShareResponse(response: Response, error: Error): Promise<never> {
|
||||
try {
|
||||
await response.body?.cancel(error);
|
||||
} catch (cleanupError) {
|
||||
throw new AggregateError([error, cleanupError], error.message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
async function readSharePage(response: Response): Promise<string> {
|
||||
const declaredLength = response.headers.get('content-length');
|
||||
if (declaredLength !== null) {
|
||||
if (!/^\d+$/.test(declaredLength)) {
|
||||
await rejectShareResponse(response, new Error('get_fileset_id: invalid response length'));
|
||||
}
|
||||
if (Number(declaredLength) > QFILE_SHARE_PAGE_MAX_BYTES) {
|
||||
await rejectShareResponse(response, new Error('get_fileset_id: share page too large'));
|
||||
}
|
||||
}
|
||||
if (!response.body) throw new Error('get_fileset_id: share page response has no body');
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let total = 0;
|
||||
let html = '';
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > QFILE_SHARE_PAGE_MAX_BYTES) {
|
||||
const error = new Error('get_fileset_id: share page too large');
|
||||
try {
|
||||
await reader.cancel(error);
|
||||
} catch (cleanupError) {
|
||||
throw new AggregateError([error, cleanupError], error.message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
html += decoder.decode(value, { stream: true });
|
||||
}
|
||||
html += decoder.decode();
|
||||
return html;
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
// 手写 PNG 编码(zlib 压缩,避免引入图像库)。缩略图用随机纯色,每次 SHA1 不同,
|
||||
// 避免命中服务端秒传缓存。
|
||||
const CRC_TABLE: Uint32Array = (() => {
|
||||
@@ -123,21 +319,30 @@ export class FlashTransferApi {
|
||||
* 多文件时每条 f6=序号、f14=主文件 fileId),按 fileIndex 选中后走 0x12a9 sub=200
|
||||
* 拿主文件直链。0x93d3/0x93d4 的 downloadUrl 字段是缩略图(appid=14903/14902),
|
||||
* 主文件必须走 0x12a9 sub=200。
|
||||
*
|
||||
* create 刚返回时 f14 可能还是空的(#364)。fileId 空则按
|
||||
* FLASH_FILE_ID_RETRY_DELAYS_MS 再问 0x93d4;已经有 fileId 后 0x12a9 只打一枪。
|
||||
*/
|
||||
private async getFileDownload(
|
||||
filesetUuid: string, fileIndex: number = 1,
|
||||
): Promise<{ url: string; fileName: string; fileSize: number } | null> {
|
||||
const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid });
|
||||
const meta = metas.find((m) => m.fileIndex === fileIndex);
|
||||
if (!meta || !meta.fileId) return null;
|
||||
const url = await GetFlashDownload.invoke(this.ctx, {
|
||||
filesetUuid: meta.filesetUuid,
|
||||
fileUuid: meta.fileUuid,
|
||||
fileId: meta.fileId,
|
||||
fileName: meta.fileName,
|
||||
});
|
||||
if (!url) return null;
|
||||
return { url, fileName: meta.fileName, fileSize: meta.fileSize };
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const metas = await GetDownloadUrl.invoke(this.ctx, { filesetUuid });
|
||||
const meta = metas.find((m) => m.fileIndex === fileIndex);
|
||||
if (meta?.fileId) {
|
||||
const url = await GetFlashDownload.invoke(this.ctx, {
|
||||
filesetUuid: meta.filesetUuid,
|
||||
fileUuid: meta.fileUuid,
|
||||
fileId: meta.fileId,
|
||||
fileName: meta.fileName,
|
||||
});
|
||||
if (!url) return null;
|
||||
return { url, fileName: meta.fileName, fileSize: meta.fileSize };
|
||||
}
|
||||
const delay = FLASH_FILE_ID_RETRY_DELAYS_MS[attempt];
|
||||
if (delay === undefined) return null;
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -207,10 +412,26 @@ export class FlashTransferApi {
|
||||
* 接口数据),直接 GET + 正则提取即可,无需复刻带签名的 trpc 调用。
|
||||
*/
|
||||
async getFilesetIdByCode(shareCode: string): Promise<string> {
|
||||
const url = /^https?:\/\//i.test(shareCode) ? shareCode : `https://qfile.qq.com/q/${shareCode}`;
|
||||
const resp = await fetch(url);
|
||||
if (!resp.ok) throw new Error(`get_fileset_id: HTTP ${resp.status}`);
|
||||
const html = await resp.text();
|
||||
const url = officialQfileShareUrl(shareCode);
|
||||
let resp: Response;
|
||||
try {
|
||||
resp = await fetch(url, {
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(QFILE_SHARE_TIMEOUT_MS),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {
|
||||
throw new Error('get_fileset_id: share page request timed out', { cause: error });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (resp.status >= 300 && resp.status < 400) {
|
||||
await rejectShareResponse(resp, new Error('get_fileset_id: share page redirect is not allowed'));
|
||||
}
|
||||
if (!resp.ok) {
|
||||
await rejectShareResponse(resp, new Error(`get_fileset_id: HTTP ${resp.status}`));
|
||||
}
|
||||
const html = await readSharePage(resp);
|
||||
// 网页里 fileset_id 以 JSON 嵌入(引号可能被转义为 \"),正则兼容两种形态。
|
||||
const m = /fileset_id\\?"\s*:\s*\\?"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec(html);
|
||||
if (!m) throw new Error('get_fileset_id: fileset_id not found in share page');
|
||||
@@ -220,21 +441,13 @@ export class FlashTransferApi {
|
||||
// ─────────────── 文件上传 ───────────────
|
||||
|
||||
/**
|
||||
* 文件扩展名 → 闪传类型码映射。typeCode 用于 0x93cf f3,formatCode 用于
|
||||
* 0x93d0 commit f7 与 0x12a9 filesetWrap.f7(两者同值)。mp4 → 2,rar/zip → 4。
|
||||
* 未知扩展名按媒体类处理(formatCode=2),服务端按文件名扩展名判定。
|
||||
* 文件扩展名 → 闪传类型码。typeCode 用于 0x93cf f3(卡片粗类:压缩包/媒体);
|
||||
* formatCode 用于 0x93d0 commit f7 与 0x12a9 filesetWrap.f7,决定对端图标
|
||||
* (png=26,mp4=2,zip=4,未知=11)。
|
||||
*/
|
||||
private static fileTypeCode(fileName: string): { typeCode: number; formatCode: number } {
|
||||
const ext = fileName.toLowerCase().match(/\.([^.]+)$/)?.[1] ?? '';
|
||||
switch (ext) {
|
||||
case 'rar': return { typeCode: 2, formatCode: 4 };
|
||||
case 'zip': return { typeCode: 6, formatCode: 4 };
|
||||
case '7z': case 'gz': case 'tar': case 'bz2': return { typeCode: 2, formatCode: 4 };
|
||||
case 'png': case 'jpg': case 'jpeg': case 'bmp': case 'gif': case 'webp':
|
||||
case 'mp4': case 'mov': case 'avi': case 'mkv':
|
||||
return { typeCode: 7, formatCode: 2 };
|
||||
default: return { typeCode: 7, formatCode: 2 };
|
||||
}
|
||||
return { typeCode: flashApplyTypeCode(ext), formatCode: flashFormatCode(ext) };
|
||||
}
|
||||
|
||||
/** 构造 sub=103 的 fileId(客户端生成的 protobuf,base64url 编码)。
|
||||
@@ -268,11 +481,21 @@ export class FlashTransferApi {
|
||||
* 多文件:0x93d0 的 f4 是 repeated,一个 commit 请求同时携带 fileset 内所有文件
|
||||
* 条目,每条 f6=文件序号(1,2,3...)。commit 在上传前只发一次,之后 complete →
|
||||
* 逐个 prepare/apply/sliceupload。prepare/apply 的 filesetWrap.f4 必须与 commit
|
||||
* 的 f6 一致,否则文件不计入 fileset。多文件时 ApplyFileset 的 fileName 用
|
||||
* 「<首文件名>等N个文件」、fileSize 用总和——服务端据此判定 fileset 为多文件。
|
||||
* 的 f6 一致,否则文件不计入 fileset。ApplyFileset 的 fileName 是 fileset 显示名
|
||||
* (卡片标题):有 name 用 name,否则单文件用首文件名、多文件用「<首文件名>等N个文件」。
|
||||
* fileSize 用总和——服务端据此判定 fileset 为多文件。各文件在 commit 里用
|
||||
* 条目上的 name(若有),否则用路径 basename。
|
||||
*
|
||||
* 源文件经 stageSourceToDisk 落到本地路径后流式哈希 / 分片读取,不再经
|
||||
* loadBinarySource 整文件进内存。本地与 HTTP 上限与群文件相同(4 GiB);
|
||||
* 内联 base64 仍按 1 GiB 封顶,因为 stage 解码时会占用等量 RAM。
|
||||
*/
|
||||
async createFlashTask(files: string | string[], _name?: string, _thumbPath?: string): Promise<{ filesetId: string }> {
|
||||
const fileList = Array.isArray(files) ? files : [files];
|
||||
async createFlashTask(
|
||||
files: FlashTaskFileInput | FlashTaskFileInput[],
|
||||
name?: string,
|
||||
_thumbPath?: string,
|
||||
): Promise<{ filesetId: string }> {
|
||||
const fileList = normalizeFlashTaskInputs(files);
|
||||
if (fileList.length === 0) throw new Error('create_flash_task: files is empty');
|
||||
const uploader = {
|
||||
uin: this.ctx.identity.uin,
|
||||
@@ -281,104 +504,127 @@ export class FlashTransferApi {
|
||||
// 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 }[] = [];
|
||||
for (let i = 0; i < fileList.length; i++) {
|
||||
const { bytes, fileName } = await loadBinarySource(fileList[i], 'flash-transfer');
|
||||
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
|
||||
items.push({ bytes: new Uint8Array(bytes), fileName, fileUuid: randomUUID(), fileIndex: i + 1, formatCode });
|
||||
const items: StagedFlashItem[] = [];
|
||||
try {
|
||||
for (let i = 0; i < fileList.length; i++) {
|
||||
const source = fileList[i]!.file;
|
||||
if (!source) throw new Error('create_flash_task: files is empty');
|
||||
const staged = await stageSourceToDisk(source, flashStageMaxBytes(source));
|
||||
const fileName = flashFileDisplayName(fileList[i]!.name, staged.fileName);
|
||||
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
|
||||
items.push({
|
||||
filePath: staged.filePath,
|
||||
fileSize: staged.fileSize,
|
||||
fileName,
|
||||
fileUuid: randomUUID(),
|
||||
fileIndex: i + 1,
|
||||
formatCode,
|
||||
guardStat: await fsp.stat(staged.filePath),
|
||||
cleanup: () => staged.cleanup(),
|
||||
});
|
||||
if (staged.fileSize === 0) throw new Error('create_flash_task: file is empty');
|
||||
}
|
||||
// 申请 fileset。fileName 是卡片/面板上的 fileset 标题;各文件真实名走 commit。
|
||||
// 未指定 name 时,多文件用「<首文件名>等N个文件」、fileSize 用总和,
|
||||
// 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。
|
||||
const first = items[0];
|
||||
const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName);
|
||||
const isMulti = items.length > 1;
|
||||
const filesetName = name?.trim()
|
||||
|| (isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName);
|
||||
const totalSize = items.reduce((s, it) => s + it.fileSize, 0);
|
||||
const apply = await ApplyFileset.invoke(this.ctx, {
|
||||
fileName: filesetName, origName: filesetName,
|
||||
fileSize: totalSize, typeCode, uploader,
|
||||
});
|
||||
const filesetUuid = apply.filesetUuid;
|
||||
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
|
||||
// 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号)
|
||||
const commitEntries = items.map((it) => ({
|
||||
fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName,
|
||||
fileSize: it.fileSize, formatCode: it.formatCode, fileIndex: it.fileIndex,
|
||||
}));
|
||||
await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries });
|
||||
await CompleteFileset.invoke(this.ctx, { filesetUuid });
|
||||
// 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。
|
||||
const prepared: { it: StagedFlashItem; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
|
||||
for (const it of items) {
|
||||
const p = await this.prepareAndApply(filesetUuid, it);
|
||||
if (p) prepared.push({ it, ...p });
|
||||
}
|
||||
for (const p of prepared) {
|
||||
await assertUnchanged(p.it.filePath, p.it.guardStat);
|
||||
await this.sliceuploadFile(
|
||||
p.it.filePath, p.it.fileSize, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName,
|
||||
);
|
||||
}
|
||||
// fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联
|
||||
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1);
|
||||
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2);
|
||||
await SetFilesetStatus.invoke(this.ctx, { filesetUuid });
|
||||
return { filesetId: filesetUuid };
|
||||
} finally {
|
||||
await Promise.all(items.map((it) => it.cleanup()));
|
||||
}
|
||||
// 申请 fileset。多文件时 fileName 用「<首文件名>等N个文件」、fileSize 用总和,
|
||||
// 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。
|
||||
const first = items[0];
|
||||
const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName);
|
||||
const isMulti = items.length > 1;
|
||||
const filesetName = isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName;
|
||||
const totalSize = items.reduce((s, it) => s + it.bytes.length, 0);
|
||||
const apply = await ApplyFileset.invoke(this.ctx, {
|
||||
fileName: filesetName, origName: filesetName,
|
||||
fileSize: totalSize, typeCode, uploader,
|
||||
});
|
||||
const filesetUuid = apply.filesetUuid;
|
||||
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
|
||||
// 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号)
|
||||
const commitEntries = items.map((it) => ({
|
||||
fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName,
|
||||
fileSize: it.bytes.length, formatCode: it.formatCode, fileIndex: it.fileIndex,
|
||||
}));
|
||||
await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries });
|
||||
await CompleteFileset.invoke(this.ctx, { filesetUuid });
|
||||
// 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。
|
||||
const prepared: { it: typeof items[0]; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
|
||||
for (const it of items) {
|
||||
const p = await this.prepareAndApply(filesetUuid, it.bytes, it.fileName, it.fileUuid, it.fileIndex, it.formatCode);
|
||||
if (p) prepared.push({ it, ...p });
|
||||
}
|
||||
for (const p of prepared) {
|
||||
await this.sliceuploadFile(p.it.bytes, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName);
|
||||
}
|
||||
// fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联
|
||||
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1);
|
||||
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2);
|
||||
await SetFilesetStatus.invoke(this.ctx, { filesetUuid });
|
||||
return { filesetId: filesetUuid };
|
||||
}
|
||||
|
||||
/**
|
||||
* 阶段1:prepare(拿 rkey)+ apply(注册 fileId)。返回 sliceupload 所需的 rkey/sha1state。
|
||||
* 秒传(rkey=null)返回 null,调用方跳过 sliceupload。
|
||||
* 阶段1:流式哈希 + prepare(拿 rkey)+ apply(注册 fileId)。
|
||||
* 秒传时 prepare 不回 rkey,仍必须 apply,否则 fileset 会一直停在等待上传;
|
||||
* 返回 null 只表示调用方跳过 sliceupload。
|
||||
*/
|
||||
private async prepareAndApply(
|
||||
filesetUuid: string, bytes: Uint8Array, fileName: string, fileUuid: string, fileIndex: number, formatCode: number,
|
||||
filesetUuid: string, it: StagedFlashItem,
|
||||
): Promise<{ rkey: string; sha1StateV: Uint8Array[]; sliceCount: number } | null> {
|
||||
const fileSize = bytes.length;
|
||||
const hashes = computeHashes(bytes);
|
||||
const SLICE_SIZE = 1024 * 1024;
|
||||
const sliceCount = Math.ceil(fileSize / SLICE_SIZE);
|
||||
const sha1StateV = computeSha1StateV(bytes, sliceCount, SLICE_SIZE);
|
||||
const hashes = await hashFlashFileStreaming(it.filePath);
|
||||
await assertUnchanged(it.filePath, it.guardStat);
|
||||
|
||||
const rkey = await PrepareUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex, fileIndex, formatCode,
|
||||
filesetUuid, fileUuid: it.fileUuid, fileName: it.fileName, fileSize: it.fileSize,
|
||||
sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
|
||||
});
|
||||
if (rkey === null) return null; // 秒传
|
||||
|
||||
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize);
|
||||
const fileId = FlashTransferApi.buildFileId(hashes.sha1, it.fileSize);
|
||||
await ApplyUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileId, fileName, fileSize,
|
||||
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode,
|
||||
filesetUuid, fileUuid: it.fileUuid, fileId, fileName: it.fileName, fileSize: it.fileSize,
|
||||
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
|
||||
});
|
||||
return { rkey, sha1StateV, sliceCount };
|
||||
if (rkey === null) return null;
|
||||
return { rkey, sha1StateV: hashes.sha1StateV, sliceCount: hashes.sliceCount };
|
||||
}
|
||||
|
||||
/**
|
||||
* 阶段2:sliceupload 分片上传(所有文件 prepare+apply 完成后调用)。
|
||||
* 阶段2:从磁盘按 1 MiB 切片 POST sliceupload(所有文件 prepare+apply 完成后调用)。
|
||||
*/
|
||||
private async sliceuploadFile(
|
||||
bytes: Uint8Array, rkey: string, sha1StateV: Uint8Array[], sliceCount: number, fileName: string,
|
||||
filePath: string, fileSize: number, rkey: string,
|
||||
sha1StateV: Uint8Array[], sliceCount: number, fileName: string,
|
||||
): Promise<void> {
|
||||
const fileSize = bytes.length;
|
||||
const SLICE_SIZE = 1024 * 1024;
|
||||
for (let i = 0; i < sliceCount; i++) {
|
||||
const start = i * SLICE_SIZE;
|
||||
const chunk = bytes.subarray(start, Math.min(start + SLICE_SIZE, fileSize));
|
||||
const chunkLen = chunk.length;
|
||||
const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest());
|
||||
const body: FlashSliceUploadBody = {
|
||||
field1: 0,
|
||||
appid: 14901,
|
||||
field3: 2,
|
||||
payload: {
|
||||
field1: {},
|
||||
rkey,
|
||||
start,
|
||||
end: start + chunkLen - 1,
|
||||
sha1: chunkSha1,
|
||||
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
|
||||
chunk: new Uint8Array(chunk),
|
||||
},
|
||||
};
|
||||
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
|
||||
await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`);
|
||||
const src = await FileChunkSource.open(filePath, fileSize);
|
||||
try {
|
||||
for (let i = 0; i < sliceCount; i++) {
|
||||
const start = i * FLASH_SLICE_SIZE;
|
||||
const chunkLen = Math.min(FLASH_SLICE_SIZE, fileSize - start);
|
||||
const chunk = await src.read(start, chunkLen);
|
||||
const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest());
|
||||
const body: FlashSliceUploadBody = {
|
||||
field1: 0,
|
||||
appid: 14901,
|
||||
field3: 2,
|
||||
payload: {
|
||||
field1: {},
|
||||
rkey,
|
||||
start,
|
||||
end: start + chunkLen - 1,
|
||||
sha1: chunkSha1,
|
||||
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
|
||||
chunk: new Uint8Array(chunk),
|
||||
},
|
||||
};
|
||||
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
|
||||
await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`);
|
||||
}
|
||||
} finally {
|
||||
await src.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -432,12 +678,12 @@ export class FlashTransferApi {
|
||||
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex,
|
||||
fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
|
||||
});
|
||||
if (rkey === null) return; // 秒传
|
||||
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize, appid);
|
||||
await ApplyUpload.invoke(this.ctx, {
|
||||
filesetUuid, fileUuid, fileId, fileName, fileSize,
|
||||
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode: thumbFormatCode, thumbType, width, height,
|
||||
});
|
||||
if (rkey === null) return;
|
||||
// sliceupload(缩略图小,1 片,Sha1StateV=[标准 SHA1])
|
||||
const sha1StateV = computeSha1StateV(new Uint8Array(thumbBytes), 1, fileSize);
|
||||
const body: FlashSliceUploadBody = {
|
||||
|
||||
@@ -233,16 +233,9 @@ function previewFromElements(elements: MessageElement[]): string {
|
||||
|
||||
function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload {
|
||||
return {
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
...node,
|
||||
elements,
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
innerForward: node.innerForward,
|
||||
news: node.news?.map(item => ({ ...item })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -478,23 +471,21 @@ export class ForwardApi {
|
||||
type: 'forward',
|
||||
resId: inner.resId,
|
||||
forwardUuid: inner.uuid,
|
||||
forwardSource: deriveInnerSource(node.innerForward, isGroup),
|
||||
forwardSummary: `查看${node.innerForward.length}条转发消息`,
|
||||
forwardPrompt: '[聊天记录]',
|
||||
forwardNews: previewLinesFromNodes(node.innerForward),
|
||||
forwardSource: node.source && node.source.length > 0
|
||||
? node.source
|
||||
: deriveInnerSource(node.innerForward, isGroup),
|
||||
forwardSummary: node.summary && node.summary.length > 0
|
||||
? node.summary
|
||||
: `查看${node.innerForward.length}条转发消息`,
|
||||
forwardPrompt: node.prompt && node.prompt.length > 0
|
||||
? node.prompt
|
||||
: '[聊天记录]',
|
||||
forwardNews: node.news && node.news.length > 0 ? node.news : previewLinesFromNodes(node.innerForward),
|
||||
forwardTSum: node.innerForward.length,
|
||||
};
|
||||
processedNodes.push({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [previewElement],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
});
|
||||
const processed = cloneNodeWithElements(node, [previewElement]);
|
||||
delete processed.innerForward;
|
||||
processedNodes.push(processed);
|
||||
} else {
|
||||
processedNodes.push(node);
|
||||
}
|
||||
@@ -548,14 +539,8 @@ export class ForwardApi {
|
||||
}
|
||||
|
||||
forwardResCache.set(resId, uploadReadyNodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
|
||||
groupId: node.groupId ?? groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
|
||||
})));
|
||||
|
||||
@@ -579,17 +564,7 @@ export class ForwardApi {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cached = forwardResCache.get(resId);
|
||||
if (cached) {
|
||||
const nodes = cached.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
}));
|
||||
const nodes = cloneNodes(cached);
|
||||
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
|
||||
// on read (a no-op once names are present) and persist so later hits skip.
|
||||
if (await this.enrichSenders(nodes)) forwardResCache.set(resId, cloneNodes(nodes));
|
||||
@@ -854,16 +829,14 @@ export class ForwardApi {
|
||||
}
|
||||
}
|
||||
|
||||
function cacheableForwardElement(element: MessageElement): MessageElement {
|
||||
if (element.type !== 'image') return element;
|
||||
if (element.imageUrl || element.fileId || element.md5Hex) return element;
|
||||
const source = (element.url ?? '').trim();
|
||||
if (!source) return element;
|
||||
return { ...element, imageUrl: source };
|
||||
}
|
||||
|
||||
function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] {
|
||||
return nodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
}));
|
||||
return nodes.map(node => cloneNodeWithElements(node, [...node.elements]));
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-contacts';
|
||||
import { ApproveDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/approve-doubt-buddy-req';
|
||||
import { ClearFriendRemark } from '@snowluma/protocol/oidb-services/friend/clear-friend-remark';
|
||||
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
|
||||
@@ -24,6 +25,9 @@ export class FriendApi {
|
||||
}
|
||||
|
||||
async delete(userId: number, block = false): Promise<void> {
|
||||
if (findDatalineDeviceByUin(userId)) {
|
||||
throw new Error('this contact cannot be deleted');
|
||||
}
|
||||
await DeleteFriend.invoke(this.ctx, { userId, block });
|
||||
|
||||
// The server-side delete has already completed. A refresh failure must be
|
||||
@@ -40,25 +44,66 @@ export class FriendApi {
|
||||
}
|
||||
}
|
||||
|
||||
setRemark(userId: number, remark: string): Promise<void> {
|
||||
if (remark === '') {
|
||||
return ClearFriendRemark.invoke(this.ctx, { userId });
|
||||
async setRemark(userId: number, remark: string): Promise<void> {
|
||||
if (findDatalineDeviceByUin(userId)) {
|
||||
throw new Error('this contact does not support remarks');
|
||||
}
|
||||
return SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||
if (remark === '') {
|
||||
await ClearFriendRemark.invoke(this.ctx, { userId });
|
||||
return;
|
||||
}
|
||||
await SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||
}
|
||||
|
||||
/** List doubtful friend-add requests (可能认识的人). */
|
||||
getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
|
||||
return GetDoubtBuddyReq.invoke(this.ctx, { count });
|
||||
async getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
|
||||
const list = await GetDoubtBuddyReq.invoke(this.ctx, { count });
|
||||
return Promise.all(list.map(async (item) => {
|
||||
let uid = item.uid;
|
||||
let userId = item.user_id;
|
||||
if (userId <= 0 && uid) {
|
||||
userId = this.ctx.identity.findUinByUid(uid) ?? 0;
|
||||
}
|
||||
// Applicants need not be friends or share a group. Use Identity's
|
||||
// profile lookup when the list only supplies an account number.
|
||||
if (!uid && userId > 0) {
|
||||
try {
|
||||
uid = await this.ctx.resolveUserUid(userId);
|
||||
} catch (err: unknown) {
|
||||
log.warn(
|
||||
'doubt-request uid resolve failed: user=%d err=%s',
|
||||
userId,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
return { ...item, uid: uid || '', user_id: userId };
|
||||
}));
|
||||
}
|
||||
|
||||
/** Approve a doubtful friend-add request by its uid (the list item's flag). */
|
||||
approveDoubtRequest(uid: string): Promise<void> {
|
||||
return ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
/** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */
|
||||
async approveDoubtRequest(uidOrFlag: string): Promise<void> {
|
||||
log.trace('doubt-request approval: resolving applicant');
|
||||
const uid = await this.resolveDoubtFlag(uidOrFlag);
|
||||
log.trace('doubt-request approval: submitting request');
|
||||
await ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
log.trace('doubt-request approval: completed');
|
||||
}
|
||||
|
||||
/** Reject (delete/decline) a doubtful friend-add request by its uid. */
|
||||
rejectDoubtRequest(uid: string): Promise<void> {
|
||||
return RejectDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
/** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */
|
||||
async rejectDoubtRequest(uidOrFlag: string): Promise<void> {
|
||||
return RejectDoubtBuddyReq.invoke(this.ctx, {
|
||||
uid: await this.resolveDoubtFlag(uidOrFlag),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Digit-only flags are account numbers and must be translated before the
|
||||
* approval/reject packet is built. A raw number in that packet is rejected
|
||||
* by the server. Same rule as inbound friend-request handling.
|
||||
*/
|
||||
private resolveDoubtFlag(uidOrFlag: string): Promise<string> {
|
||||
if (!/^\d+$/.test(uidOrFlag)) return Promise.resolve(uidOrFlag);
|
||||
return this.ctx.resolveUserUid(parseInt(uidOrFlag, 10));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { GetAtAllRemain } from '@snowluma/protocol/oidb-services/group-admin/get-at-all-remain';
|
||||
import { FetchGroupDetail } from '@snowluma/protocol/oidb-services/contacts/fetch-group-detail';
|
||||
import { KickMember } from '@snowluma/protocol/oidb-services/group-admin/kick-member';
|
||||
import { KickMembers } from '@snowluma/protocol/oidb-services/group-admin/kick-members';
|
||||
import { LeaveGroup } from '@snowluma/protocol/oidb-services/group-admin/leave-group';
|
||||
@@ -10,11 +11,59 @@ import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin
|
||||
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
|
||||
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
|
||||
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
|
||||
import { FetchGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/get-group-ext-info';
|
||||
import {
|
||||
decodeMemberInvitePolicy,
|
||||
MEMBER_INVITE_PRIVILEGE_MASK,
|
||||
mergeMemberInvitePrivilegeFlag,
|
||||
SetMemberInvitePolicy,
|
||||
type GroupMemberInvitePolicy,
|
||||
} from '@snowluma/protocol/oidb-services/group-admin/set-member-invite-policy';
|
||||
import {
|
||||
decodeGroupHistoryVisibility,
|
||||
SetNewMemberHistoryVisibility,
|
||||
} from '@snowluma/protocol/oidb-services/group-admin/set-new-member-history-visibility';
|
||||
import {
|
||||
decodeGroupMemberPermissions,
|
||||
GROUP_MEMBER_PERMISSION_MASKS,
|
||||
mergeGroupMemberPermission,
|
||||
SetMemberPermission,
|
||||
type GroupMemberPermission,
|
||||
} from '@snowluma/protocol/oidb-services/group-admin/set-member-permission';
|
||||
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
|
||||
import { GetGroupCategoryTags } from '@snowluma/protocol/oidb-services/group-admin/get-group-category-tags';
|
||||
import { AddGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/add-group-category-tag';
|
||||
import { DeleteGroupCategoryTag } from '@snowluma/protocol/oidb-services/group-admin/delete-group-category-tag';
|
||||
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
|
||||
import { ModifyGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/modify-group-ext-info';
|
||||
import { OidbError } from '@snowluma/protocol/oidb-service';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
/** QQ only accepts this write from the group owner (#411). */
|
||||
export const MEMBER_PERMISSIONS_OWNER_ONLY =
|
||||
'only the group owner can change group member permissions';
|
||||
|
||||
export type GroupAdminSettings = {
|
||||
add_type: number;
|
||||
group_question: string;
|
||||
group_answer: string;
|
||||
robot_member_switch: number;
|
||||
robot_member_examine: number;
|
||||
member_invite_policy: GroupMemberInvitePolicy;
|
||||
allow_member_upload_album: boolean;
|
||||
allow_member_temporary_session: boolean;
|
||||
allow_member_create_group: boolean;
|
||||
new_member_history_visible: boolean;
|
||||
no_finger_open: number;
|
||||
no_code_finger_open: number;
|
||||
};
|
||||
|
||||
export interface GroupMemberPermissions {
|
||||
allowMemberUploadAlbum?: boolean;
|
||||
allowMemberTemporarySession?: boolean;
|
||||
allowMemberCreateGroup?: boolean;
|
||||
}
|
||||
|
||||
export class GroupAdminApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
@@ -23,6 +72,33 @@ export class GroupAdminApi {
|
||||
return ModifyGroupExtInfo.invoke(this.ctx, { groupId, robotMemberSwitch, robotMemberExamine });
|
||||
}
|
||||
|
||||
async getAdminSettings(groupId: number): Promise<GroupAdminSettings> {
|
||||
const [detail, robot] = await Promise.all([
|
||||
FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }),
|
||||
FetchGroupExtInfo.invoke(this.ctx, { groupId }),
|
||||
]);
|
||||
const results = detail.groupInfo?.results;
|
||||
if (!results) {
|
||||
throw new Error(`unable to read group admin settings for group ${groupId}`);
|
||||
}
|
||||
const privilegeFlag = results.privilegeFlag ?? 0;
|
||||
const permissions = decodeGroupMemberPermissions(privilegeFlag);
|
||||
return {
|
||||
add_type: results.addType ?? 0,
|
||||
group_question: results.question ?? '',
|
||||
group_answer: results.answer ?? '',
|
||||
robot_member_switch: robot.robotMemberSwitch,
|
||||
robot_member_examine: robot.robotMemberExamine,
|
||||
member_invite_policy: decodeMemberInvitePolicy(privilegeFlag),
|
||||
allow_member_upload_album: permissions.allowMemberUploadAlbum,
|
||||
allow_member_temporary_session: permissions.allowMemberTemporarySession,
|
||||
allow_member_create_group: permissions.allowMemberCreateGroup,
|
||||
new_member_history_visible: decodeGroupHistoryVisibility(results.groupFlagExt4 ?? 0),
|
||||
no_finger_open: results.noFingerOpen ?? 0,
|
||||
no_code_finger_open: results.noCodeFingerOpen ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
|
||||
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
|
||||
}
|
||||
@@ -31,19 +107,154 @@ export class GroupAdminApi {
|
||||
return MuteAll.invoke(this.ctx, { groupId, enable });
|
||||
}
|
||||
|
||||
setAddOption(groupId: number, addType: number): Promise<void> {
|
||||
return SetAddOption.invoke(this.ctx, { groupId, addType });
|
||||
setAddOption(
|
||||
groupId: number,
|
||||
addType: number,
|
||||
groupQuestion?: string,
|
||||
groupAnswer?: string,
|
||||
): Promise<void> {
|
||||
return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer });
|
||||
}
|
||||
|
||||
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
|
||||
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
|
||||
}
|
||||
|
||||
listCategoryTags(groupClass: number): Promise<{ tags: { id: number; name: string; type: number }[] }> {
|
||||
return GetGroupCategoryTags.invoke(this.ctx, { groupClass });
|
||||
}
|
||||
|
||||
addCategoryTag(groupClass: number, name: string): Promise<void> {
|
||||
return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name });
|
||||
}
|
||||
|
||||
removeCategoryTag(groupClass: number, name: string): Promise<void> {
|
||||
return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name });
|
||||
}
|
||||
|
||||
async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise<void> {
|
||||
const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member invite policy',
|
||||
'before update',
|
||||
);
|
||||
const expectedPrivilegeFlag = mergeMemberInvitePrivilegeFlag(currentPrivilegeFlag, policy);
|
||||
|
||||
await SetMemberInvitePolicy.invoke(this.ctx, {
|
||||
groupId,
|
||||
currentPrivilegeFlag,
|
||||
policy,
|
||||
});
|
||||
|
||||
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member invite policy',
|
||||
'after update',
|
||||
);
|
||||
const mask = BigInt(MEMBER_INVITE_PRIVILEGE_MASK);
|
||||
if ((BigInt(actualPrivilegeFlag) & mask) !== (BigInt(expectedPrivilegeFlag) & mask)) {
|
||||
throw new Error(`group member invite policy was not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchGroupPrivilegeFlag(groupId: number, setting: string, phase: string): Promise<number> {
|
||||
return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag;
|
||||
}
|
||||
|
||||
private async fetchGroupPrivilegeState(
|
||||
groupId: number,
|
||||
setting: string,
|
||||
phase: string,
|
||||
): Promise<{ privilegeFlag: number; ownerUid?: string }> {
|
||||
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const results = detail.groupInfo?.results;
|
||||
if (!results) {
|
||||
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
|
||||
}
|
||||
return {
|
||||
privilegeFlag: results.privilegeFlag ?? 0,
|
||||
ownerUid: results.ownerUid,
|
||||
};
|
||||
}
|
||||
|
||||
async setMemberPermissions(groupId: number, permissions: GroupMemberPermissions): Promise<void> {
|
||||
const updates: ReadonlyArray<readonly [GroupMemberPermission, boolean | undefined]> = [
|
||||
['upload_album', permissions.allowMemberUploadAlbum],
|
||||
['temporary_session', permissions.allowMemberTemporarySession],
|
||||
['create_group', permissions.allowMemberCreateGroup],
|
||||
];
|
||||
if (!updates.some(([, allow]) => allow !== undefined)) {
|
||||
throw new Error('at least one member permission must be specified');
|
||||
}
|
||||
|
||||
const before = await this.fetchGroupPrivilegeState(
|
||||
groupId,
|
||||
'group member permissions',
|
||||
'before update',
|
||||
);
|
||||
const selfUid = this.ctx.identity.selfUid;
|
||||
if (selfUid && before.ownerUid && selfUid !== before.ownerUid) {
|
||||
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
}
|
||||
|
||||
let expectedPrivilegeFlag = before.privilegeFlag;
|
||||
let combinedMask = 0n;
|
||||
|
||||
for (const [permission, allow] of updates) {
|
||||
if (allow === undefined) continue;
|
||||
try {
|
||||
await SetMemberPermission.invoke(this.ctx, {
|
||||
groupId,
|
||||
currentPrivilegeFlag: expectedPrivilegeFlag,
|
||||
permission,
|
||||
allow,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof OidbError && error.code === 1287) {
|
||||
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
expectedPrivilegeFlag = mergeGroupMemberPermission(expectedPrivilegeFlag, permission, allow);
|
||||
combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]);
|
||||
}
|
||||
|
||||
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member permissions',
|
||||
'after update',
|
||||
);
|
||||
if ((BigInt(actualPrivilegeFlag) & combinedMask) !== (BigInt(expectedPrivilegeFlag) & combinedMask)) {
|
||||
throw new Error(`group member permissions were not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
|
||||
async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise<void> {
|
||||
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
|
||||
|
||||
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
|
||||
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
|
||||
throw new Error(`new-member history visibility was not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchGroupFlagExt4(groupId: number, phase: string): Promise<number> {
|
||||
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const results = detail.groupInfo?.results;
|
||||
if (!results) {
|
||||
throw new Error(`unable to read new-member history visibility ${phase} for group ${groupId}`);
|
||||
}
|
||||
return results.groupFlagExt4 ?? 0;
|
||||
}
|
||||
|
||||
setAddRequest(
|
||||
groupId: number, sequence: number, eventType: number,
|
||||
approve: boolean, reason = '', filtered = false,
|
||||
operateTransInfo?: Uint8Array,
|
||||
): Promise<void> {
|
||||
return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered });
|
||||
return SetAddRequest.invoke(this.ctx, {
|
||||
groupId, sequence, eventType, approve, reason, filtered, operateTransInfo,
|
||||
});
|
||||
}
|
||||
|
||||
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { JsonObject, JsonValue } from '@snowluma/common/json';
|
||||
import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type {
|
||||
AlbumCreator,
|
||||
CommentReqBodyHeader,
|
||||
CommentReqPhotoInfo,
|
||||
CommentRespData,
|
||||
DeleteMediasRequest,
|
||||
DeleteMediasResponse,
|
||||
DoQunCommentRequest,
|
||||
@@ -10,19 +14,26 @@ import type {
|
||||
DoQunLikeResponse,
|
||||
GetAlbumListRequest,
|
||||
GetAlbumListResponse,
|
||||
GetQunFeedDetailRequest,
|
||||
GetQunFeedDetailResponse,
|
||||
GroupAlbumInfo as GroupAlbumInfoWire,
|
||||
QunFeedCellCommon,
|
||||
GetMediaListRequest,
|
||||
GetMediaListResponse,
|
||||
MediaInfo,
|
||||
UrlInfo,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-album';
|
||||
import { uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
|
||||
import { uploadImageToGroupAlbum, uploadVideoToGroupAlbum } from '@snowluma/protocol/web/group-album';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
const log = createLogger('Bridge.GroupAlbum');
|
||||
const GET_ALBUM_LIST_CMD = 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetAlbumList';
|
||||
const GET_ALBUM_LIST_SEQ = 3331;
|
||||
const DO_QUN_COMMENT_CMD = 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment';
|
||||
const DO_QUN_COMMENT_SEQ = 8527;
|
||||
const GET_QUN_FEED_DETAIL_CMD = 'QunAlbum.trpc.qzone.webapp_qun_feeds.FeedsReader.GetQunFeedDetail';
|
||||
const GET_QUN_FEED_DETAIL_COMMENT_COUNT = 20;
|
||||
|
||||
function uint64ToString(value: bigint | undefined): string {
|
||||
return (value ?? 0n).toString();
|
||||
@@ -169,7 +180,7 @@ export class GroupAlbumApi {
|
||||
body.length,
|
||||
);
|
||||
|
||||
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, 15000);
|
||||
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, packetTimeoutMs());
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(
|
||||
`get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`,
|
||||
@@ -259,6 +270,13 @@ export class GroupAlbumApi {
|
||||
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
|
||||
}
|
||||
|
||||
async uploadVideo(groupId: number, albumId: string, albumName: string, filePath: string): Promise<{ id: string }> {
|
||||
const groupCode = groupId.toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return uploadVideoToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
|
||||
}
|
||||
|
||||
async getMediaList(groupId: number, albumId: string, attachInfo = ''): Promise<GroupAlbumMediaResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
@@ -280,7 +298,7 @@ export class GroupAlbumApi {
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
|
||||
body,
|
||||
15000,
|
||||
packetTimeoutMs(),
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
@@ -305,38 +323,36 @@ export class GroupAlbumApi {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
const clientKey = Date.now().toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
const resolved = await this.resolveCommentMedia(groupId, albumId, lloc);
|
||||
const batchId = optionalBatchId(resolved?.batchId);
|
||||
if (batchId === undefined) {
|
||||
throw new Error('comment album media error: media not found');
|
||||
}
|
||||
const mediaLloc = commentMediaLloc(resolved, lloc);
|
||||
const feed = await this.getQunFeedDetail(groupId, albumId, batchId, mediaLloc);
|
||||
const ownerUin = feed.ownerUin || resolved?.uploader || '';
|
||||
const photoInfo = commentPhotoInfo(
|
||||
feed.media,
|
||||
mediaInfoForComment(resolved, mediaLloc),
|
||||
albumId,
|
||||
batchId,
|
||||
);
|
||||
|
||||
const body = protobuf_encode<DoQunCommentRequest>({
|
||||
field1: 8527,
|
||||
field1: DO_QUN_COMMENT_SEQ,
|
||||
field2: new Uint8Array(0),
|
||||
field3: new Uint8Array(0),
|
||||
body: {
|
||||
groupId: groupId.toString(),
|
||||
field3: 2,
|
||||
reqBody: {
|
||||
field1: { field3: 0, field4: '' },
|
||||
field2: {
|
||||
field1: { uin },
|
||||
},
|
||||
field5: {
|
||||
field1: {
|
||||
field2: {
|
||||
field1: 0, field2: '',
|
||||
lloc,
|
||||
field4: '', field6: '', field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0,
|
||||
},
|
||||
},
|
||||
albumId,
|
||||
field5: 0,
|
||||
},
|
||||
field1: commentReqHeader(feed.cellCommon),
|
||||
...(ownerUin ? { field2: { field1: { uin: ownerUin } } } : {}),
|
||||
field5: photoInfo,
|
||||
},
|
||||
field5: {
|
||||
field2: { uin },
|
||||
field3: {
|
||||
field1: 0,
|
||||
field2: content,
|
||||
field3: '', field4: '', field5: 0, field6: '',
|
||||
},
|
||||
user: { uin },
|
||||
contents: [{ type: 0, content }],
|
||||
clientKey,
|
||||
},
|
||||
},
|
||||
@@ -344,31 +360,35 @@ export class GroupAlbumApi {
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
|
||||
body,
|
||||
15000,
|
||||
);
|
||||
const result = await this.ctx.sendRawPacket(DO_QUN_COMMENT_CMD, body, packetTimeoutMs());
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to comment on album media');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<DoQunCommentResponse>(result.responseData);
|
||||
|
||||
const resCode = resp.field1;
|
||||
if (resCode !== 0 && resCode !== 8527 && !resp.comment) {
|
||||
throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`);
|
||||
const resultCode = resp.result ?? 0;
|
||||
if (resultCode !== 0) {
|
||||
throw new Error(
|
||||
`comment album media error: retCode ${resultCode}`
|
||||
+ (resp.errorText ? `, ${resp.errorText}` : ''),
|
||||
);
|
||||
}
|
||||
|
||||
const commentData = resp.comment?.data ?? {};
|
||||
const commentData = commentFromResponse(resp);
|
||||
if (!commentData.id) {
|
||||
throw new Error('comment album media error: empty comment');
|
||||
}
|
||||
|
||||
return convertBigIntToString({
|
||||
id: commentData.id ?? '',
|
||||
user: { uin: commentData.user?.uin ?? '' },
|
||||
content: commentData.content ?? [],
|
||||
id: commentData.id,
|
||||
user: { uin: commentData.user?.uin || uin },
|
||||
content: (commentData.content ?? [{ type: 0, content }]).map((item) => ({
|
||||
type: item.type ?? 0,
|
||||
content: item.content ?? '',
|
||||
})),
|
||||
time: commentData.time ?? '0',
|
||||
clientKey: commentData.clientKey ?? '',
|
||||
clientKey: commentData.clientKey || clientKey,
|
||||
}) as unknown as GroupAlbumCommentResult;
|
||||
}
|
||||
|
||||
@@ -379,12 +399,7 @@ export class GroupAlbumApi {
|
||||
const type = isLike ? 2 : 1;
|
||||
const status = isLike ? 0 : 1;
|
||||
|
||||
let id = '';
|
||||
if (lloc) {
|
||||
id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
|
||||
} else {
|
||||
id = `421_1_0_${groupId}|${albumId}|${batchId}`;
|
||||
}
|
||||
const id = qunFeedCellId(groupId, albumId, batchId, lloc);
|
||||
|
||||
const body = protobuf_encode<DoQunLikeRequest>({
|
||||
field1: 5495,
|
||||
@@ -417,7 +432,7 @@ export class GroupAlbumApi {
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
|
||||
body,
|
||||
15000,
|
||||
packetTimeoutMs(),
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
@@ -435,6 +450,7 @@ export class GroupAlbumApi {
|
||||
}
|
||||
|
||||
async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> {
|
||||
const target = await this.resolveDeleteTarget(groupId, albumId, lloc);
|
||||
const uin = this.ctx.identity.uin;
|
||||
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
@@ -445,7 +461,8 @@ export class GroupAlbumApi {
|
||||
body: {
|
||||
groupId: groupId.toString(),
|
||||
albumId,
|
||||
lloc,
|
||||
mediaIds: [target.mediaId],
|
||||
...(target.batchId ? { batchIds: [target.batchId] } : {}),
|
||||
},
|
||||
traceId: clientKey,
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
@@ -454,7 +471,7 @@ export class GroupAlbumApi {
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
|
||||
body,
|
||||
15000,
|
||||
packetTimeoutMs(),
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
@@ -472,7 +489,264 @@ export class GroupAlbumApi {
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Official delete uses a photo lloc, or a video's cover lloc plus batch id.
|
||||
* Callers may pass either an image lloc or a video id; resolve the latter.
|
||||
*/
|
||||
private async resolveDeleteTarget(
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
mediaKey: string,
|
||||
): Promise<{ mediaId: string; batchId?: string }> {
|
||||
try {
|
||||
const seenCursors = new Set<string>();
|
||||
let attachInfo = '';
|
||||
while (true) {
|
||||
const page = await this.getMediaList(groupId, albumId, attachInfo);
|
||||
const hit = findDeleteTarget(page.mediaList, mediaKey);
|
||||
if (hit) return hit;
|
||||
|
||||
const next = page.nextAttachInfo ?? '';
|
||||
if (!next || seenCursors.has(next)) {
|
||||
return { mediaId: mediaKey };
|
||||
}
|
||||
seenCursors.add(next);
|
||||
attachInfo = next;
|
||||
}
|
||||
} catch (err) {
|
||||
log.debug(
|
||||
'resolve album delete target failed, using raw id: group=%d album=%s err=%s',
|
||||
groupId,
|
||||
albumId,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
return { mediaId: mediaKey };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Page the album when the caller only has a lloc / video id, so the
|
||||
* comment can carry the official batch id and media kind.
|
||||
*/
|
||||
private async resolveCommentMedia(
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
mediaKey: string,
|
||||
): Promise<AlbumCommentMediaItem | undefined> {
|
||||
const seenCursors = new Set<string>();
|
||||
let attachInfo = '';
|
||||
while (true) {
|
||||
const page = await this.getMediaList(groupId, albumId, attachInfo);
|
||||
const hit = findCommentMedia(page.mediaList, mediaKey);
|
||||
if (hit) return hit;
|
||||
|
||||
const next = page.nextAttachInfo ?? '';
|
||||
if (!next || seenCursors.has(next)) return undefined;
|
||||
seenCursors.add(next);
|
||||
attachInfo = next;
|
||||
}
|
||||
}
|
||||
|
||||
private async getQunFeedDetail(
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
batchId: bigint,
|
||||
lloc: string,
|
||||
): Promise<{ cellCommon: QunFeedCellCommon; ownerUin: string; media?: CommentReqPhotoInfo }> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
const body = protobuf_encode<GetQunFeedDetailRequest>({
|
||||
seq: 0,
|
||||
field2: new Uint8Array(0),
|
||||
field3: new Uint8Array(0),
|
||||
data: {
|
||||
groupId: groupId.toString(),
|
||||
feedId: '',
|
||||
commentCount: GET_QUN_FEED_DETAIL_COMMENT_COUNT,
|
||||
attachInfo: '',
|
||||
albumId,
|
||||
batchId: batchId.toString(),
|
||||
lloc,
|
||||
},
|
||||
traceId,
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(GET_QUN_FEED_DETAIL_CMD, body, packetTimeoutMs());
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to fetch album feed');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<GetQunFeedDetailResponse>(result.responseData);
|
||||
const resultCode = resp.result ?? 0;
|
||||
if (resultCode !== 0) {
|
||||
throw new Error(
|
||||
`fetch album feed error: retCode ${resultCode}`
|
||||
+ (resp.errorText ? `, ${resp.errorText}` : ''),
|
||||
);
|
||||
}
|
||||
|
||||
const feed = resp.data?.feed?.feed;
|
||||
const cell = feed?.cellCommon;
|
||||
const feedId = cell?.feedId ?? '';
|
||||
if (!feedId) {
|
||||
throw new Error('comment album media error: empty feed');
|
||||
}
|
||||
return {
|
||||
cellCommon: cell ?? { feedId },
|
||||
ownerUin: feed?.cellUserInfo?.user?.uin ?? '',
|
||||
media: feed?.cellMedia,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
interface AlbumDeleteMediaItem {
|
||||
image?: { lloc?: string } | null;
|
||||
video?: { id?: string; cover?: { lloc?: string } | null } | null;
|
||||
batchId?: string | number;
|
||||
}
|
||||
|
||||
function findDeleteTarget(
|
||||
mediaList: ReadonlyArray<unknown>,
|
||||
mediaKey: string,
|
||||
): { mediaId: string; batchId?: string } | undefined {
|
||||
for (const raw of mediaList) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
const item = raw as AlbumDeleteMediaItem;
|
||||
const batchId = item.batchId === undefined || item.batchId === ''
|
||||
? undefined
|
||||
: String(item.batchId);
|
||||
if (item.image?.lloc === mediaKey) {
|
||||
return { mediaId: mediaKey, batchId };
|
||||
}
|
||||
const coverLloc = item.video?.cover?.lloc;
|
||||
if (item.video?.id === mediaKey || coverLloc === mediaKey) {
|
||||
return { mediaId: coverLloc || mediaKey, batchId };
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
interface AlbumCommentMediaItem {
|
||||
type?: number;
|
||||
image?: {
|
||||
name?: string;
|
||||
sloc?: string;
|
||||
lloc?: string;
|
||||
isGif?: boolean;
|
||||
hasRaw?: boolean;
|
||||
} | null;
|
||||
video?: {
|
||||
id?: string;
|
||||
cover?: {
|
||||
name?: string;
|
||||
sloc?: string;
|
||||
lloc?: string;
|
||||
} | null;
|
||||
} | null;
|
||||
uploader?: string;
|
||||
batchId?: string | number | bigint;
|
||||
}
|
||||
|
||||
function optionalBatchId(value: unknown): bigint | undefined {
|
||||
if (value === undefined || value === null || value === '') return undefined;
|
||||
try {
|
||||
const batchId = BigInt(value as string | number | bigint);
|
||||
return batchId === 0n ? undefined : batchId;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function commentMediaLloc(item: AlbumCommentMediaItem | undefined, lloc: string): string {
|
||||
if (item?.video?.cover?.lloc) return item.video.cover.lloc;
|
||||
if (item?.image?.lloc) return item.image.lloc;
|
||||
return lloc;
|
||||
}
|
||||
|
||||
function mediaInfoForComment(item: AlbumCommentMediaItem | undefined, lloc: string): MediaInfo {
|
||||
const batchId = optionalBatchId(item?.batchId);
|
||||
const shared: MediaInfo = {
|
||||
...(item?.uploader ? { uploader: item.uploader } : {}),
|
||||
...(batchId !== undefined ? { batchId } : {}),
|
||||
};
|
||||
if (item?.video) {
|
||||
return {
|
||||
...shared,
|
||||
type: 1,
|
||||
video: { cover: { lloc: item.video.cover?.lloc || lloc } },
|
||||
};
|
||||
}
|
||||
return {
|
||||
...shared,
|
||||
type: 0,
|
||||
image: { lloc: item?.image?.lloc || lloc },
|
||||
};
|
||||
}
|
||||
|
||||
function qunFeedCellId(
|
||||
groupId: number,
|
||||
albumId: string,
|
||||
batchId: string | number | bigint,
|
||||
lloc?: string,
|
||||
): string {
|
||||
const head = `421_1_0_${groupId}|${albumId}|${batchId}`;
|
||||
if (!lloc) return head;
|
||||
return `${head}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
|
||||
}
|
||||
|
||||
function commentReqHeader(cell: QunFeedCellCommon): CommentReqBodyHeader {
|
||||
return {
|
||||
...(cell.time !== undefined ? { time: cell.time } : {}),
|
||||
...(cell.feedId ? { feedId: cell.feedId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function commentPhotoInfo(
|
||||
feedMedia: CommentReqPhotoInfo | undefined,
|
||||
fallback: MediaInfo,
|
||||
albumId: string,
|
||||
batchId: bigint,
|
||||
): CommentReqPhotoInfo {
|
||||
if (feedMedia?.medias?.length) {
|
||||
return {
|
||||
medias: feedMedia.medias,
|
||||
albumId: feedMedia.albumId || albumId,
|
||||
batchId: feedMedia.batchId ?? batchId,
|
||||
};
|
||||
}
|
||||
return { medias: [fallback], albumId, batchId };
|
||||
}
|
||||
|
||||
function findCommentMedia(
|
||||
mediaList: ReadonlyArray<unknown>,
|
||||
mediaKey: string,
|
||||
): AlbumCommentMediaItem | undefined {
|
||||
for (const raw of mediaList) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
const item = raw as AlbumCommentMediaItem;
|
||||
if (item.image?.lloc === mediaKey) return item;
|
||||
if (item.video?.id === mediaKey || item.video?.cover?.lloc === mediaKey) return item;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function commentFromResponse(resp: DoQunCommentResponse): CommentRespData {
|
||||
const wrapped = resp.comment;
|
||||
if (!wrapped) return {};
|
||||
if (wrapped.data?.id) return wrapped.data;
|
||||
if (wrapped.id) {
|
||||
return {
|
||||
id: wrapped.id,
|
||||
content: wrapped.content,
|
||||
time: wrapped.time,
|
||||
clientKey: wrapped.clientKey,
|
||||
user: wrapped.data?.user,
|
||||
};
|
||||
}
|
||||
return wrapped.data ?? {};
|
||||
}
|
||||
|
||||
export interface GroupAlbumMediaResult {
|
||||
mediaList: Array<JsonValue & Partial<MediaInfo>>;
|
||||
nextAttachInfo: string;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { toHexUpper } from '@snowluma/common/hex';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
|
||||
import { FileChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
@@ -83,11 +82,6 @@ function normalizeDirectory(dir?: string): string {
|
||||
return dir;
|
||||
}
|
||||
|
||||
function bytesToHexUpper(data: unknown): string {
|
||||
if (!(data instanceof Uint8Array) || data.length === 0) return '';
|
||||
return toHexUpper(data);
|
||||
}
|
||||
|
||||
// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives
|
||||
// little-endian-packed (byte0 = first dotted octet) and we unpack it the
|
||||
// same way. Force-unsigned the shift to keep negative ints (high bit set)
|
||||
@@ -568,9 +562,8 @@ export class GroupFileApi {
|
||||
groupId, targetDirectory, startIndex, pageSize,
|
||||
});
|
||||
if (!list) break;
|
||||
ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
|
||||
|
||||
for (const item of list.items ?? []) {
|
||||
for (const item of list.items) {
|
||||
const type = toInt(item?.type);
|
||||
if (type === 1 && item?.fileInfo) {
|
||||
const file = item.fileInfo;
|
||||
@@ -627,34 +620,14 @@ export class GroupFileApi {
|
||||
// ─────────────── url fetch (group / private files) ───────────────
|
||||
|
||||
async getUrl(groupId: number, fileId: string, busId = 102): Promise<string> {
|
||||
const download = await GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
|
||||
ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording);
|
||||
|
||||
const dns = (typeof download.downloadDns === 'string' && download.downloadDns)
|
||||
|| (typeof download.downloadIp === 'string' && download.downloadIp)
|
||||
|| '';
|
||||
const hexUrl = bytesToHexUpper(download.downloadUrl);
|
||||
if (!dns || !hexUrl) {
|
||||
throw new Error('group file url response invalid');
|
||||
}
|
||||
|
||||
// Keep the same behavior as Lagrange: append file_id after ?fname=
|
||||
return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`;
|
||||
return GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
|
||||
}
|
||||
|
||||
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
void userId;
|
||||
const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
|
||||
|
||||
const server = typeof result?.server === 'string' ? result.server : '';
|
||||
const port = toInt(result?.port);
|
||||
const url = typeof result?.url === 'string' ? result.url : '';
|
||||
if (!server || !port || !url) {
|
||||
throw new Error('private file url response invalid');
|
||||
}
|
||||
return `http://${server}:${port}${url}&isthumb=0`;
|
||||
return GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
|
||||
}
|
||||
|
||||
// ─────────────── delete / move ───────────────
|
||||
|
||||
@@ -14,6 +14,7 @@ import { MiscApi } from './misc';
|
||||
import { ProfileApi } from './profile';
|
||||
import { QzoneApi } from './qzone';
|
||||
import { WebApi } from './web';
|
||||
import { SystemFaceApi } from './system-face';
|
||||
|
||||
export interface ApiHub {
|
||||
/** Personal QQ collections: authenticated list retrieval and pagination. */
|
||||
@@ -46,6 +47,8 @@ export interface ApiHub {
|
||||
readonly extras: ExtrasApi;
|
||||
/** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */
|
||||
readonly web: WebApi;
|
||||
/** QQ system-face directory: durable catalog, id lookup, and search. */
|
||||
readonly systemFace: SystemFaceApi;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,6 +76,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub {
|
||||
misc: new MiscApi(ctx),
|
||||
extras: new ExtrasApi(ctx),
|
||||
web: new WebApi(ctx),
|
||||
systemFace: new SystemFaceApi(ctx),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -101,3 +105,4 @@ export { ProfileApi } from './profile';
|
||||
export { QzoneApi } from './qzone';
|
||||
export { FlashTransferApi, type FlashFileInfo } from './flash-transfer';
|
||||
export { WebApi } from './web';
|
||||
export { SystemFaceApi } from './system-face';
|
||||
@@ -33,11 +33,7 @@ export class InteractionApi {
|
||||
return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable });
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy stub: see `GetEmojiLikes` namespace comment for why this
|
||||
* SSO path can never surface the user list. Real data lives in
|
||||
* ReactionStore on the OneBot side.
|
||||
*/
|
||||
/** Fetch the reactor list for one emoji on a group message. */
|
||||
async getEmojiLikes(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
@@ -54,10 +50,7 @@ export class InteractionApi {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the per-emoji reaction summary on a group message via
|
||||
* 0x9084_1 — emoji_id + reactor count + last-reaction timestamp.
|
||||
* Cross-checked against the local ReactionStore cache for callers
|
||||
* that need to detect cache gaps.
|
||||
* Recent-used emoji catalog (0x9084_1). Not a per-message reaction list.
|
||||
*/
|
||||
fetchReactionSummary(
|
||||
groupId: number,
|
||||
|
||||
@@ -14,6 +14,14 @@ import type {
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import { assertWindowShakeSendPolicy } from '@snowluma/protocol/element-manifest';
|
||||
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
|
||||
import {
|
||||
datalineTextFromElements,
|
||||
encodeDatalineText,
|
||||
} from '@snowluma/protocol/dataline/codec';
|
||||
import {
|
||||
findDatalineDeviceByUin,
|
||||
type DatalineDeviceContact,
|
||||
} from '@snowluma/protocol/dataline/device-contacts';
|
||||
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import {
|
||||
fetchC2cMessageRange,
|
||||
@@ -404,6 +412,14 @@ export class MessageApi {
|
||||
}
|
||||
|
||||
const seq = response.groupSequence ?? 0;
|
||||
if (seq <= 0) {
|
||||
log.warn(
|
||||
'group message delivery unconfirmed: group=%d random=%d result=%s sequence=%s time=%s responseBytes=%d',
|
||||
groupId, random, response.result, response.groupSequence,
|
||||
response.timestamp1, result.responseData.length,
|
||||
);
|
||||
throw new Error('group message delivery was not confirmed: QQ returned no message receipt; check the conversation before retrying');
|
||||
}
|
||||
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||
return { messageId, sequence: seq, clientSequence: 0, random, timestamp };
|
||||
@@ -417,6 +433,8 @@ export class MessageApi {
|
||||
* (and optionally `c2c.uid` for the media case).
|
||||
*/
|
||||
async sendPrivate(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||
const device = findDatalineDeviceByUin(userUin);
|
||||
if (device) return this.sendDatalineText(device, elements);
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
assertWindowShakeSendPolicy(
|
||||
elements.filter((element) => element.type === 'poke').length,
|
||||
@@ -483,6 +501,67 @@ export class MessageApi {
|
||||
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
||||
}
|
||||
|
||||
/**
|
||||
* Send text to an official my-device contact. These peers are not
|
||||
* ordinary friends — they use the same trans0x211 send path as c2c
|
||||
* files, with a device-chat body instead of FileExtra.
|
||||
*/
|
||||
private async sendDatalineText(
|
||||
device: DatalineDeviceContact,
|
||||
elements: MessageElement[],
|
||||
): Promise<SendMessageReceipt> {
|
||||
const text = datalineTextFromElements(elements);
|
||||
const selfUin = parseInt(this.ctx.identity.uin, 10);
|
||||
if (!Number.isSafeInteger(selfUin) || selfUin <= 0) {
|
||||
throw new Error('self uin unavailable');
|
||||
}
|
||||
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
routingHead: {
|
||||
trans0x211: {
|
||||
toUin: BigInt(selfUin),
|
||||
ccCmd: 7,
|
||||
uid: device.uid,
|
||||
},
|
||||
},
|
||||
contentHead: {
|
||||
type: 1,
|
||||
subType: 0,
|
||||
},
|
||||
messageBody: {
|
||||
msgContent: encodeDatalineText({
|
||||
selfUin,
|
||||
dstTerType: device.terType,
|
||||
text,
|
||||
}),
|
||||
},
|
||||
clientSequence: clientSeq,
|
||||
random,
|
||||
syncCookie: new Uint8Array(0),
|
||||
via: 0,
|
||||
dataStatist: 0,
|
||||
ctrl: { msgFlag: nowSec },
|
||||
multiSendSeq: 0,
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(`send device message failed: ${result.errorMessage || 'no response'}`);
|
||||
}
|
||||
const response = protobuf_decode<SendMessageResponse>(result.responseData);
|
||||
if (!response) throw new Error('failed to decode SendMessageResponse');
|
||||
if (response.result != null && response.result !== 0) {
|
||||
throw new Error(`send device message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
||||
}
|
||||
const seq = response.privateSequence ?? 0;
|
||||
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reply into an existing group temp session (临时会话). Wire primitive only —
|
||||
* it does NOT gate; the caller verifies the session before calling. Routes
|
||||
@@ -506,6 +585,7 @@ export class MessageApi {
|
||||
bridge: this.ctx as unknown as Bridge,
|
||||
userUid,
|
||||
scene: 'group-temp',
|
||||
tempGroupId: groupUin,
|
||||
});
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
@@ -715,7 +795,7 @@ export class MessageApi {
|
||||
info: {
|
||||
clientSequence: clientSeq,
|
||||
random,
|
||||
messageId: BigInt((0x01000000 * 0x100000000) + random),
|
||||
messageId: (0x01000000n << 32n) | BigInt(random >>> 0),
|
||||
timestamp,
|
||||
field5: 0,
|
||||
messageSequence: msgSeq,
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type {
|
||||
FaceroamOpReq,
|
||||
FaceroamOpResp,
|
||||
GroupAvatarExtra,
|
||||
SetStatusReq,
|
||||
SetStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { AddCustomFace } from '@snowluma/protocol/oidb-services/custom-face/add-custom-face';
|
||||
import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/delete-custom-face';
|
||||
import { FetchCustomFaceDetail } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-detail';
|
||||
import { FetchCustomFaceList } from '@snowluma/protocol/oidb-services/custom-face/fetch-custom-face-list';
|
||||
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';
|
||||
@@ -23,6 +23,13 @@ import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
export interface CustomFaceDetail {
|
||||
emojiId: string;
|
||||
url: string;
|
||||
md5: string;
|
||||
desc: string;
|
||||
}
|
||||
|
||||
export class ProfileApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
@@ -68,14 +75,15 @@ export class ProfileApi {
|
||||
if (!resp) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
}
|
||||
if (resp.errCode !== undefined && resp.errCode !== 0) {
|
||||
throw new Error(resp.errMsg || `set online status failed with errCode: ${resp.errCode}`);
|
||||
const message = resp.errMsg ?? '';
|
||||
if (message !== '' && message !== 'set status success') {
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setProfile(nickname?: string, personalNote?: string): Promise<void> {
|
||||
return SetProfile.invoke(this.ctx, { nickname, personalNote });
|
||||
setProfile(nickname?: string, personalNote?: string, sex?: number): Promise<void> {
|
||||
return SetProfile.invoke(this.ctx, { nickname, personalNote, sex });
|
||||
}
|
||||
|
||||
setSelfLongNick(longNick: string): Promise<void> {
|
||||
@@ -134,26 +142,58 @@ export class ProfileApi {
|
||||
}
|
||||
|
||||
async fetchCustomFace(count = 10): Promise<string[]> {
|
||||
const req = {
|
||||
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
|
||||
uin: BigInt(this.ctx.identity.uin),
|
||||
field3: 1,
|
||||
field6: 1,
|
||||
};
|
||||
const request = protobuf_encode<FaceroamOpReq>(req);
|
||||
const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'fetch custom face failed');
|
||||
}
|
||||
const resp = protobuf_decode<FaceroamOpResp>(result.responseData);
|
||||
if (!resp || resp.retCode !== 0) {
|
||||
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
|
||||
}
|
||||
const faceIds = resp.item?.faceIds || [];
|
||||
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`);
|
||||
const faceIds = await this.fetchCustomFaceIds(count);
|
||||
return faceIds.map((id) => this.customFaceUrl(id));
|
||||
}
|
||||
|
||||
/** 删除一个收藏表情(custom face)。emoji_id 来自 fetchCustomFace 返回的 URL 路径段。 */
|
||||
async fetchCustomFaceDetails(count = 10): Promise<CustomFaceDetail[]> {
|
||||
const faceIds = await this.fetchCustomFaceIds(count);
|
||||
if (faceIds.length === 0) return [];
|
||||
|
||||
const emojis = faceIds.map((emojiId) => ({
|
||||
emojiId,
|
||||
md5: md5FromEmojiId(emojiId),
|
||||
}));
|
||||
const details = await FetchCustomFaceDetail.invoke(this.ctx, { emojis });
|
||||
const descriptions = new Map(details.map((detail) => [detail.emojiId, detail.desc]));
|
||||
|
||||
return emojis.map(({ emojiId, md5 }) => ({
|
||||
emojiId,
|
||||
url: this.customFaceUrl(emojiId),
|
||||
md5,
|
||||
// The detail response may omit entries which have never had a remark.
|
||||
desc: descriptions.get(emojiId) ?? '',
|
||||
}));
|
||||
}
|
||||
|
||||
async fetchCustomFaceIds(count = 10): Promise<string[]> {
|
||||
if (!Number.isInteger(count) || count < 0) {
|
||||
throw new Error('custom face count must be a non-negative integer');
|
||||
}
|
||||
if (count === 0) return [];
|
||||
|
||||
const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
|
||||
return faceIds.slice(0, count);
|
||||
}
|
||||
|
||||
private customFaceUrl(emojiId: string): string {
|
||||
return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`;
|
||||
}
|
||||
|
||||
/** Resolve an existing saved sticker by its resource id or content MD5. */
|
||||
async resolveCustomFace(identifier: string): Promise<Pick<CustomFaceDetail, 'emojiId' | 'url' | 'md5'>> {
|
||||
const wanted = identifier.trim();
|
||||
if (!wanted) throw new Error('custom face identifier is empty');
|
||||
const ids = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
|
||||
const byMd5 = /^[a-fA-F0-9]{32}$/.test(wanted);
|
||||
const emojiId = ids.find((id) => byMd5
|
||||
? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase()
|
||||
: id === wanted);
|
||||
if (!emojiId) throw new Error('custom face is not in the saved sticker list');
|
||||
return { emojiId, url: this.customFaceUrl(emojiId), md5: md5FromEmojiId(emojiId) };
|
||||
}
|
||||
|
||||
/** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */
|
||||
deleteCustomFace(emojiId: string): Promise<void> {
|
||||
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
|
||||
}
|
||||
@@ -168,9 +208,8 @@ export class ProfileApi {
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改收藏表情(custom face)备注。emoji_id 来自 fetchCustomFace 返回的
|
||||
* URL 路径段;md5 从 emoji_id 中段解析,无需调用方单独提供。desc 为空串
|
||||
* 则清空备注。
|
||||
* 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id
|
||||
* 中段解析,无需调用方单独提供。desc 为空串则清空备注。
|
||||
*/
|
||||
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
|
||||
return ModifyCustomFace.invoke(this.ctx, {
|
||||
@@ -188,11 +227,7 @@ export class ProfileApi {
|
||||
*/
|
||||
async moveCustomFaceToFront(emojiId: string): Promise<void> {
|
||||
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
|
||||
const urls = await this.fetchCustomFace(1000);
|
||||
const ids = urls.map((url) => {
|
||||
const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url);
|
||||
return m ? m[1] : '';
|
||||
}).filter(Boolean);
|
||||
const ids = await this.fetchCustomFaceIds(1000);
|
||||
const idx = ids.indexOf(emojiId);
|
||||
if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`);
|
||||
// 新顺序:目标挪到第一,其余按原顺序
|
||||
|
||||
@@ -11,19 +11,6 @@ export function toInt(value: unknown): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard OIDB response check: throw a typed Error if retCode != 0.
|
||||
* Prefers `wording` over `msg` for the human-facing message, falling
|
||||
* back to a generic string. All themed action modules use this for
|
||||
* their OIDB error-path uniformity.
|
||||
*/
|
||||
export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown, wording: unknown): void {
|
||||
const retCode = toInt(code);
|
||||
if (retCode === 0) return;
|
||||
const text = (typeof wording === 'string' && wording) || (typeof msg === 'string' && msg) || 'unknown error';
|
||||
throw new Error(`${operation} failed: code=${retCode} msg=${text}`);
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import {
|
||||
sysFaceStore,
|
||||
type SysFaceEntry,
|
||||
type SysFacePackEntry,
|
||||
} from '@snowluma/protocol/sys-face-store';
|
||||
import { isSuperFaceEntry } from '@snowluma/protocol/oidb-services/sys-faces/fetch-sys-faces';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
/** QQ's account-independent system-face directory. The shared store owns
|
||||
* persistence and refresh coalescing; this API binds it to one live sender. */
|
||||
export class SystemFaceApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
fetchCatalog(refresh = false): Promise<SysFacePackEntry[]> {
|
||||
return sysFaceStore.getCatalog(this.ctx, refresh);
|
||||
}
|
||||
|
||||
async fetchFace(faceId: number, refresh = false): Promise<SysFaceEntry | null> {
|
||||
if (refresh) {
|
||||
await sysFaceStore.refresh(this.ctx);
|
||||
return sysFaceStore.lookup(faceId);
|
||||
}
|
||||
return sysFaceStore.resolve(this.ctx, faceId);
|
||||
}
|
||||
|
||||
async search(query: string): Promise<SysFaceEntry[]> {
|
||||
await sysFaceStore.ensureReady(this.ctx);
|
||||
return sysFaceStore.search(query);
|
||||
}
|
||||
|
||||
async isSuper(faceId: number, refresh = false): Promise<boolean> {
|
||||
const face = await this.fetchFace(faceId, refresh);
|
||||
return face !== null && isSuperFaceEntry(face);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||
GROUP_NOTICE_TYPE_NORMAL,
|
||||
getGroupNoticeWebAPI,
|
||||
groupNoticeImageUrl,
|
||||
setGroupNoticeWebAPI,
|
||||
uploadGroupNoticeImage,
|
||||
type SetNoticeRetSuccess,
|
||||
@@ -43,8 +44,8 @@ export interface WebNoticeInfo {
|
||||
publish_time: number;
|
||||
message: {
|
||||
text: string;
|
||||
image: Array<{ id: string; height: number; width: number }>;
|
||||
images: Array<{ id: string; height: number; width: number }>;
|
||||
image: Array<{ id: string; url: string; height: number; width: number }>;
|
||||
images: Array<{ id: string; url: string; height: number; width: number }>;
|
||||
};
|
||||
settings: import('@snowluma/common/json').JsonValue;
|
||||
read_num: number;
|
||||
@@ -104,6 +105,7 @@ function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boole
|
||||
}
|
||||
return {
|
||||
id: pic.id,
|
||||
url: groupNoticeImageUrl(pic.id),
|
||||
height: finiteNumber(pic.h, `feed ${feed.fid} image ${index}.h`),
|
||||
width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`),
|
||||
};
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
|
||||
import type { BridgeContext } from './bridge-context';
|
||||
|
||||
export interface RosterWarmupResult {
|
||||
friendsLoaded: boolean;
|
||||
groupsLoaded: boolean;
|
||||
}
|
||||
|
||||
export interface BridgeInterface extends BridgeContext {
|
||||
readonly activePid: number | null;
|
||||
/** False only when every attached QQ process is confirmed stale.
|
||||
* An unarmed watchdog remains true for compatibility. */
|
||||
/** Settles once for this Bridge session after first-login roster fetch. */
|
||||
whenRosterWarmupSettled(): Promise<RosterWarmupResult>;
|
||||
/** False only when every attached QQ process has a confirmed receive or
|
||||
* request-path failure. An unarmed watchdog remains true for compatibility. */
|
||||
readonly receiveHealthy: boolean;
|
||||
/** Latest device snapshot observed on this Bridge lifecycle. `null` means
|
||||
* QQ has not emitted its cache notification since SnowLuma attached. */
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { packetTimeoutMs } from '@snowluma/bridge/packet-timeout';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
@@ -21,10 +22,11 @@ import {
|
||||
type AiVoiceCategory,
|
||||
type StrangerStatus,
|
||||
} from './apis/extras';
|
||||
import type { BridgeInterface } from './bridge-interface';
|
||||
import type { BridgeInterface, RosterWarmupResult } from './bridge-interface';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const runtimeLog = createLogger('Bridge.Runtime');
|
||||
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
|
||||
|
||||
export class Bridge implements BridgeInterface {
|
||||
readonly identity: IdentityService;
|
||||
@@ -46,32 +48,33 @@ export class Bridge implements BridgeInterface {
|
||||
// Per-account dedup for QQ NT's already-deduped system pushes (#137).
|
||||
private readonly sysMsgDedup_ = new SysMsgDedup();
|
||||
private onlineClients_: readonly Readonly<OnlineDeviceInfo>[] | null = null;
|
||||
private disposed_ = false;
|
||||
private rosterWarmupStarted_ = false;
|
||||
private rosterWarmupSettled_ = false;
|
||||
private rosterWarmupResult_: RosterWarmupResult | null = null;
|
||||
private readonly rosterWarmupWaiters_: Array<(result: RosterWarmupResult) => void> = [];
|
||||
|
||||
constructor(identity: IdentityService) {
|
||||
this.identity = identity;
|
||||
this.apis = buildApiHub(this);
|
||||
this.identity.setFetcher({
|
||||
fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin),
|
||||
fetchProfileByUid: (uid) => this.apis.contacts.fetchUserProfileByUid(uid),
|
||||
fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid),
|
||||
});
|
||||
this.pipeline = new IncomingPacketPipeline({
|
||||
identity: this.identity,
|
||||
events: this.events,
|
||||
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
|
||||
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
|
||||
resolveStrangerProfile: async (uid) => {
|
||||
try {
|
||||
const p = await this.apis.contacts.fetchUserProfileByUid(uid);
|
||||
if (p.uin <= 0) return null;
|
||||
return { uin: p.uin, nickname: p.nickname };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
fetchGroupList: async () => {
|
||||
await this.apis.contacts.fetchGroupList();
|
||||
},
|
||||
fetchGroupMemberList: async (groupId) => {
|
||||
await this.apis.contacts.fetchGroupMemberList(groupId);
|
||||
},
|
||||
resolveGroupJoinRequest: async (groupId, uid, subType) => {
|
||||
const [main, filtered] = await Promise.allSettled([
|
||||
this.apis.contacts.fetchGroupRequests(false),
|
||||
this.apis.contacts.fetchGroupRequests(true),
|
||||
this.apis.contacts.fetchGroupRequestsByUid(false),
|
||||
this.apis.contacts.fetchGroupRequestsByUid(true),
|
||||
]);
|
||||
if (main.status === 'rejected') {
|
||||
log.warn('group-request enrichment main inbox failed: group=%d uid=%s err=%s',
|
||||
@@ -88,10 +91,14 @@ export class Bridge implements BridgeInterface {
|
||||
...(main.status === 'fulfilled' ? main.value : []),
|
||||
...(filtered.status === 'fulfilled' ? filtered.value : []),
|
||||
];
|
||||
return requests.find(r => {
|
||||
const matches = requests.filter((r) => {
|
||||
if (r.groupId !== groupId) return false;
|
||||
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
|
||||
}) ?? null;
|
||||
});
|
||||
if (subType === 'invite') {
|
||||
return matches.find((r) => r.notifyType === 1) ?? matches[0] ?? null;
|
||||
}
|
||||
return matches.find((r) => r.notifyType === 7) ?? matches[0] ?? null;
|
||||
},
|
||||
resolveGroupInviteCardSequence: async (groupId) => {
|
||||
const deadline = Date.now() + 1_000;
|
||||
@@ -102,6 +109,9 @@ export class Bridge implements BridgeInterface {
|
||||
} while (Date.now() < deadline);
|
||||
return null;
|
||||
},
|
||||
rememberGroupInviteCardSequence: (groupUin, sequence) => {
|
||||
this.apis.contacts.rememberGroupInviteCardSequence(groupUin, sequence);
|
||||
},
|
||||
});
|
||||
this.pipeline.registerCmd(
|
||||
MSG_PUSH_CMD,
|
||||
@@ -122,6 +132,8 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposed_ = true;
|
||||
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
|
||||
this.pids_.clear();
|
||||
this.receiveHealthByPid_.clear();
|
||||
this.packetClientsByPid_.clear();
|
||||
@@ -146,6 +158,7 @@ export class Bridge implements BridgeInterface {
|
||||
const pid = pids.length > 0 ? pids[pids.length - 1]! : null;
|
||||
this.packetClientPid_ = pid;
|
||||
if (pid !== null) this.packetClientsByPid_.set(pid, client);
|
||||
this.maybeStartRosterWarmup();
|
||||
}
|
||||
|
||||
registerCmd(cmd: string, parser: CmdParser): void {
|
||||
@@ -185,6 +198,7 @@ export class Bridge implements BridgeInterface {
|
||||
previousPid,
|
||||
);
|
||||
}
|
||||
this.maybeStartRosterWarmup();
|
||||
}
|
||||
|
||||
/** @internal BridgeManager lookup used when an incoming packet is the first
|
||||
@@ -241,18 +255,25 @@ export class Bridge implements BridgeInterface {
|
||||
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null {
|
||||
return this.onlineClients_;
|
||||
}
|
||||
|
||||
whenRosterWarmupSettled(): Promise<RosterWarmupResult> {
|
||||
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
|
||||
return Promise.resolve(this.rosterWarmupResult_);
|
||||
}
|
||||
this.maybeStartRosterWarmup();
|
||||
return new Promise((resolve) => {
|
||||
if (this.rosterWarmupSettled_ && this.rosterWarmupResult_) {
|
||||
resolve(this.rosterWarmupResult_);
|
||||
return;
|
||||
}
|
||||
this.rosterWarmupWaiters_.push(resolve);
|
||||
});
|
||||
}
|
||||
|
||||
onPacket(pkt: PacketInfo): Promise<void> {
|
||||
return this.pipeline.process(pkt);
|
||||
}
|
||||
|
||||
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
|
||||
if (refreshGroupList) {
|
||||
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
|
||||
}
|
||||
if (!this.identity.findGroup(groupId)) return false;
|
||||
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
|
||||
return true;
|
||||
}
|
||||
rememberUploadedFile(meta: UploadedFileMeta): void {
|
||||
if (!meta.fileId) return;
|
||||
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
|
||||
@@ -276,7 +297,7 @@ export class Bridge implements BridgeInterface {
|
||||
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
|
||||
return this.msgRandom_ & 0x7FFFFFFF;
|
||||
}
|
||||
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
|
||||
if (!this.packetClient_) {
|
||||
return runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
@@ -362,6 +383,125 @@ export class Bridge implements BridgeInterface {
|
||||
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
|
||||
return this.identity.resolveUid(uin, groupId);
|
||||
}
|
||||
|
||||
private maybeStartRosterWarmup(): void {
|
||||
if (this.disposed_ || this.rosterWarmupStarted_ || !this.packetClient_) return;
|
||||
this.rosterWarmupStarted_ = true;
|
||||
if (!this.identity.nickname) this.identity.nickname = this.identity.uin;
|
||||
void this.runRosterWarmup().then(
|
||||
(result) => this.settleRosterWarmup(this.disposed_ ? { friendsLoaded: false, groupsLoaded: false } : result),
|
||||
(err) => {
|
||||
log.warn(
|
||||
'roster warmup failed: uin=%s err=%s',
|
||||
this.identity.uin,
|
||||
err instanceof Error ? (err.stack ?? err.message) : String(err),
|
||||
);
|
||||
this.settleRosterWarmup({ friendsLoaded: false, groupsLoaded: false });
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private settleRosterWarmup(result: RosterWarmupResult): void {
|
||||
if (this.rosterWarmupSettled_) return;
|
||||
this.rosterWarmupSettled_ = true;
|
||||
this.rosterWarmupResult_ = result;
|
||||
const waiters = this.rosterWarmupWaiters_.splice(0);
|
||||
for (const resolve of waiters) resolve(result);
|
||||
}
|
||||
|
||||
private stillOpen(): boolean {
|
||||
return !this.disposed_;
|
||||
}
|
||||
|
||||
private async runRosterWarmup(): Promise<RosterWarmupResult> {
|
||||
const uin = this.identity.uin;
|
||||
const selfUin = parseInt(uin, 10) || 0;
|
||||
let selfResolved = false;
|
||||
let friendsLoaded = false;
|
||||
|
||||
try {
|
||||
const friends = await this.apis.contacts.fetchFriendList();
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
friendsLoaded = true;
|
||||
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
|
||||
|
||||
for (const friend of friends) {
|
||||
if (friend.uin === selfUin) {
|
||||
this.identity.setSelfProfile({
|
||||
uin: friend.uin, uid: friend.uid,
|
||||
nickname: friend.nickname || uin,
|
||||
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0,
|
||||
qidianMasterFlag: 0, qidianCrewFlag: 0, qidianCrewFlag2: 0,
|
||||
});
|
||||
this.identity.nickname = friend.nickname || uin;
|
||||
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, friend.uid, friend.nickname ?? '');
|
||||
selfResolved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
if (!selfResolved && selfUin > 0 && this.stillOpen()) {
|
||||
try {
|
||||
const profile = await this.apis.contacts.fetchUserProfile(selfUin);
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
this.identity.setSelfProfile(profile);
|
||||
this.identity.nickname = profile.nickname || uin;
|
||||
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
|
||||
uin, profile.uid, profile.nickname);
|
||||
} catch (e) {
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
log.warn('failed to load self profile for UIN %s: %s',
|
||||
uin, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
let groups: { groupId: number }[] = [];
|
||||
let groupsLoaded = false;
|
||||
try {
|
||||
groups = await this.apis.contacts.fetchGroupList();
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
groupsLoaded = true;
|
||||
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
|
||||
} catch (e) {
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
|
||||
let loadedGroupCount = 0;
|
||||
let loadedMemberCount = 0;
|
||||
let failedGroupCount = 0;
|
||||
for (const group of groups) {
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
try {
|
||||
const members = await this.apis.contacts.fetchGroupMemberList(group.groupId);
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
loadedGroupCount += 1;
|
||||
loadedMemberCount += members.length;
|
||||
if (VERBOSE_WARMUP) {
|
||||
log.debug('members loaded: group=%d count=%d', group.groupId, members.length);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
failedGroupCount += 1;
|
||||
log.warn('failed to load members for group %d: %s', group.groupId, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.stillOpen()) return { friendsLoaded: false, groupsLoaded: false };
|
||||
log.info(
|
||||
'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d',
|
||||
uin,
|
||||
loadedGroupCount,
|
||||
groups.length,
|
||||
loadedMemberCount,
|
||||
failedGroupCount,
|
||||
);
|
||||
return { friendsLoaded, groupsLoaded };
|
||||
}
|
||||
}
|
||||
export interface SendMessageReceipt {
|
||||
messageId: number;
|
||||
|
||||
@@ -18,6 +18,7 @@ import { workerData } from 'node:worker_threads';
|
||||
import { BridgeManager } from './bridge/manager';
|
||||
import { createNotificationManager } from './notifications/manager';
|
||||
import { createStateWiring } from './webui/state-wiring';
|
||||
import { bindSystemFaceCatalog } from './sys-face-catalog';
|
||||
|
||||
const log = createLogger('App');
|
||||
|
||||
@@ -57,6 +58,7 @@ async function main() {
|
||||
cleanupInvalidPerUinConfigs();
|
||||
|
||||
const bridgeManager = new BridgeManager();
|
||||
bindSystemFaceCatalog(bridgeManager);
|
||||
const oneBotManager = new OneBotManager();
|
||||
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
||||
|
||||
@@ -81,18 +83,20 @@ async function main() {
|
||||
const notificationManager = createNotificationManager();
|
||||
notificationManager.bind(bridgeManager);
|
||||
|
||||
let stopWebUI: (() => Promise<void>) | undefined;
|
||||
if (
|
||||
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
|
||||
process.env.SNOWLUMA_DEV_WEBUI === '1'
|
||||
) {
|
||||
try {
|
||||
const { initWebUI } = await import('./webui/server');
|
||||
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, {
|
||||
const started = await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, {
|
||||
host: runtimeConfig.webuiHost,
|
||||
tlsEnabled: runtimeConfig.webuiTls?.enabled,
|
||||
trustProxy: runtimeConfig.trustProxy,
|
||||
stateBus: stateWiring.bus,
|
||||
});
|
||||
stopWebUI = started.stop;
|
||||
} catch (err) {
|
||||
log.error('Failed to start WebUI: ', err);
|
||||
}
|
||||
@@ -116,14 +120,23 @@ async function main() {
|
||||
exitCode = 1;
|
||||
log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
try { hookManager.dispose(); } catch (error) {
|
||||
try {
|
||||
if (stopWebUI) await stopWebUI();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
log.error('WebUI shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
// Observers go deaf before Hook teardown. Hook dispose then emits the
|
||||
// same disconnected → PID detach → Bridge closed path as a live drop;
|
||||
// those closed edges must not look like a runtime offline.
|
||||
try { stateWiring.dispose(); } catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('state wiring shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
try { hookManager.dispose(); } catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
await closeLogger();
|
||||
process.exit(exitCode);
|
||||
};
|
||||
|
||||
@@ -11,6 +11,7 @@ import { boolOr, clampInt, isObject } from '@snowluma/common/coerce';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { extractAddress, parseRecipients } from './smtp';
|
||||
|
||||
const log = createLogger('Notifications.Config');
|
||||
|
||||
@@ -31,16 +32,45 @@ export const CHANNEL_ID_RE = /^[\w.-]+$/;
|
||||
const CHANNEL_ID_MAX = 64;
|
||||
const CHANNEL_NAME_MAX = 128;
|
||||
const BODY_TEMPLATE_MAX = 8192;
|
||||
const HEADER_NAME_MAX = 128;
|
||||
const HEADER_VALUE_MAX = 1024;
|
||||
const HEADERS_MAX = 16;
|
||||
const HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
||||
|
||||
/** event ∈ {offline, online}; rendered verbatim into `{event}`. */
|
||||
export type NotificationEvent = 'offline' | 'online';
|
||||
|
||||
export type NotificationChannelType = 'webhook' | 'email';
|
||||
|
||||
export interface NotificationChannel {
|
||||
id: string;
|
||||
name: string;
|
||||
type: NotificationChannelType;
|
||||
/** http(s) webhook target. Empty on email channels. */
|
||||
url: string;
|
||||
bodyTemplate: string;
|
||||
enabled: boolean;
|
||||
/** Extra outbound request headers (Authorization, etc.). Webhook only. */
|
||||
headers?: Record<string, string>;
|
||||
smtpHost?: string;
|
||||
smtpPort?: number;
|
||||
smtpSecure?: boolean;
|
||||
smtpUser?: string;
|
||||
smtpPass?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
subjectTemplate?: string;
|
||||
}
|
||||
|
||||
export function isEmailChannel(ch: NotificationChannel): ch is NotificationChannel & {
|
||||
smtpHost: string;
|
||||
smtpPort: number;
|
||||
smtpSecure: boolean;
|
||||
from: string;
|
||||
to: string;
|
||||
subjectTemplate: string;
|
||||
} {
|
||||
return ch.type === 'email';
|
||||
}
|
||||
|
||||
export interface NotificationsConfig {
|
||||
@@ -57,6 +87,23 @@ export const DEFAULT_BODY_TEMPLATE = `{
|
||||
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}"
|
||||
}`;
|
||||
|
||||
export const DEFAULT_SUBJECT_TEMPLATE = '账号{event}:{nickname} ({uin})';
|
||||
|
||||
export const DEFAULT_EMAIL_BODY_TEMPLATE = `账号状态发生了改变。
|
||||
|
||||
昵称:{nickname}
|
||||
QQ号:{uin}
|
||||
当前状态:{event}
|
||||
时间:{time}`;
|
||||
|
||||
const SMTP_HOST_MAX = 253;
|
||||
const SMTP_USER_MAX = 256;
|
||||
const SMTP_PASS_MAX = 256;
|
||||
const EMAIL_FIELD_MAX = 1024;
|
||||
const SUBJECT_TEMPLATE_MAX = 256;
|
||||
const SMTP_PORT_MIN = 1;
|
||||
const SMTP_PORT_MAX = 65535;
|
||||
|
||||
export function defaultNotificationsConfig(): NotificationsConfig {
|
||||
return {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
@@ -118,21 +165,118 @@ function isHttpUrl(value: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/** A channel is usable only with a valid id AND an http(s) target — anything
|
||||
* else is unusable, so the whole entry is dropped (total normalize). */
|
||||
function normalizeHeaders(value: unknown): Record<string, string> | undefined {
|
||||
if (!isObject(value)) return undefined;
|
||||
const out: Record<string, string> = {};
|
||||
const seen = new Set<string>();
|
||||
for (const [rawName, rawValue] of Object.entries(value)) {
|
||||
if (Object.keys(out).length >= HEADERS_MAX) break;
|
||||
if (typeof rawValue !== 'string') continue;
|
||||
const name = rawName.trim();
|
||||
if (name.length === 0 || name.length > HEADER_NAME_MAX) continue;
|
||||
if (!HEADER_NAME_RE.test(name)) continue;
|
||||
const folded = name.toLowerCase();
|
||||
if (seen.has(folded)) continue;
|
||||
const headerValue = rawValue.trim();
|
||||
if (headerValue.length === 0 || headerValue.length > HEADER_VALUE_MAX) continue;
|
||||
if (headerValue.includes('\r') || headerValue.includes('\n')) continue;
|
||||
seen.add(folded);
|
||||
out[name] = headerValue;
|
||||
}
|
||||
return Object.keys(out).length > 0 ? out : undefined;
|
||||
}
|
||||
|
||||
function normalizeSmtpHost(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const v = value.trim();
|
||||
if (!v || v.length > SMTP_HOST_MAX) return null;
|
||||
if (/\s/.test(v) || v.includes('/') || v.includes('://')) return null;
|
||||
return v;
|
||||
}
|
||||
|
||||
function normalizeFrom(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const v = value.trim().slice(0, EMAIL_FIELD_MAX);
|
||||
return extractAddress(v) ? v : null;
|
||||
}
|
||||
|
||||
function normalizeTo(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const addrs = parseRecipients(value.trim().slice(0, EMAIL_FIELD_MAX));
|
||||
return addrs.length > 0 ? addrs.join(', ') : null;
|
||||
}
|
||||
|
||||
function normalizeChannelType(value: unknown): NotificationChannelType | null {
|
||||
if (value === 'email') return 'email';
|
||||
if (value === 'webhook' || value === undefined || value === '') return 'webhook';
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeEmailChannel(
|
||||
raw: Record<string, unknown>,
|
||||
id: string,
|
||||
name: string,
|
||||
): NotificationChannel | null {
|
||||
const smtpHost = normalizeSmtpHost(raw.smtpHost);
|
||||
const from = normalizeFrom(raw.from);
|
||||
const to = normalizeTo(raw.to);
|
||||
if (!smtpHost || !from || !to) return null;
|
||||
|
||||
const portRaw = raw.smtpPort;
|
||||
const portProvided = portRaw !== undefined && portRaw !== null && portRaw !== '';
|
||||
const secureProvided = typeof raw.smtpSecure === 'boolean';
|
||||
const port = portProvided
|
||||
? clampInt(portRaw, SMTP_PORT_MIN, SMTP_PORT_MAX, 0)
|
||||
: 0;
|
||||
if (portProvided && port === 0) return null;
|
||||
|
||||
const smtpSecure = secureProvided ? Boolean(raw.smtpSecure) : port === 465 || port === 0;
|
||||
const smtpPort = port === 0 ? (smtpSecure ? 465 : 587) : port;
|
||||
|
||||
const smtpUser = typeof raw.smtpUser === 'string' ? raw.smtpUser.trim().slice(0, SMTP_USER_MAX) : '';
|
||||
const smtpPass = typeof raw.smtpPass === 'string' ? raw.smtpPass.slice(0, SMTP_PASS_MAX) : '';
|
||||
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
type: 'email',
|
||||
url: '',
|
||||
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
|
||||
enabled: boolOr(raw.enabled, true),
|
||||
smtpHost,
|
||||
smtpPort,
|
||||
smtpSecure,
|
||||
...(smtpUser ? { smtpUser } : {}),
|
||||
...(smtpPass ? { smtpPass } : {}),
|
||||
from,
|
||||
to,
|
||||
subjectTemplate: strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) || DEFAULT_SUBJECT_TEMPLATE,
|
||||
};
|
||||
}
|
||||
|
||||
/** A channel is usable only with a valid id AND a deliverable target —
|
||||
* http(s) URL for webhooks, SMTP host + from/to for email. Anything else
|
||||
* is dropped (total normalize). */
|
||||
function normalizeChannel(raw: unknown): NotificationChannel | null {
|
||||
if (!isObject(raw)) return null;
|
||||
const id = normalizeChannelId(raw.id);
|
||||
if (!id) return null;
|
||||
const type = normalizeChannelType(raw.type);
|
||||
if (!type) return null;
|
||||
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
|
||||
if (type === 'email') return normalizeEmailChannel(raw, id, name);
|
||||
|
||||
const url = typeof raw.url === 'string' ? raw.url.trim() : '';
|
||||
if (!isHttpUrl(url)) return null;
|
||||
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
|
||||
const headers = normalizeHeaders(raw.headers);
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
type: 'webhook',
|
||||
url,
|
||||
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
|
||||
enabled: boolOr(raw.enabled, true),
|
||||
...(headers ? { headers } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -170,11 +314,22 @@ function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function enforceSensitiveFileMode(file: string): void {
|
||||
// POSIX mode bits do not model Windows ACLs; on Windows the inherited ACL
|
||||
// remains authoritative. Avoid pretending chmod provides equivalent policy.
|
||||
if (process.platform !== 'win32') fs.chmodSync(file, 0o600);
|
||||
}
|
||||
|
||||
function atomicWrite(config: NotificationsConfig): void {
|
||||
ensureConfigDir();
|
||||
const tmp = NOTIFICATIONS_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), {
|
||||
encoding: 'utf8',
|
||||
mode: 0o600,
|
||||
});
|
||||
enforceSensitiveFileMode(tmp);
|
||||
fs.renameSync(tmp, NOTIFICATIONS_CONFIG_PATH);
|
||||
enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH);
|
||||
}
|
||||
|
||||
let cached: NotificationsConfig | null = null;
|
||||
@@ -195,6 +350,10 @@ export function loadNotificationsConfig(): NotificationsConfig {
|
||||
return fresh;
|
||||
}
|
||||
|
||||
// Webhook URLs commonly embed credentials. Repair older permissive files
|
||||
// before reading them into memory so upgrades close the exposure promptly.
|
||||
enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH);
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(NOTIFICATIONS_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
@@ -203,8 +362,8 @@ export function loadNotificationsConfig(): NotificationsConfig {
|
||||
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
|
||||
try {
|
||||
atomicWrite(normalized);
|
||||
} catch {
|
||||
/* best-effort self-heal */
|
||||
} catch (err) {
|
||||
log.warn('failed to normalize notifications.json on disk: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
cached = normalized;
|
||||
|
||||
@@ -2,16 +2,18 @@
|
||||
//
|
||||
// Subscribes to BridgeManager session online/offline edges, runs a per-UIN
|
||||
// debounce state machine (see debounce.ts), and on a fired transition renders
|
||||
// each opted-in + enabled channel's body template and POSTs it — recording the
|
||||
// each opted-in + enabled channel's template and delivers it — recording the
|
||||
// outcome in a bounded in-memory history (lost on restart, by design).
|
||||
//
|
||||
// Side-effecting collaborators (config load, per-UIN channel ids, the outbound
|
||||
// POST, the clock) are injected so the class is fully unit-testable; the real
|
||||
// wiring lives in `createNotificationManager()` at the bottom.
|
||||
// Side-effecting collaborators (config load, per-UIN channel ids, webhook POST,
|
||||
// SMTP send, the clock) are injected so the class is fully unit-testable; the
|
||||
// real wiring lives in `createNotificationManager()` at the bottom.
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { loadOneBotConfig } from '@snowluma/onebot/config';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
import {
|
||||
isEmailChannel,
|
||||
loadNotificationsConfig,
|
||||
renderTemplate,
|
||||
type NotificationChannel,
|
||||
@@ -19,6 +21,7 @@ import {
|
||||
type NotificationsConfig,
|
||||
} from './config';
|
||||
import { DebounceMachine, type DebounceDecision } from './debounce';
|
||||
import { formatSmtpError, parseRecipients, sendSmtpMail } from './smtp';
|
||||
|
||||
const log = createLogger('Notifications');
|
||||
|
||||
@@ -43,13 +46,27 @@ export interface PostResult {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface MailPayload {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user?: string;
|
||||
pass?: string;
|
||||
from: string;
|
||||
to: string;
|
||||
subject: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface NotificationManagerDeps {
|
||||
/** Global channel store (channels + debounceSeconds). */
|
||||
loadConfig: () => NotificationsConfig;
|
||||
/** The channel ids a UIN has opted into. */
|
||||
loadChannelIds: (uin: string) => string[];
|
||||
/** Outbound delivery — never throws; failures come back as `{ ok: false }`. */
|
||||
post: (url: string, body: string) => Promise<PostResult>;
|
||||
/** Webhook delivery — never throws; failures come back as `{ ok: false }`. */
|
||||
post: (url: string, body: string, headers?: Record<string, string>) => Promise<PostResult>;
|
||||
/** SMTP delivery — optional so webhook-only tests stay lean. */
|
||||
sendMail?: (mail: MailPayload) => Promise<PostResult>;
|
||||
now: () => number;
|
||||
historyLimit?: number;
|
||||
}
|
||||
@@ -74,6 +91,7 @@ export class NotificationManager {
|
||||
private readonly nicknames = new Map<string, string>();
|
||||
private readonly history: DeliveryRecord[] = [];
|
||||
private readonly historyLimit: number;
|
||||
private disposed = false;
|
||||
|
||||
constructor(deps: NotificationManagerDeps) {
|
||||
this.deps = deps;
|
||||
@@ -88,11 +106,13 @@ export class NotificationManager {
|
||||
}
|
||||
|
||||
handleOnline(uin: string, nickname?: string): void {
|
||||
if (this.disposed) return;
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
this.apply(uin, this.machine.onOnline(uin));
|
||||
}
|
||||
|
||||
handleOffline(uin: string, nickname?: string): void {
|
||||
if (this.disposed) return;
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
|
||||
}
|
||||
@@ -137,7 +157,7 @@ export class NotificationManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** Render + POST a transition to every opted-in, enabled channel and record
|
||||
/** Render + deliver a transition to every opted-in, enabled channel and record
|
||||
* the outcome. Never throws (a bad channel can't break the others). */
|
||||
async notify(uin: string, event: NotificationEvent): Promise<void> {
|
||||
let channels: NotificationChannel[];
|
||||
@@ -159,14 +179,7 @@ export class NotificationManager {
|
||||
};
|
||||
|
||||
for (const ch of channels) {
|
||||
const body = renderTemplate(ch.bodyTemplate, vars);
|
||||
let result: PostResult;
|
||||
try {
|
||||
result = await this.deps.post(ch.url, body);
|
||||
} catch (err) {
|
||||
// The injected post is contracted not to throw, but guard anyway.
|
||||
result = { ok: false, error: errMsg(err) };
|
||||
}
|
||||
const result = await this.deliver(ch, vars);
|
||||
this.record({
|
||||
time: this.deps.now(),
|
||||
uin,
|
||||
@@ -182,9 +195,33 @@ export class NotificationManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async deliver(ch: NotificationChannel, vars: Record<string, string>): Promise<PostResult> {
|
||||
try {
|
||||
if (isEmailChannel(ch)) {
|
||||
const send = this.deps.sendMail;
|
||||
if (!send) return { ok: false, error: 'email delivery is not configured' };
|
||||
return await send({
|
||||
host: ch.smtpHost,
|
||||
port: ch.smtpPort,
|
||||
secure: ch.smtpSecure,
|
||||
user: ch.smtpUser,
|
||||
pass: ch.smtpPass,
|
||||
from: ch.from,
|
||||
to: ch.to,
|
||||
subject: renderTemplate(ch.subjectTemplate, vars),
|
||||
text: renderTemplate(ch.bodyTemplate, vars),
|
||||
});
|
||||
}
|
||||
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
|
||||
} catch (err) {
|
||||
// Injected collaborators are contracted not to throw, but guard anyway.
|
||||
return { ok: false, error: errMsg(err) };
|
||||
}
|
||||
}
|
||||
|
||||
/** Send a one-off test to a single channel by id — ignores `enabled` and the
|
||||
* per-UIN opt-in (you test a channel before wiring it up), with sample
|
||||
* variables. Reuses the real render+POST path; NOT recorded to history.
|
||||
* variables. Reuses the real render+deliver path; NOT recorded to history.
|
||||
* `found:false` means the channel id is unknown. */
|
||||
async testSend(channelId: string): Promise<PostResult & { found: boolean }> {
|
||||
let channel: NotificationChannel | undefined;
|
||||
@@ -194,17 +231,13 @@ export class NotificationManager {
|
||||
return { ok: false, found: false, error: errMsg(err) };
|
||||
}
|
||||
if (!channel) return { ok: false, found: false };
|
||||
const body = renderTemplate(channel.bodyTemplate, {
|
||||
const vars = {
|
||||
uin: '10000',
|
||||
nickname: '测试账号',
|
||||
event: 'offline',
|
||||
event: 'offline' as const,
|
||||
time: new Date(this.deps.now()).toISOString(),
|
||||
});
|
||||
try {
|
||||
return { ...(await this.deps.post(channel.url, body)), found: true };
|
||||
} catch (err) {
|
||||
return { ok: false, found: true, error: errMsg(err) };
|
||||
}
|
||||
};
|
||||
return { ...(await this.deliver(channel, vars)), found: true };
|
||||
}
|
||||
|
||||
private record(rec: DeliveryRecord): void {
|
||||
@@ -221,6 +254,8 @@ export class NotificationManager {
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
for (const timer of this.timers.values()) clearTimeout(timer);
|
||||
this.timers.clear();
|
||||
}
|
||||
@@ -228,12 +263,14 @@ export class NotificationManager {
|
||||
|
||||
/** Default outbound POST: a single attempt with a timeout, JSON content-type
|
||||
* (the common case for 钉钉/Discord/飞书). Never throws. */
|
||||
export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): NotificationManagerDeps['post'] {
|
||||
return async (url, body) => {
|
||||
export function createDefaultPost(
|
||||
timeoutMs = positiveIntEnv('SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', DEFAULT_POST_TIMEOUT_MS),
|
||||
): NotificationManagerDeps['post'] {
|
||||
return async (url, body, headers) => {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', ...headers },
|
||||
body,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
@@ -244,12 +281,37 @@ export function createDefaultPost(timeoutMs = DEFAULT_POST_TIMEOUT_MS): Notifica
|
||||
};
|
||||
}
|
||||
|
||||
const DEFAULT_SMTP_TIMEOUT_MS = 15_000;
|
||||
|
||||
/** Default SMTP send. Never throws. */
|
||||
export function createDefaultSendMail(timeoutMs = DEFAULT_SMTP_TIMEOUT_MS): NonNullable<NotificationManagerDeps['sendMail']> {
|
||||
return async (mail) => {
|
||||
try {
|
||||
await sendSmtpMail({
|
||||
host: mail.host,
|
||||
port: mail.port,
|
||||
secure: mail.secure,
|
||||
user: mail.user,
|
||||
pass: mail.pass,
|
||||
from: mail.from,
|
||||
to: parseRecipients(mail.to),
|
||||
subject: mail.subject,
|
||||
body: mail.text,
|
||||
}, { timeoutMs });
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
return { ok: false, error: formatSmtpError(err, mail.host, mail.port) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** The real, fully-wired singleton. */
|
||||
export function createNotificationManager(): NotificationManager {
|
||||
return new NotificationManager({
|
||||
loadConfig: loadNotificationsConfig,
|
||||
loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [],
|
||||
post: createDefaultPost(),
|
||||
sendMail: createDefaultSendMail(),
|
||||
now: () => Date.now(),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
// Minimal SMTP client for notification-channel email. Runtime ships with no
|
||||
// npm dependencies, so this speaks the protocol over node:net / node:tls
|
||||
// (EHLO, optional STARTTLS, AUTH PLAIN/LOGIN, DATA). No extra features.
|
||||
|
||||
import net from 'node:net';
|
||||
import tls from 'node:tls';
|
||||
|
||||
const CRLF = '\r\n';
|
||||
const DEFAULT_TIMEOUT_MS = 15_000;
|
||||
|
||||
export class SmtpError extends Error {
|
||||
readonly responseCode?: number;
|
||||
readonly code?: string;
|
||||
|
||||
constructor(message: string, opts?: { responseCode?: number; code?: string }) {
|
||||
super(message);
|
||||
this.name = 'SmtpError';
|
||||
this.responseCode = opts?.responseCode;
|
||||
this.code = opts?.code;
|
||||
}
|
||||
}
|
||||
|
||||
export interface SmtpMail {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user?: string;
|
||||
pass?: string;
|
||||
from: string;
|
||||
to: string[];
|
||||
subject: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface SendSmtpOptions {
|
||||
timeoutMs?: number;
|
||||
/** Defaults true. Tests against a self-signed mock pass false. */
|
||||
rejectUnauthorized?: boolean;
|
||||
}
|
||||
|
||||
export function looksLikeEmail(value: string): boolean {
|
||||
return /^[^\s<>@]+@[^\s<>@]+$/.test(value);
|
||||
}
|
||||
|
||||
/** Address from `Name <user@host>` or a bare addr; null if neither is usable. */
|
||||
export function extractAddress(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
const angled = /<([^<>]+)>/.exec(trimmed);
|
||||
const addr = (angled ? angled[1] : trimmed).trim();
|
||||
return looksLikeEmail(addr) ? addr : null;
|
||||
}
|
||||
|
||||
/** Split a comma / semicolon / newline list and keep unique addresses. */
|
||||
export function parseRecipients(value: string): string[] {
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
for (const part of value.split(/[,;\n]+/)) {
|
||||
const addr = extractAddress(part);
|
||||
if (!addr) continue;
|
||||
const key = addr.toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(addr);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function encodeHeader(value: string): string {
|
||||
if (/^[\x20-\x7E]*$/.test(value) && !/[\r\n]/.test(value)) return value;
|
||||
return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`;
|
||||
}
|
||||
|
||||
function rfc5322Date(d: Date): string {
|
||||
return d.toUTCString().replace(/GMT$/, '+0000');
|
||||
}
|
||||
|
||||
function wrap76(b64: string): string {
|
||||
return b64.replace(/.{1,76}/g, (line) => `${line}\r\n`).trimEnd();
|
||||
}
|
||||
|
||||
function isHtmlBody(body: string): boolean {
|
||||
return /^\s*</.test(body);
|
||||
}
|
||||
|
||||
function dotStuff(payload: string): string {
|
||||
return payload.replace(/^\./gm, '..');
|
||||
}
|
||||
|
||||
/** Build a single-part MIME message (plain or HTML). Exported for tests. */
|
||||
export function buildMimeMessage(mail: SmtpMail, now = new Date()): string {
|
||||
const fromAddr = extractAddress(mail.from);
|
||||
const toHeader = mail.to.join(', ');
|
||||
const html = isHtmlBody(mail.body);
|
||||
const id = `<${now.getTime()}.${Math.random().toString(36).slice(2, 10)}@snowluma>`;
|
||||
const headers = [
|
||||
`From: ${mail.from.trim() || (fromAddr ? `<${fromAddr}>` : '')}`,
|
||||
`To: ${toHeader}`,
|
||||
`Subject: ${encodeHeader(mail.subject)}`,
|
||||
`Date: ${rfc5322Date(now)}`,
|
||||
`Message-ID: ${id}`,
|
||||
'MIME-Version: 1.0',
|
||||
`Content-Type: ${html ? 'text/html' : 'text/plain'}; charset=UTF-8`,
|
||||
'Content-Transfer-Encoding: base64',
|
||||
];
|
||||
const body = wrap76(Buffer.from(mail.body, 'utf8').toString('base64'));
|
||||
return `${headers.join(CRLF)}${CRLF}${CRLF}${body}${CRLF}`;
|
||||
}
|
||||
|
||||
interface SmtpReply {
|
||||
code: number;
|
||||
lines: string[];
|
||||
text: string;
|
||||
}
|
||||
|
||||
function consumeReply(buf: string): { reply: SmtpReply; rest: string } | null {
|
||||
let offset = 0;
|
||||
const lines: string[] = [];
|
||||
let code = 0;
|
||||
while (offset < buf.length) {
|
||||
const nl = buf.indexOf('\n', offset);
|
||||
if (nl === -1) return null;
|
||||
const line = buf.slice(offset, nl).replace(/\r$/, '');
|
||||
offset = nl + 1;
|
||||
const m = /^(\d{3})([ -])(.*)$/.exec(line);
|
||||
if (!m) continue;
|
||||
code = Number(m[1]);
|
||||
lines.push(m[3]);
|
||||
if (m[2] === ' ') {
|
||||
return { reply: { code, lines, text: lines.join('\n') }, rest: buf.slice(offset) };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type SmtpSock = net.Socket | tls.TLSSocket;
|
||||
|
||||
function parseCapabilities(reply: SmtpReply): { starttls: boolean; auth: Set<string> } {
|
||||
const auth = new Set<string>();
|
||||
let starttls = false;
|
||||
for (const line of reply.lines) {
|
||||
const u = line.toUpperCase();
|
||||
if (u === 'STARTTLS' || u.startsWith('STARTTLS ')) starttls = true;
|
||||
if (u.startsWith('AUTH ')) {
|
||||
for (const mech of u.slice(5).split(/\s+/)) {
|
||||
if (mech) auth.add(mech);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { starttls, auth };
|
||||
}
|
||||
|
||||
function connectSocket(
|
||||
host: string,
|
||||
port: number,
|
||||
secure: boolean,
|
||||
timeoutMs: number,
|
||||
rejectUnauthorized: boolean,
|
||||
): Promise<SmtpSock> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const sock: SmtpSock = secure
|
||||
? tls.connect({
|
||||
host,
|
||||
port,
|
||||
servername: net.isIP(host) === 0 ? host : undefined,
|
||||
rejectUnauthorized,
|
||||
})
|
||||
: net.connect({ host, port });
|
||||
const fail = (err: Error) => {
|
||||
sock.destroy();
|
||||
reject(err);
|
||||
};
|
||||
sock.setTimeout(timeoutMs);
|
||||
sock.once('timeout', () => fail(new SmtpError('SMTP connection timed out', { code: 'ETIMEDOUT' })));
|
||||
sock.once('error', fail);
|
||||
sock.once(secure ? 'secureConnect' : 'connect', () => {
|
||||
sock.removeAllListeners('timeout');
|
||||
sock.removeAllListeners('error');
|
||||
resolve(sock);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function upgradeTls(
|
||||
socket: net.Socket,
|
||||
host: string,
|
||||
timeoutMs: number,
|
||||
rejectUnauthorized: boolean,
|
||||
): Promise<tls.TLSSocket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const tlsSocket = tls.connect({
|
||||
socket,
|
||||
servername: net.isIP(host) === 0 ? host : undefined,
|
||||
rejectUnauthorized,
|
||||
}, () => resolve(tlsSocket));
|
||||
tlsSocket.setTimeout(timeoutMs);
|
||||
tlsSocket.once('timeout', () => {
|
||||
tlsSocket.destroy();
|
||||
reject(new SmtpError('SMTP STARTTLS timed out', { code: 'ETIMEDOUT' }));
|
||||
});
|
||||
tlsSocket.once('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
class SmtpSession {
|
||||
private buf = '';
|
||||
|
||||
constructor(private socket: SmtpSock) {}
|
||||
|
||||
destroy(): void {
|
||||
this.socket.destroy();
|
||||
}
|
||||
|
||||
attachTimeout(timeoutMs: number, onTimeout: () => void): void {
|
||||
this.socket.setTimeout(timeoutMs);
|
||||
this.socket.once('timeout', onTimeout);
|
||||
}
|
||||
|
||||
async read(): Promise<SmtpReply> {
|
||||
const ready = consumeReply(this.buf);
|
||||
if (ready) {
|
||||
this.buf = ready.rest;
|
||||
return ready.reply;
|
||||
}
|
||||
return new Promise<SmtpReply>((resolve, reject) => {
|
||||
const onData = (chunk: Buffer) => {
|
||||
this.buf += chunk.toString('utf8');
|
||||
const got = consumeReply(this.buf);
|
||||
if (!got) return;
|
||||
this.buf = got.rest;
|
||||
cleanup();
|
||||
resolve(got.reply);
|
||||
};
|
||||
const onError = (err: Error) => {
|
||||
cleanup();
|
||||
reject(err);
|
||||
};
|
||||
const onClose = () => {
|
||||
cleanup();
|
||||
reject(new SmtpError('SMTP connection closed'));
|
||||
};
|
||||
const cleanup = () => {
|
||||
this.socket.removeListener('data', onData);
|
||||
this.socket.removeListener('error', onError);
|
||||
this.socket.removeListener('close', onClose);
|
||||
};
|
||||
this.socket.on('data', onData);
|
||||
this.socket.once('error', onError);
|
||||
this.socket.once('close', onClose);
|
||||
});
|
||||
}
|
||||
|
||||
write(data: string): void {
|
||||
this.socket.write(data);
|
||||
}
|
||||
|
||||
async command(line: string, ok: (code: number) => boolean, label?: string): Promise<SmtpReply> {
|
||||
this.write(line + CRLF);
|
||||
const reply = await this.read();
|
||||
if (!ok(reply.code)) {
|
||||
const name = label ?? line.split(' ')[0] ?? 'SMTP';
|
||||
throw new SmtpError(`${name} failed: ${reply.code} ${reply.text}`.trim(), {
|
||||
responseCode: reply.code,
|
||||
});
|
||||
}
|
||||
return reply;
|
||||
}
|
||||
|
||||
replaceSocket(next: SmtpSock): void {
|
||||
this.socket = next;
|
||||
this.buf = '';
|
||||
}
|
||||
}
|
||||
|
||||
export function formatSmtpError(err: unknown, host: string, port: number): string {
|
||||
if (err instanceof SmtpError) {
|
||||
if (err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND' || err.code === 'ETIMEDOUT') {
|
||||
return `无法连接 SMTP:${host}:${port}`;
|
||||
}
|
||||
if (err.responseCode === 535) return 'SMTP 认证失败';
|
||||
return err.message;
|
||||
}
|
||||
if (err instanceof Error) {
|
||||
const code = (err as NodeJS.ErrnoException).code;
|
||||
if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'ETIMEDOUT') {
|
||||
return `无法连接 SMTP:${host}:${port}`;
|
||||
}
|
||||
if (/self-signed|unable to verify/i.test(err.message)) {
|
||||
return `SMTP 证书不受信任:${host}`;
|
||||
}
|
||||
return err.message || '邮件发送失败';
|
||||
}
|
||||
return '邮件发送失败';
|
||||
}
|
||||
|
||||
export async function sendSmtpMail(mail: SmtpMail, opts: SendSmtpOptions = {}): Promise<void> {
|
||||
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const rejectUnauthorized = opts.rejectUnauthorized ?? true;
|
||||
const fromAddr = extractAddress(mail.from);
|
||||
if (!fromAddr) throw new SmtpError('invalid from address');
|
||||
if (mail.to.length === 0) throw new SmtpError('no recipients');
|
||||
|
||||
let sock = await connectSocket(mail.host, mail.port, mail.secure, timeoutMs, rejectUnauthorized);
|
||||
const session = new SmtpSession(sock);
|
||||
let finished = false;
|
||||
const failTimeout = () => {
|
||||
if (finished) return;
|
||||
session.destroy();
|
||||
};
|
||||
session.attachTimeout(timeoutMs, failTimeout);
|
||||
|
||||
try {
|
||||
const greeting = await session.read();
|
||||
if (greeting.code !== 220) {
|
||||
throw new SmtpError(`SMTP greeting failed: ${greeting.code} ${greeting.text}`.trim(), {
|
||||
responseCode: greeting.code,
|
||||
});
|
||||
}
|
||||
|
||||
const ehlo = async () => session.command('EHLO [127.0.0.1]', (c) => c === 250);
|
||||
let caps = parseCapabilities(await ehlo());
|
||||
|
||||
if (!mail.secure && caps.starttls) {
|
||||
await session.command('STARTTLS', (c) => c === 220);
|
||||
const upgraded = await upgradeTls(sock as net.Socket, mail.host, timeoutMs, rejectUnauthorized);
|
||||
session.replaceSocket(upgraded);
|
||||
session.attachTimeout(timeoutMs, failTimeout);
|
||||
sock = upgraded;
|
||||
caps = parseCapabilities(await ehlo());
|
||||
}
|
||||
|
||||
const user = mail.user?.trim() ?? '';
|
||||
if (user) {
|
||||
await authenticate(session, caps.auth, user, mail.pass ?? '');
|
||||
}
|
||||
|
||||
await session.command(`MAIL FROM:<${fromAddr}>`, (c) => c === 250);
|
||||
for (const rcpt of mail.to) {
|
||||
await session.command(`RCPT TO:<${rcpt}>`, (c) => c === 250 || c === 251);
|
||||
}
|
||||
await session.command('DATA', (c) => c === 354);
|
||||
session.write(dotStuff(buildMimeMessage(mail)));
|
||||
await session.command('.', (c) => c === 250, 'DATA');
|
||||
try {
|
||||
await session.command('QUIT', (c) => c === 221);
|
||||
} catch {
|
||||
// Some relays drop the socket after 250; delivery already succeeded.
|
||||
}
|
||||
finished = true;
|
||||
} catch (err) {
|
||||
finished = true;
|
||||
throw err;
|
||||
} finally {
|
||||
session.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async function authenticate(
|
||||
session: SmtpSession,
|
||||
mechs: Set<string>,
|
||||
user: string,
|
||||
pass: string,
|
||||
): Promise<void> {
|
||||
const hasPlain = mechs.has('PLAIN');
|
||||
const hasLogin = mechs.has('LOGIN');
|
||||
if (hasPlain || !hasLogin) {
|
||||
try {
|
||||
const token = Buffer.from(`\0${user}\0${pass}`, 'utf8').toString('base64');
|
||||
await session.command(`AUTH PLAIN ${token}`, (c) => c === 235, 'AUTH');
|
||||
return;
|
||||
} catch (err) {
|
||||
if (hasPlain && !hasLogin) throw err;
|
||||
if (err instanceof SmtpError && err.responseCode === 535) throw err;
|
||||
}
|
||||
}
|
||||
await loginAuth(session, user, pass);
|
||||
}
|
||||
|
||||
async function loginAuth(session: SmtpSession, user: string, pass: string): Promise<void> {
|
||||
await session.command('AUTH LOGIN', (c) => c === 334, 'AUTH');
|
||||
await session.command(Buffer.from(user, 'utf8').toString('base64'), (c) => c === 334, 'AUTH');
|
||||
await session.command(Buffer.from(pass, 'utf8').toString('base64'), (c) => c === 235, 'AUTH');
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import path from 'node:path';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
SysFaceStore,
|
||||
sysFaceStore,
|
||||
type SysFaceCatalogStorage,
|
||||
} from '@snowluma/protocol/sys-face-store';
|
||||
import { JsonSysFaceCatalogStorage } from '@snowluma/protocol/sys-face-storage';
|
||||
import type { BridgeManager } from './bridge/manager';
|
||||
|
||||
const log = createLogger('SysFace');
|
||||
|
||||
export interface SystemFaceCatalogBindingOptions {
|
||||
store?: SysFaceStore;
|
||||
storage?: SysFaceCatalogStorage;
|
||||
dataRoot?: string;
|
||||
}
|
||||
|
||||
/** Attach the shared system-face catalog to Bridge login edges. The first
|
||||
* account restores + refreshes it; later accounts reuse the same result. */
|
||||
export function bindSystemFaceCatalog(
|
||||
manager: BridgeManager,
|
||||
options: SystemFaceCatalogBindingOptions = {},
|
||||
): void {
|
||||
const store = options.store ?? sysFaceStore;
|
||||
const storage = options.storage ?? new JsonSysFaceCatalogStorage(
|
||||
path.join(options.dataRoot ?? 'data', 'sys-face-catalog.json'),
|
||||
);
|
||||
store.configureStorage(storage);
|
||||
|
||||
manager.addSessionStartedListener((uin, bridge) => {
|
||||
void store.prewarm(bridge).catch((error) => {
|
||||
log.error(
|
||||
'system face catalog login prewarm failed: uin=%s error=%s',
|
||||
uin,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -2,6 +2,12 @@ import { createLogger } from '@snowluma/common/logger';
|
||||
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import {
|
||||
parseTotpStateLenient,
|
||||
prepareTotpStateForRestore,
|
||||
rewrapTotpSecret,
|
||||
type TotpPersistedState,
|
||||
} from './totp';
|
||||
|
||||
const log = createLogger('WebUI.Auth');
|
||||
|
||||
@@ -32,6 +38,7 @@ export interface WebuiAuthState {
|
||||
mustChangePassword: boolean;
|
||||
generatedAt: string;
|
||||
updatedAt: string;
|
||||
totp?: TotpPersistedState;
|
||||
}
|
||||
|
||||
export interface PasswordRule {
|
||||
@@ -91,24 +98,43 @@ export function prepareWebuiAuthStateForRestore(value: unknown): WebuiAuthState
|
||||
if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) {
|
||||
throw new Error('updatedAt must be a valid timestamp');
|
||||
}
|
||||
const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt']);
|
||||
const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt', 'totp']);
|
||||
const unknown = Object.keys(v).find((key) => !allowed.has(key));
|
||||
if (unknown) throw new Error(`unknown field $.${unknown}`);
|
||||
return {
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: v.passwordHash,
|
||||
passwordSalt: v.passwordSalt,
|
||||
mustChangePassword: v.mustChangePassword,
|
||||
generatedAt: v.generatedAt,
|
||||
updatedAt: v.updatedAt,
|
||||
};
|
||||
if (!Object.prototype.hasOwnProperty.call(v, 'totp') || v.totp === undefined) {
|
||||
return state;
|
||||
}
|
||||
state.totp = prepareTotpStateForRestore(v.totp);
|
||||
return state;
|
||||
}
|
||||
|
||||
function isValidState(value: unknown): value is WebuiAuthState {
|
||||
function parseLiveAuthState(value: unknown): WebuiAuthState | null {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
||||
const v = value as Record<string, unknown>;
|
||||
const totpValue = v.totp;
|
||||
const withoutTotp = { ...v };
|
||||
delete withoutTotp.totp;
|
||||
try {
|
||||
prepareWebuiAuthStateForRestore(value);
|
||||
return true;
|
||||
const state = prepareWebuiAuthStateForRestore(
|
||||
Object.prototype.hasOwnProperty.call(v, 'totp')
|
||||
? withoutTotp
|
||||
: value,
|
||||
);
|
||||
const totp = parseTotpStateLenient(totpValue);
|
||||
if (Object.prototype.hasOwnProperty.call(v, 'totp') && totpValue !== undefined && !totp) {
|
||||
log.warn('webui.json totp field is invalid and will be ignored; password credentials are unchanged');
|
||||
}
|
||||
if (totp) state.totp = totp;
|
||||
return state;
|
||||
} catch {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,8 +203,9 @@ export class WebuiAuth {
|
||||
try {
|
||||
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (isValidState(parsed)) {
|
||||
if (parsed.mustChangePassword) {
|
||||
const live = parseLiveAuthState(parsed);
|
||||
if (live) {
|
||||
if (live.mustChangePassword) {
|
||||
// Previous start generated a bootstrap password but the operator
|
||||
// never completed the forced-change flow. The plaintext is gone
|
||||
// (only the hash is on disk, and the log line from last run may
|
||||
@@ -189,7 +216,7 @@ export class WebuiAuth {
|
||||
log.warn('previous bootstrap password was never rotated; regenerated a new one');
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
return new WebuiAuth(parsed, null, false);
|
||||
return new WebuiAuth(live, null, false);
|
||||
}
|
||||
log.error('webui.json schema invalid; backing up and regenerating credentials');
|
||||
backupCorruptConfig();
|
||||
@@ -257,13 +284,20 @@ export class WebuiAuth {
|
||||
}
|
||||
}
|
||||
|
||||
setPassword(newPassword: string): void {
|
||||
setPassword(newPassword: string, currentPassword?: string): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
|
||||
}
|
||||
if (!isStrongPassword(newPassword)) {
|
||||
throw new Error('密码不符合强度要求');
|
||||
}
|
||||
let totp = this.state.totp;
|
||||
if (totp) {
|
||||
if (typeof currentPassword !== 'string' || currentPassword.length === 0) {
|
||||
throw new Error('修改密码需要当前密码以重新保护 2FA 密钥');
|
||||
}
|
||||
totp = rewrapTotpSecret(currentPassword, newPassword, totp);
|
||||
}
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(newPassword, salt);
|
||||
const next: WebuiAuthState = {
|
||||
@@ -272,8 +306,38 @@ export class WebuiAuth {
|
||||
mustChangePassword: false,
|
||||
generatedAt: this.state.generatedAt,
|
||||
updatedAt: new Date().toISOString(),
|
||||
...(totp ? { totp } : {}),
|
||||
};
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
|
||||
totpEnabled(): boolean {
|
||||
return this.state.totp !== undefined;
|
||||
}
|
||||
|
||||
totpStatus(): { enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } {
|
||||
const totp = this.state.totp;
|
||||
if (!totp) return { enabled: false };
|
||||
return {
|
||||
enabled: true,
|
||||
remainingRecoveryCodes: totp.recoveryCodeHashes.length,
|
||||
label: totp.label,
|
||||
};
|
||||
}
|
||||
|
||||
totpState(): TotpPersistedState | undefined {
|
||||
return this.state.totp;
|
||||
}
|
||||
|
||||
persistTotp(totp: TotpPersistedState | undefined): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA');
|
||||
}
|
||||
const next: WebuiAuthState = { ...this.state, updatedAt: new Date().toISOString() };
|
||||
if (totp) next.totp = totp;
|
||||
else delete next.totp;
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,10 @@
|
||||
// can't leak and an import can't path-traverse.
|
||||
//
|
||||
// Credentials are gated by a toggle on both export and import. The credential
|
||||
// set is: webui.json (password hash), key.pem (TLS private key), AND every
|
||||
// OneBot config (onebot.json + per-account onebot_<uin>.json) — those carry the
|
||||
// OneBot access token, so a no-credentials backup must NOT include them.
|
||||
// set is: webui.json (password hash), key.pem (TLS private key),
|
||||
// notifications.json (webhook URLs / SMTP passwords), AND every OneBot config
|
||||
// (onebot.json + per-account onebot_<uin>.json) — those carry access tokens, so
|
||||
// a no-credentials backup must NOT include them.
|
||||
// cert.pem is public so it always travels.
|
||||
//
|
||||
// Pure functions here own bundle validation and semantic preflight. Filesystem
|
||||
@@ -17,10 +18,10 @@ import { normalizeRuntimeConfig } from '@snowluma/common/runtime';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
import { normalizeGlobalSettings } from '@snowluma/onebot/global-config';
|
||||
import { prepareOneBotConfigForRestore } from '@snowluma/onebot/config';
|
||||
import { isIP } from 'node:net';
|
||||
import { normalizeNotificationsConfig } from '../notifications/config';
|
||||
import { prepareWebuiAuthStateForRestore } from './auth';
|
||||
import { MAX_BACKGROUND_BYTES, normalizeStoredUiConfig, sniffImageMime } from './ui-config';
|
||||
import { isValidBindHost } from './listener-exposure';
|
||||
import { validateTlsPair } from './tls';
|
||||
|
||||
export const BACKUP_VERSION = 1;
|
||||
@@ -39,9 +40,8 @@ export interface BackupFileSpec {
|
||||
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: 'notifications.json', binary: false, credential: true },
|
||||
// Global all-accounts SnowLuma settings (rkey fallback servers, …).
|
||||
{ name: 'snowluma.json', binary: false, credential: false },
|
||||
{ name: 'cert.pem', binary: false, credential: false },
|
||||
{ name: 'ui-assets/background', binary: true, credential: false },
|
||||
@@ -450,17 +450,6 @@ function serializeJson(value: unknown): Buffer {
|
||||
return Buffer.from(JSON.stringify(value, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
function isValidBindHost(value: string): boolean {
|
||||
const host = value.trim();
|
||||
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) return false;
|
||||
if (host.includes(':')) return isIP(host) === 6;
|
||||
if (/^[\d.]+$/.test(host)) {
|
||||
return isIP(host) === 4;
|
||||
}
|
||||
const normalized = host.endsWith('.') ? host.slice(0, -1) : host;
|
||||
return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/.test(label));
|
||||
}
|
||||
|
||||
function validateEffectiveTls(restore: PreparedRestoreFile[], opts: PrepareRestoreOptions): void {
|
||||
const byName = new Map(restore.map((file) => [file.name, file.data]));
|
||||
const pairTouched = byName.has('cert.pem') || byName.has('key.pem');
|
||||
|
||||
@@ -28,15 +28,23 @@ export function describeTrustProxy(mode: TrustProxyMode): string {
|
||||
}
|
||||
}
|
||||
|
||||
function isLoopback(ip: string): boolean {
|
||||
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
|
||||
export function isLoopbackClientIp(ip: string): boolean {
|
||||
const normalized = ip.trim().toLowerCase();
|
||||
if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') return true;
|
||||
if (normalized.startsWith('::ffff:')) {
|
||||
return isLoopbackClientIp(normalized.slice('::ffff:'.length));
|
||||
}
|
||||
const octets = normalized.split('.');
|
||||
return octets.length === 4
|
||||
&& octets[0] === '127'
|
||||
&& octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
|
||||
}
|
||||
|
||||
function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
|
||||
switch (mode.kind) {
|
||||
case 'none': return false;
|
||||
case 'all': return true;
|
||||
case 'loopback': return isLoopback(socketIp);
|
||||
case 'loopback': return isLoopbackClientIp(socketIp);
|
||||
case 'ip-list': return mode.ips.has(socketIp);
|
||||
}
|
||||
}
|
||||
@@ -45,11 +53,15 @@ export function pickClientIp(
|
||||
c: Pick<Context, 'req'>,
|
||||
mode: TrustProxyMode,
|
||||
getSocketIp: () => string,
|
||||
fallbackIp = '127.0.0.1',
|
||||
): string {
|
||||
const socketIp = (() => {
|
||||
try { return getSocketIp() || '127.0.0.1'; }
|
||||
catch { return '127.0.0.1'; }
|
||||
})();
|
||||
let socketIp: string;
|
||||
try {
|
||||
socketIp = getSocketIp();
|
||||
} catch {
|
||||
return fallbackIp;
|
||||
}
|
||||
if (!socketIp) return fallbackIp;
|
||||
|
||||
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
|
||||
|
||||
@@ -64,9 +76,14 @@ export function pickClientIp(
|
||||
}
|
||||
|
||||
/** Convenience binding for the live server: read socket via getConnInfo. */
|
||||
export function makeClientIpResolver(mode: TrustProxyMode): (c: Context) => string {
|
||||
return (c) => pickClientIp(c, mode, () => {
|
||||
try { return getConnInfo(c).remote.address ?? '127.0.0.1'; }
|
||||
catch { return '127.0.0.1'; }
|
||||
});
|
||||
export function makeClientIpResolver(
|
||||
mode: TrustProxyMode,
|
||||
fallbackIp = '127.0.0.1',
|
||||
): (c: Context) => string {
|
||||
return (c) => pickClientIp(
|
||||
c,
|
||||
mode,
|
||||
() => getConnInfo(c).remote.address ?? fallbackIp,
|
||||
fallbackIp,
|
||||
);
|
||||
}
|
||||
@@ -23,7 +23,7 @@ import { traceWebuiMutationRequestChunk } from './mutation-trace';
|
||||
|
||||
/** 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');
|
||||
export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'webui-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
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { isIP } from 'node:net';
|
||||
|
||||
export type ListenerExposureCheck =
|
||||
| { ok: true }
|
||||
| { ok: false; code: 'invalid-bind-host' | 'tls-pair-required' };
|
||||
|
||||
/** TCP bind-host accepted by WebUI Listener Exposure (settings, restore, boot). */
|
||||
export function isValidBindHost(value: string): boolean {
|
||||
const host = value.trim();
|
||||
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) return false;
|
||||
if (host.includes(':')) return isIP(host) === 6;
|
||||
if (/^[\d.]+$/.test(host)) {
|
||||
return isIP(host) === 4;
|
||||
}
|
||||
const normalized = host.endsWith('.') ? host.slice(0, -1) : host;
|
||||
return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/.test(label));
|
||||
}
|
||||
|
||||
export function checkListenerExposure(input: {
|
||||
webuiHost: string;
|
||||
tlsEnabled: boolean;
|
||||
pairOk: boolean;
|
||||
}): ListenerExposureCheck {
|
||||
if (!isValidBindHost(input.webuiHost)) return { ok: false, code: 'invalid-bind-host' };
|
||||
if (input.tlsEnabled && !input.pairOk) return { ok: false, code: 'tls-pair-required' };
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { assessAccessToken } from '@snowluma/common/access-token';
|
||||
import type { OneBotConfig } from '@snowluma/onebot/types';
|
||||
import { isLoopbackClientIp } from './client-ip';
|
||||
|
||||
function isLoopbackBindHost(host: string | undefined): boolean {
|
||||
const value = host?.trim().toLowerCase().replace(/^\[|\]$/gu, '').replace(/\.$/u, '') ?? '';
|
||||
if (!value) return false;
|
||||
if (value === 'localhost' || value.endsWith('.localhost')) return true;
|
||||
return isLoopbackClientIp(value);
|
||||
}
|
||||
|
||||
export class OneBotAccessTokenPolicyError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'OneBotAccessTokenPolicyError';
|
||||
}
|
||||
}
|
||||
|
||||
export interface OneBotAccessTokenPolicyOptions {
|
||||
clientIp: string;
|
||||
uin: string;
|
||||
}
|
||||
|
||||
type InboundKind = 'httpServers' | 'wsServers';
|
||||
|
||||
const INBOUND_KINDS: readonly InboundKind[] = ['httpServers', 'wsServers'];
|
||||
|
||||
function sameTokenAtPreviousIdentity(
|
||||
previous: OneBotConfig['networks'][InboundKind],
|
||||
next: OneBotConfig['networks'][InboundKind],
|
||||
nextName: string,
|
||||
nextToken: string,
|
||||
index: number,
|
||||
): boolean {
|
||||
const named = previous.find((adapter) => adapter.name === nextName);
|
||||
if (named && (named.accessToken ?? '') === nextToken) return true;
|
||||
// Preserve a legacy token when the operator only renames the same list item.
|
||||
// Reordering keeps names stable and is covered by the lookup above.
|
||||
const sameIndex = previous[index];
|
||||
return sameIndex !== undefined
|
||||
&& !next.some((adapter) => adapter.name === sameIndex.name)
|
||||
&& (sameIndex.accessToken ?? '') === nextToken;
|
||||
}
|
||||
|
||||
export function validateOneBotAccessTokenChanges(
|
||||
previous: OneBotConfig | null,
|
||||
next: OneBotConfig,
|
||||
options: OneBotAccessTokenPolicyOptions,
|
||||
): void {
|
||||
const allowEmptyFromClient = isLoopbackClientIp(options.clientIp);
|
||||
for (const kind of INBOUND_KINDS) {
|
||||
const previousList = previous?.networks[kind] ?? [];
|
||||
const nextList = next.networks[kind];
|
||||
for (let index = 0; index < nextList.length; index += 1) {
|
||||
const adapter = nextList[index];
|
||||
const token = adapter.accessToken ?? '';
|
||||
if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) continue;
|
||||
|
||||
if (!token) {
|
||||
if (!allowEmptyFromClient && !isLoopbackBindHost(adapter.host)) {
|
||||
throw new OneBotAccessTokenPolicyError(
|
||||
`节点“${adapter.name}”未绑定本机地址,远程保存必须填写令牌;请生成令牌或将主机改为 127.0.0.1。`,
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const host = adapter.host ?? '0.0.0.0';
|
||||
const assessment = assessAccessToken(token, [
|
||||
options.uin,
|
||||
adapter.name,
|
||||
kind,
|
||||
host,
|
||||
adapter.port,
|
||||
]);
|
||||
if (assessment.reason === 'too-short') {
|
||||
throw new OneBotAccessTokenPolicyError(
|
||||
`节点“${adapter.name}”的令牌至少需要 16 个字符;请重新生成或继续补充。`,
|
||||
);
|
||||
}
|
||||
if (!assessment.acceptable) {
|
||||
throw new OneBotAccessTokenPolicyError(
|
||||
`节点“${adapter.name}”的令牌容易被猜中;请重新生成随机令牌。`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import net from 'net';
|
||||
|
||||
function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
|
||||
function isPortAvailable(port: number, host = '127.0.0.1'): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
let settled = false;
|
||||
@@ -27,11 +27,15 @@ function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
|
||||
* Find an available TCP port starting from `start`, advancing by 1 up to `maxTries` attempts.
|
||||
* Skips reserved/invalid port numbers.
|
||||
*/
|
||||
export async function findAvailablePort(start: number, maxTries = 50): Promise<number> {
|
||||
export async function findAvailablePort(
|
||||
start: number,
|
||||
options: { maxTries?: number; host?: string } = {},
|
||||
): Promise<number> {
|
||||
const { maxTries = 50, host = '127.0.0.1' } = options;
|
||||
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
if (port > 65535) break;
|
||||
if (await isPortAvailable(port)) return port;
|
||||
if (await isPortAvailable(port, host)) return port;
|
||||
port += 1;
|
||||
}
|
||||
throw new Error(`No available TCP port found near ${start}`);
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { bodyLimit } from 'hono/body-limit';
|
||||
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
||||
import type { Context, Hono, MiddlewareHandler } from 'hono';
|
||||
|
||||
export const LOGIN_BODY_LIMIT_BYTES = 16 * 1024;
|
||||
const AVATAR_SESSION_COOKIE = 'snowluma_avatar_session';
|
||||
const AVATAR_SESSION_MAX_AGE_SECONDS = 24 * 60 * 60;
|
||||
|
||||
function isJsonMediaType(value: string | undefined): boolean {
|
||||
const mediaType = value?.split(';', 1)[0]?.trim().toLowerCase() ?? '';
|
||||
return mediaType === 'application/json' || mediaType.endsWith('+json');
|
||||
}
|
||||
|
||||
/** Install guards before the login route is registered. */
|
||||
export function registerLoginRequestSecurity(app: Hono): void {
|
||||
app.use('/api/login', bodyLimit({
|
||||
maxSize: LOGIN_BODY_LIMIT_BYTES,
|
||||
onError: (c) => c.json({ success: false, message: '请求体过大' }, 413),
|
||||
}));
|
||||
app.use('/api/login', async (c, next) => {
|
||||
if (!isJsonMediaType(c.req.header('content-type'))) {
|
||||
return c.json({ success: false, message: 'Content-Type 必须为 application/json' }, 415);
|
||||
}
|
||||
return next();
|
||||
});
|
||||
}
|
||||
|
||||
/** Minimal response policy that does not restrict the current script/style bundle. */
|
||||
export const webuiSecurityHeaders: MiddlewareHandler = async (c, next) => {
|
||||
await next();
|
||||
c.res.headers.set('X-Frame-Options', 'DENY');
|
||||
c.res.headers.set('X-Content-Type-Options', 'nosniff');
|
||||
c.res.headers.set('Referrer-Policy', 'no-referrer');
|
||||
c.res.headers.set(
|
||||
'Content-Security-Policy',
|
||||
"frame-ancestors 'none'; base-uri 'self'; object-src 'none'",
|
||||
);
|
||||
};
|
||||
|
||||
export function extractBearerToken(request: Request): string {
|
||||
const authorization = request.headers.get('authorization');
|
||||
return authorization?.startsWith('Bearer ') ? authorization.slice(7) : '';
|
||||
}
|
||||
|
||||
const avatarCookieOptions = (secure: boolean) => ({
|
||||
httpOnly: true,
|
||||
sameSite: 'Strict' as const,
|
||||
secure,
|
||||
path: '/avatar',
|
||||
});
|
||||
|
||||
export function setAvatarSessionCookie(c: Context, token: string, secure: boolean): void {
|
||||
setCookie(c, AVATAR_SESSION_COOKIE, token, {
|
||||
...avatarCookieOptions(secure),
|
||||
maxAge: AVATAR_SESSION_MAX_AGE_SECONDS,
|
||||
});
|
||||
}
|
||||
|
||||
export function clearAvatarSessionCookie(c: Context, secure: boolean): void {
|
||||
deleteCookie(c, AVATAR_SESSION_COOKIE, avatarCookieOptions(secure));
|
||||
}
|
||||
|
||||
export function readAvatarSessionToken(c: Context): string {
|
||||
return getCookie(c, AVATAR_SESSION_COOKIE) ?? '';
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
subscribeLogs,
|
||||
} from '@snowluma/common/logger';
|
||||
import {
|
||||
assertValidOneBotConfig,
|
||||
loadOneBotConfig,
|
||||
OneBotConfigValidationError,
|
||||
saveOneBotConfig,
|
||||
@@ -38,6 +39,13 @@ import os from 'os';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
|
||||
import { completeWebuiLogin, invalidateOtherSessions } from './webui-login';
|
||||
import {
|
||||
beginTotpEnrollment,
|
||||
confirmTotpEnrollment,
|
||||
decideSecondFactorLogin,
|
||||
regenerateRecoveryCodes,
|
||||
} from './totp';
|
||||
import {
|
||||
EULA_ACCEPT_ENV,
|
||||
getAgreementsPayload,
|
||||
@@ -47,8 +55,9 @@ import {
|
||||
recordConsent,
|
||||
resolveEnvironmentConsent,
|
||||
} from './consent';
|
||||
import { resolveTlsContext, validateTlsPair } from './tls';
|
||||
import { coerceSettingsPatch } from './system-settings';
|
||||
import { requireTlsContext, resolveTlsContext, validateTlsPair } from './tls';
|
||||
import { coerceSettingsPatch, evaluateSettingsSave, tlsCertDeletionBlocked } from './system-settings';
|
||||
import { checkListenerExposure } from './listener-exposure';
|
||||
import { buildBackup } from './backup';
|
||||
import { restoreBackup, RestoreTransactionError, type RestorePhase } from './restore';
|
||||
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
|
||||
@@ -61,6 +70,10 @@ import { startConnectionDiffLoop } from './connection-diff-loop';
|
||||
import { comparableConnectionSnapshot } from './connection-snapshot';
|
||||
import { traceAuthenticatedWebuiMutation } from './mutation-trace';
|
||||
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
||||
import {
|
||||
OneBotAccessTokenPolicyError,
|
||||
validateOneBotAccessTokenChanges,
|
||||
} from './onebot-token-policy';
|
||||
import { findAvailablePort } from './port';
|
||||
import {
|
||||
clearBackgroundImage,
|
||||
@@ -79,6 +92,14 @@ import type { NotificationManager } from '../notifications/manager';
|
||||
import { StorageManagementService } from './storage-management';
|
||||
import { registerStorageRoutes } from './storage-routes';
|
||||
import { LogStorageSettingsManager } from './storage-settings';
|
||||
import {
|
||||
clearAvatarSessionCookie,
|
||||
extractBearerToken,
|
||||
readAvatarSessionToken,
|
||||
registerLoginRequestSecurity,
|
||||
setAvatarSessionCookie,
|
||||
webuiSecurityHeaders,
|
||||
} from './request-security';
|
||||
|
||||
const log = createLogger('WebUI');
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -90,10 +111,18 @@ interface SessionInfo {
|
||||
|
||||
const sessionTokens = new Map<string, SessionInfo>();
|
||||
const loginAttempts = new Map<string, { count: number; resetAt: number }>();
|
||||
const totpEnrollments = new Map<string, {
|
||||
secret: string;
|
||||
issuer: string;
|
||||
accountName: string;
|
||||
expiresAt: number;
|
||||
}>();
|
||||
|
||||
const LOGIN_MAX_ATTEMPTS = 5;
|
||||
const LOGIN_LOCKOUT_MS = 15 * 60 * 1000;
|
||||
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
const TOTP_ENROLL_TTL_MS = 10 * 60 * 1000;
|
||||
const DEFAULT_TOTP_ISSUER = 'SnowLuma';
|
||||
const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60;
|
||||
|
||||
@@ -199,21 +228,6 @@ const CONSENT_ALLOWLIST = new Set([
|
||||
'/api/logout',
|
||||
]);
|
||||
|
||||
// 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–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
|
||||
@@ -231,6 +245,21 @@ function purgeExpiredTokens() {
|
||||
for (const [ip, attempt] of loginAttempts) {
|
||||
if (now > attempt.resetAt) loginAttempts.delete(ip);
|
||||
}
|
||||
for (const [token, enrollment] of totpEnrollments) {
|
||||
if (now > enrollment.expiresAt) totpEnrollments.delete(token);
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeTotpLabelPart(value: unknown, fallback: string): string {
|
||||
if (typeof value !== 'string') return fallback;
|
||||
const trimmed = value.replace(/[\r\n\t]/g, '').trim();
|
||||
if (!trimmed) return fallback;
|
||||
return trimmed.slice(0, 64);
|
||||
}
|
||||
|
||||
function defaultTotpAccountName(): string {
|
||||
const host = os.hostname().trim();
|
||||
return host || 'admin';
|
||||
}
|
||||
|
||||
|
||||
@@ -442,13 +471,30 @@ export async function initWebUI(
|
||||
hookManager?: HookManager,
|
||||
notificationManager?: NotificationManager,
|
||||
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: StateBus } = {},
|
||||
): Promise<{ port: number }> {
|
||||
): Promise<{ port: number; stop: () => Promise<void> }> {
|
||||
const host = listener.host || '127.0.0.1';
|
||||
const tlsEnabled = listener.tlsEnabled === true;
|
||||
const bootCheck = checkListenerExposure({
|
||||
webuiHost: host,
|
||||
tlsEnabled,
|
||||
pairOk: resolveTlsContext('config').ok,
|
||||
});
|
||||
if (!bootCheck.ok) {
|
||||
const reason = bootCheck.code === 'invalid-bind-host'
|
||||
? `bind host is not a valid TCP address: ${host}`
|
||||
: 'TLS is enabled but the certificate/private-key pair is unusable';
|
||||
throw new Error(`WebUI listener cannot start: ${reason}`);
|
||||
}
|
||||
// Resolve the client IP for per-IP rate limiting from the configured
|
||||
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
|
||||
// SNOWLUMA_WEBUI_TRUST_PROXY which loadRuntimeConfig already merged in).
|
||||
// Default ('') = trust the TCP socket peer only (cannot be spoofed).
|
||||
const trustProxyMode = parseTrustProxy(listener.trustProxy);
|
||||
const getClientIp = makeClientIpResolver(trustProxyMode);
|
||||
// Security decisions must not silently turn an unreadable socket peer into
|
||||
// localhost. The regular resolver keeps its compatibility fallback for
|
||||
// rate-limit bucketing; this resolver fails closed with an empty address.
|
||||
const getSecurityClientIp = makeClientIpResolver(trustProxyMode, '');
|
||||
|
||||
// Connection-status diff loop: OneBot adapters don't emit events for
|
||||
// listening/connected/client-count changes, so we poll the snapshot at
|
||||
@@ -473,10 +519,9 @@ export async function initWebUI(
|
||||
// adapter detail strings at sub-second cadence wasn't required. If it
|
||||
// becomes one, surface client-count as a structured field on
|
||||
// AdapterStatus and include it in the comparable.
|
||||
let connectionDiffLoop: ReturnType<typeof startConnectionDiffLoop> | undefined;
|
||||
if (listener.stateBus) {
|
||||
// Handle deliberately discarded — initWebUI has no shutdown path; the
|
||||
// loop's setInterval is .unref'd so it doesn't pin the event loop.
|
||||
startConnectionDiffLoop({
|
||||
connectionDiffLoop = startConnectionDiffLoop({
|
||||
bus: listener.stateBus,
|
||||
getSnapshot: () => oneBotManager.getConnectionStatuses(),
|
||||
pickComparable: comparableConnectionSnapshot,
|
||||
@@ -491,7 +536,7 @@ export async function initWebUI(
|
||||
const auth = WebuiAuth.load();
|
||||
const initialPassword = auth.takeInitialPassword();
|
||||
if (auth.isDevMode()) {
|
||||
log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword);
|
||||
log.warn('dev mode enabled with the configured development credential');
|
||||
log.warn('dev mode skips config/webui.json and password rotation');
|
||||
} else if (initialPassword) {
|
||||
log.info('════════════════════════════════════════════════════════════════');
|
||||
@@ -533,6 +578,8 @@ export async function initWebUI(
|
||||
}
|
||||
|
||||
const app = new Hono();
|
||||
app.use('*', webuiSecurityHeaders);
|
||||
registerLoginRequestSecurity(app);
|
||||
const storageManagement = new StorageManagementService({
|
||||
dataDir: 'data',
|
||||
getLogStatus: getLogStorageStatus,
|
||||
@@ -583,10 +630,7 @@ export async function initWebUI(
|
||||
// nothing sensitive (no layout, no secrets) — see ui-config.ts.
|
||||
if (reqPath === '/api/login' || reqPath === '/api/ui/public') return next();
|
||||
|
||||
const authHeader = c.req.header('Authorization');
|
||||
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
|
||||
const queryToken = TOKEN_QUERY_ALLOWLIST.has(reqPath) ? (c.req.query('token') ?? '') : '';
|
||||
const token = bearerToken || queryToken;
|
||||
const token = extractBearerToken(c.req.raw);
|
||||
if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
|
||||
|
||||
const info = sessionTokens.get(token);
|
||||
@@ -631,31 +675,48 @@ export async function initWebUI(
|
||||
return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429);
|
||||
}
|
||||
|
||||
let body: { password?: unknown };
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const password = typeof body.password === 'string' ? body.password : '';
|
||||
if (!auth.verify(password)) {
|
||||
|
||||
const result = completeWebuiLogin(auth, body, now);
|
||||
if (result.kind === 'bad-request') {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
if (result.kind === 'bad-password' || result.kind === 'bad-second-factor') {
|
||||
const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS };
|
||||
current.count += 1;
|
||||
if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS;
|
||||
loginAttempts.set(ip, current);
|
||||
return c.json({ success: false, message: '密码错误' }, 401);
|
||||
const message = result.kind === 'bad-second-factor' ? '验证码不正确' : '密码错误';
|
||||
return c.json({ success: false, message }, 401);
|
||||
}
|
||||
if (result.kind === 'needs-totp') {
|
||||
return c.json({ success: false, needsTotp: true });
|
||||
}
|
||||
|
||||
loginAttempts.delete(ip);
|
||||
if (result.totpState) {
|
||||
try {
|
||||
auth.persistTotp(result.totpState);
|
||||
} catch (err) {
|
||||
log.warn('persist totp after login failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '登录失败' }, 500);
|
||||
}
|
||||
}
|
||||
const token = randomBytes(32).toString('hex');
|
||||
const mustChange = auth.mustChangePassword();
|
||||
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange });
|
||||
return c.json({ success: true, token, mustChangePassword: mustChange });
|
||||
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: result.mustChangePassword });
|
||||
setAvatarSessionCookie(c, token, listener.tlsEnabled === true);
|
||||
return c.json({ success: true, token, mustChangePassword: result.mustChangePassword });
|
||||
});
|
||||
|
||||
app.post('/api/logout', (c) => {
|
||||
const token = c.get('sessionToken' as never) as string | undefined;
|
||||
if (token) sessionTokens.delete(token);
|
||||
clearAvatarSessionCookie(c, listener.tlsEnabled === true);
|
||||
return c.json({ success: true });
|
||||
});
|
||||
|
||||
@@ -700,7 +761,7 @@ export async function initWebUI(
|
||||
return c.json({ success: false, message: '新密码不得与旧密码相同' }, 400);
|
||||
}
|
||||
try {
|
||||
auth.setPassword(newPassword);
|
||||
auth.setPassword(newPassword, oldPassword);
|
||||
} catch (err) {
|
||||
log.warn('change password failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '密码修改失败' }, 400);
|
||||
@@ -709,10 +770,172 @@ export async function initWebUI(
|
||||
// password was compromised, the attacker may already hold the current
|
||||
// token; rotating credentials must rotate sessions too.
|
||||
sessionTokens.clear();
|
||||
clearAvatarSessionCookie(c, listener.tlsEnabled === true);
|
||||
log.info('password updated; all sessions invalidated');
|
||||
return c.json({ success: true, requireRelogin: true });
|
||||
});
|
||||
|
||||
const totpDisabledInDev = () => auth.isDevMode();
|
||||
|
||||
app.get('/api/auth/totp', (c) => {
|
||||
if (totpDisabledInDev()) {
|
||||
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
|
||||
}
|
||||
return c.json(auth.totpStatus());
|
||||
});
|
||||
|
||||
app.post('/api/auth/totp/begin', async (c) => {
|
||||
if (totpDisabledInDev()) {
|
||||
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
|
||||
}
|
||||
if (auth.totpEnabled()) {
|
||||
return c.json({ success: false, message: '2FA 已开启' }, 409);
|
||||
}
|
||||
const token = c.get('sessionToken' as never) as string;
|
||||
let body: Record<string, unknown> = {};
|
||||
try {
|
||||
const parsed = await c.req.json();
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
body = parsed as Record<string, unknown>;
|
||||
}
|
||||
} catch {
|
||||
body = {};
|
||||
}
|
||||
const issuer = sanitizeTotpLabelPart(body.issuer, DEFAULT_TOTP_ISSUER);
|
||||
const accountName = sanitizeTotpLabelPart(body.accountName, defaultTotpAccountName());
|
||||
const now = Date.now();
|
||||
const existing = totpEnrollments.get(token);
|
||||
const secret = existing && existing.expiresAt > now ? existing.secret : undefined;
|
||||
const enrollment = beginTotpEnrollment({ issuer, accountName, secret });
|
||||
totpEnrollments.set(token, {
|
||||
secret: enrollment.secret,
|
||||
issuer,
|
||||
accountName,
|
||||
expiresAt: now + TOTP_ENROLL_TTL_MS,
|
||||
});
|
||||
return c.json({
|
||||
success: true,
|
||||
secret: enrollment.secret,
|
||||
otpauthUrl: enrollment.otpauthUrl,
|
||||
issuer: enrollment.issuer,
|
||||
accountName: enrollment.accountName,
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/api/auth/totp/confirm', async (c) => {
|
||||
if (totpDisabledInDev()) {
|
||||
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
|
||||
}
|
||||
if (auth.totpEnabled()) {
|
||||
return c.json({ success: false, message: '2FA 已开启' }, 409);
|
||||
}
|
||||
const token = c.get('sessionToken' as never) as string;
|
||||
let body: { password?: unknown; code?: unknown };
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const password = typeof body.password === 'string' ? body.password : '';
|
||||
const code = typeof body.code === 'string' ? body.code : '';
|
||||
if (!auth.verify(password)) {
|
||||
return c.json({ success: false, message: '当前密码不正确' }, 401);
|
||||
}
|
||||
const pending = totpEnrollments.get(token);
|
||||
if (!pending || pending.expiresAt <= Date.now()) {
|
||||
totpEnrollments.delete(token);
|
||||
return c.json({ success: false, message: '请先开始绑定' }, 400);
|
||||
}
|
||||
try {
|
||||
const enabled = confirmTotpEnrollment({
|
||||
password,
|
||||
secret: pending.secret,
|
||||
code,
|
||||
label: `${pending.issuer} (${pending.accountName})`,
|
||||
atMs: Date.now(),
|
||||
});
|
||||
auth.persistTotp(enabled.state);
|
||||
totpEnrollments.delete(token);
|
||||
invalidateOtherSessions(sessionTokens, token);
|
||||
log.info('webui 2FA enabled; other sessions invalidated');
|
||||
return c.json({ success: true, recoveryCodes: enabled.recoveryCodes });
|
||||
} catch (err) {
|
||||
log.warn('totp confirm failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '验证码不正确' }, 401);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/auth/totp/disable', async (c) => {
|
||||
if (totpDisabledInDev()) {
|
||||
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
|
||||
}
|
||||
if (!auth.totpEnabled()) {
|
||||
return c.json({ success: false, message: '2FA 未开启' }, 400);
|
||||
}
|
||||
const token = c.get('sessionToken' as never) as string;
|
||||
let body: { password?: unknown; totp?: unknown; recoveryCode?: unknown };
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const password = typeof body.password === 'string' ? body.password : '';
|
||||
if (!auth.verify(password)) {
|
||||
return c.json({ success: false, message: '当前密码不正确' }, 401);
|
||||
}
|
||||
const decision = decideSecondFactorLogin({
|
||||
totpEnabled: true,
|
||||
state: auth.totpState(),
|
||||
password,
|
||||
totp: typeof body.totp === 'string' ? body.totp : undefined,
|
||||
recoveryCode: typeof body.recoveryCode === 'string' ? body.recoveryCode : undefined,
|
||||
atMs: Date.now(),
|
||||
});
|
||||
if (decision.kind !== 'ok') {
|
||||
return c.json({ success: false, message: '验证码不正确' }, 401);
|
||||
}
|
||||
auth.persistTotp(undefined);
|
||||
totpEnrollments.delete(token);
|
||||
invalidateOtherSessions(sessionTokens, token);
|
||||
log.info('webui 2FA disabled; other sessions invalidated');
|
||||
return c.json({ success: true });
|
||||
});
|
||||
|
||||
app.post('/api/auth/totp/recovery-codes', async (c) => {
|
||||
if (totpDisabledInDev()) {
|
||||
return c.json({ success: false, message: '开发模式已禁用 2FA' }, 400);
|
||||
}
|
||||
const state = auth.totpState();
|
||||
if (!state) {
|
||||
return c.json({ success: false, message: '2FA 未开启' }, 400);
|
||||
}
|
||||
let body: { password?: unknown; totp?: unknown };
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const password = typeof body.password === 'string' ? body.password : '';
|
||||
const totp = typeof body.totp === 'string' ? body.totp : '';
|
||||
if (!auth.verify(password)) {
|
||||
return c.json({ success: false, message: '当前密码不正确' }, 401);
|
||||
}
|
||||
try {
|
||||
const next = regenerateRecoveryCodes({
|
||||
password,
|
||||
state,
|
||||
totp,
|
||||
atMs: Date.now(),
|
||||
});
|
||||
auth.persistTotp(next.state);
|
||||
log.info('webui 2FA recovery codes regenerated');
|
||||
return c.json({ success: true, recoveryCodes: next.recoveryCodes });
|
||||
} catch (err) {
|
||||
log.warn('totp recovery regenerate failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '验证码不正确' }, 401);
|
||||
}
|
||||
});
|
||||
|
||||
// ─── EULA / PRIVACY consent ──────────────────────────────────────────────
|
||||
// Both are bearer-gated (consent is collected AFTER login) and live in the
|
||||
// consent + must-change allowlists so they're reachable during onboarding.
|
||||
@@ -750,6 +973,12 @@ export async function initWebUI(
|
||||
|
||||
// ─── Avatar proxy (uin validated) ────────────────────────────────────────
|
||||
app.get('/avatar/:uin', async (c) => {
|
||||
const sessionToken = readAvatarSessionToken(c);
|
||||
const session = sessionTokens.get(sessionToken);
|
||||
if (!session || Date.now() > session.expiresAt) {
|
||||
if (sessionToken) sessionTokens.delete(sessionToken);
|
||||
return c.text('unauthorized', 401);
|
||||
}
|
||||
const uin = c.req.param('uin');
|
||||
if (!UIN_REGEX.test(uin)) return c.text('invalid uin', 400);
|
||||
|
||||
@@ -768,7 +997,8 @@ export async function initWebUI(
|
||||
return new Response(cached.body, {
|
||||
headers: {
|
||||
'Content-Type': cached.contentType,
|
||||
'Cache-Control': `public, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`,
|
||||
'Cache-Control': `private, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`,
|
||||
Vary: 'Cookie',
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -793,7 +1023,13 @@ export async function initWebUI(
|
||||
});
|
||||
|
||||
// ─── Read-only API ───────────────────────────────────────────────────────
|
||||
app.get('/api/status', (c) => c.json({ status: 'running' }));
|
||||
app.get('/api/status', (c) => {
|
||||
// Refresh the path-scoped avatar cookie for a still-valid localStorage
|
||||
// session (for example after upgrading from a version without the cookie).
|
||||
const token = c.get('sessionToken' as never) as string;
|
||||
setAvatarSessionCookie(c, token, listener.tlsEnabled === true);
|
||||
return c.json({ status: 'running' });
|
||||
});
|
||||
|
||||
// Advisory update check — compares the running build against the latest
|
||||
// GitHub stable release and links the user to it. Read-only: SnowLuma
|
||||
@@ -905,11 +1141,13 @@ export async function initWebUI(
|
||||
}
|
||||
const coerced = coerceSettingsPatch(body);
|
||||
if (!coerced.ok) return c.json({ success: false, message: coerced.error }, 400);
|
||||
// Enabling TLS without a usable cert would brick HTTPS on restart — block it.
|
||||
if (coerced.patch.webuiTls?.enabled && !resolveTlsContext('config').ok) {
|
||||
return c.json({ success: false, message: '启用 TLS 前请先上传有效的证书与私钥' }, 400);
|
||||
}
|
||||
const saved = updateRuntimeConfig(coerced.patch);
|
||||
const evaluated = evaluateSettingsSave(
|
||||
readRuntimeConfig(),
|
||||
coerced.patch,
|
||||
resolveTlsContext('config').ok,
|
||||
);
|
||||
if (!evaluated.ok) return c.json({ success: false, message: evaluated.error }, 400);
|
||||
const saved = updateRuntimeConfig(evaluated.patch);
|
||||
return c.json({
|
||||
success: true,
|
||||
settings: {
|
||||
@@ -978,6 +1216,9 @@ export async function initWebUI(
|
||||
});
|
||||
|
||||
app.delete('/api/system/tls/cert', (c) => {
|
||||
if (tlsCertDeletionBlocked(readRuntimeConfig().webuiTls?.enabled === true)) {
|
||||
return c.json({ success: false, message: '请先关闭 TLS 再删除证书' }, 400);
|
||||
}
|
||||
try {
|
||||
rmSync(SYSTEM_CERT_PATH, { force: true });
|
||||
rmSync(SYSTEM_KEY_PATH, { force: true });
|
||||
@@ -1287,11 +1528,36 @@ export async function initWebUI(
|
||||
return c.json({ success: false, saved: false, applied: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
|
||||
let nextConfig: OneBotConfig;
|
||||
try {
|
||||
saveOneBotConfig(uin, body as OneBotConfig);
|
||||
assertValidOneBotConfig(body);
|
||||
nextConfig = body;
|
||||
|
||||
let previousConfig: OneBotConfig | null = null;
|
||||
try {
|
||||
previousConfig = loadOneBotConfig(uin);
|
||||
} catch (err) {
|
||||
// A damaged existing file must not strand the recovery UI. Treat the
|
||||
// submitted endpoints as new, apply the full policy, and let the
|
||||
// subsequent atomic save either repair the file or fail visibly.
|
||||
log.warn(
|
||||
'could not read prior OneBot config for uin=%s before save: %s',
|
||||
uin,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
|
||||
validateOneBotAccessTokenChanges(previousConfig, nextConfig, {
|
||||
clientIp: getSecurityClientIp(c),
|
||||
uin,
|
||||
});
|
||||
saveOneBotConfig(uin, nextConfig);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
if (err instanceof OneBotConfigValidationError) {
|
||||
if (
|
||||
err instanceof OneBotConfigValidationError
|
||||
|| err instanceof OneBotAccessTokenPolicyError
|
||||
) {
|
||||
log.warn('reject invalid config for uin=%s: %s', uin, message);
|
||||
return c.json({ success: false, saved: false, applied: false, message }, 400);
|
||||
}
|
||||
@@ -1303,7 +1569,7 @@ export async function initWebUI(
|
||||
// Apply the exact validated value that was persisted above. Re-reading
|
||||
// the path here would race concurrent POSTs (request A could load B and
|
||||
// falsely report that A was applied).
|
||||
const apply = await oneBotManager.reloadConfig(uin, body as OneBotConfig);
|
||||
const apply = await oneBotManager.reloadConfig(uin, nextConfig);
|
||||
const message = !apply.online
|
||||
? '配置保存成功,当前会话未在线,将在下次连接时生效。'
|
||||
: apply.applied
|
||||
@@ -1530,33 +1796,35 @@ export async function initWebUI(
|
||||
);
|
||||
});
|
||||
|
||||
const finalPort = await findAvailablePort(desiredPort);
|
||||
const finalPort = await findAvailablePort(desiredPort, { host });
|
||||
if (finalPort !== desiredPort) {
|
||||
log.warn('port %d is in use, using %d instead', desiredPort, finalPort);
|
||||
}
|
||||
boundPort = finalPort;
|
||||
|
||||
const host = listener.host || '0.0.0.0';
|
||||
|
||||
// TLS: only when explicitly enabled AND the on-disk cert/key load. A bad
|
||||
// or missing cert must never brick the WebUI — fall back to HTTP + warn.
|
||||
// TLS is an explicit transport promise. Once enabled, an unusable pair must
|
||||
// abort startup instead of silently exposing the listener over plaintext.
|
||||
let tlsServe: { createServer: typeof createHttpsServer; serverOptions: { cert: Buffer; key: Buffer } } | undefined;
|
||||
let scheme = 'http';
|
||||
if (listener.tlsEnabled) {
|
||||
const tls = resolveTlsContext('config');
|
||||
if (tls.ok && tls.cert && tls.key) {
|
||||
tlsServe = { createServer: createHttpsServer, serverOptions: { cert: tls.cert, key: tls.key } };
|
||||
scheme = 'https';
|
||||
} else {
|
||||
log.warn('TLS enabled but cert/key unusable (%s) — serving over HTTP instead', tls.reason);
|
||||
}
|
||||
const tls = requireTlsContext('config');
|
||||
tlsServe = { createServer: createHttpsServer, serverOptions: tls };
|
||||
scheme = 'https';
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => {
|
||||
const listeningServer = await new Promise<ReturnType<typeof serve>>((resolve) => {
|
||||
const server = serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => {
|
||||
log.info(`listening ${scheme}://${host}:${info.port}`);
|
||||
resolve();
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
return { port: finalPort };
|
||||
return {
|
||||
port: finalPort,
|
||||
async stop() {
|
||||
connectionDiffLoop?.dispose();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
listeningServer.close((err) => (err ? reject(err) : resolve()));
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -14,8 +14,9 @@
|
||||
* 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.
|
||||
* `dispose()` sets a latch and neuters the bus. BridgeManager listeners stay
|
||||
* attached; further session edges publish nothing. Process shutdown disposes
|
||||
* this wiring before Hook teardown so exit-time closed is not a WebUI invalidate.
|
||||
*/
|
||||
|
||||
import { StateBus } from './state-bus';
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// nested `webuiTls.enabled`.
|
||||
|
||||
import type { RuntimeConfig } from '@snowluma/common/runtime';
|
||||
import { checkListenerExposure } from './listener-exposure';
|
||||
|
||||
export type SettingsPatch = Partial<Pick<RuntimeConfig, 'webuiPort' | 'webuiHost' | 'webuiTls' | 'trustProxy'>>;
|
||||
|
||||
@@ -50,3 +51,25 @@ export function coerceSettingsPatch(body: unknown): CoerceResult {
|
||||
|
||||
return { ok: true, patch };
|
||||
}
|
||||
|
||||
const SETTINGS_ERRORS: Record<'invalid-bind-host' | 'tls-pair-required', string> = {
|
||||
'invalid-bind-host': '绑定地址不是有效的 TCP 地址',
|
||||
'tls-pair-required': '启用 TLS 前请先上传有效的证书与私钥',
|
||||
};
|
||||
|
||||
/** Validate the listener that would be persisted after applying `patch` to `current`. */
|
||||
export function evaluateSettingsSave(
|
||||
current: RuntimeConfig,
|
||||
patch: SettingsPatch,
|
||||
pairOk: boolean,
|
||||
): CoerceResult {
|
||||
const webuiHost = patch.webuiHost ?? current.webuiHost ?? '127.0.0.1';
|
||||
const tlsEnabled = patch.webuiTls?.enabled ?? current.webuiTls?.enabled ?? false;
|
||||
const check = checkListenerExposure({ webuiHost, tlsEnabled, pairOk });
|
||||
if (!check.ok) return { ok: false, error: SETTINGS_ERRORS[check.code] };
|
||||
return { ok: true, patch };
|
||||
}
|
||||
|
||||
export function tlsCertDeletionBlocked(tlsEnabled: boolean): boolean {
|
||||
return tlsEnabled;
|
||||
}
|
||||
@@ -20,6 +20,11 @@ export interface TlsResolution {
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface RequiredTlsContext {
|
||||
cert: Buffer;
|
||||
key: Buffer;
|
||||
}
|
||||
|
||||
function errMsg(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
@@ -55,3 +60,12 @@ export function resolveTlsContext(configDir: string): TlsResolution {
|
||||
if (!valid.ok) return { ok: false, reason: valid.reason };
|
||||
return { ok: true, cert, key };
|
||||
}
|
||||
|
||||
/** Resolve the configured pair for an enabled listener or abort startup. */
|
||||
export function requireTlsContext(configDir: string): RequiredTlsContext {
|
||||
const resolved = resolveTlsContext(configDir);
|
||||
if (!resolved.ok || !resolved.cert || !resolved.key) {
|
||||
throw new Error(`TLS listener cannot start: ${resolved.reason ?? 'certificate pair is unusable'}`);
|
||||
}
|
||||
return { cert: resolved.cert, key: resolved.key };
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
|
||||
const TOTP_PERIOD_SECONDS = 30;
|
||||
const TOTP_WINDOW = 1;
|
||||
const TOTP_DIGITS = 6;
|
||||
const RECOVERY_CODE_COUNT = 8;
|
||||
const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
const WRAP_SALT_BYTES = 16;
|
||||
const WRAP_IV_BYTES = 12;
|
||||
const WRAP_KEY_BYTES = 32;
|
||||
const SCRYPT_N = 16384;
|
||||
const SCRYPT_R = 8;
|
||||
const SCRYPT_P = 1;
|
||||
|
||||
export interface WrappedTotpSecret {
|
||||
wrapSalt: string;
|
||||
iv: string;
|
||||
ciphertext: string;
|
||||
authTag: string;
|
||||
}
|
||||
|
||||
export interface TotpPersistedState extends WrappedTotpSecret {
|
||||
recoveryCodeHashes: string[];
|
||||
lastUsedStep: number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface TotpEnrollment {
|
||||
secret: string;
|
||||
otpauthUrl: string;
|
||||
issuer: string;
|
||||
accountName: string;
|
||||
}
|
||||
|
||||
function totpFromSecret(secretBase32: string, issuer = '', accountName = 'admin'): OTPAuth.TOTP {
|
||||
return new OTPAuth.TOTP({
|
||||
issuer,
|
||||
label: accountName,
|
||||
algorithm: 'SHA1',
|
||||
digits: TOTP_DIGITS,
|
||||
period: TOTP_PERIOD_SECONDS,
|
||||
secret: OTPAuth.Secret.fromBase32(secretBase32),
|
||||
});
|
||||
}
|
||||
|
||||
export function verifyTotpCode(
|
||||
secretBase32: string,
|
||||
code: string,
|
||||
atMs: number,
|
||||
lastUsedStep?: number,
|
||||
): { ok: true; step: number } | { ok: false } {
|
||||
const token = code.replace(/\s/g, '');
|
||||
if (!/^\d{6}$/.test(token)) return { ok: false };
|
||||
|
||||
let totp: OTPAuth.TOTP;
|
||||
try {
|
||||
totp = totpFromSecret(secretBase32);
|
||||
} catch {
|
||||
return { ok: false };
|
||||
}
|
||||
const delta = totp.validate({ token, timestamp: atMs, window: TOTP_WINDOW });
|
||||
if (delta === null) return { ok: false };
|
||||
|
||||
const step = totp.counter({ timestamp: atMs }) + delta;
|
||||
if (lastUsedStep !== undefined && step === lastUsedStep) return { ok: false };
|
||||
return { ok: true, step };
|
||||
}
|
||||
|
||||
function deriveWrapKey(password: string, salt: Buffer): Buffer {
|
||||
return scryptSync(password, salt, WRAP_KEY_BYTES, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
|
||||
}
|
||||
|
||||
export function wrapTotpSecret(password: string, secret: string): WrappedTotpSecret {
|
||||
const wrapSalt = randomBytes(WRAP_SALT_BYTES);
|
||||
const iv = randomBytes(WRAP_IV_BYTES);
|
||||
const key = deriveWrapKey(password, wrapSalt);
|
||||
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
||||
const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
|
||||
return {
|
||||
wrapSalt: wrapSalt.toString('hex'),
|
||||
iv: iv.toString('hex'),
|
||||
ciphertext: ciphertext.toString('hex'),
|
||||
authTag: cipher.getAuthTag().toString('hex'),
|
||||
};
|
||||
}
|
||||
|
||||
export function unwrapTotpSecret(password: string, wrapped: WrappedTotpSecret): string | null {
|
||||
try {
|
||||
const wrapSalt = Buffer.from(wrapped.wrapSalt, 'hex');
|
||||
const iv = Buffer.from(wrapped.iv, 'hex');
|
||||
const ciphertext = Buffer.from(wrapped.ciphertext, 'hex');
|
||||
const authTag = Buffer.from(wrapped.authTag, 'hex');
|
||||
if (wrapSalt.length !== WRAP_SALT_BYTES || iv.length !== WRAP_IV_BYTES || authTag.length !== 16) {
|
||||
return null;
|
||||
}
|
||||
const key = deriveWrapKey(password, wrapSalt);
|
||||
const decipher = createDecipheriv('aes-256-gcm', key, iv);
|
||||
decipher.setAuthTag(authTag);
|
||||
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function randomRecoveryChunk(): string {
|
||||
const bytes = randomBytes(4);
|
||||
let chunk = '';
|
||||
for (let i = 0; i < 4; i++) {
|
||||
chunk += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length];
|
||||
}
|
||||
return chunk;
|
||||
}
|
||||
|
||||
export function generateRecoveryCodes(): string[] {
|
||||
const codes = new Set<string>();
|
||||
while (codes.size < RECOVERY_CODE_COUNT) {
|
||||
codes.add(`${randomRecoveryChunk()}-${randomRecoveryChunk()}`);
|
||||
}
|
||||
return [...codes];
|
||||
}
|
||||
|
||||
export function normalizeRecoveryCode(code: string): string {
|
||||
return code.replace(/[-\s]/g, '').toUpperCase();
|
||||
}
|
||||
|
||||
export function hashRecoveryCode(code: string): string {
|
||||
return createHash('sha256').update(normalizeRecoveryCode(code), 'utf8').digest('hex');
|
||||
}
|
||||
|
||||
function hashesEqual(left: string, right: string): boolean {
|
||||
const a = Buffer.from(left, 'hex');
|
||||
const b = Buffer.from(right, 'hex');
|
||||
if (a.length !== b.length || a.length === 0) return false;
|
||||
return timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
export function consumeRecoveryCode(
|
||||
code: string,
|
||||
hashes: readonly string[],
|
||||
): { ok: true; remainingHashes: string[] } | { ok: false } {
|
||||
const candidate = hashRecoveryCode(code);
|
||||
const index = hashes.findIndex((hash) => hashesEqual(hash, candidate));
|
||||
if (index < 0) return { ok: false };
|
||||
return { ok: true, remainingHashes: hashes.filter((_, i) => i !== index) };
|
||||
}
|
||||
|
||||
export function beginTotpEnrollment(options: {
|
||||
issuer: string;
|
||||
accountName: string;
|
||||
secret?: string;
|
||||
}): TotpEnrollment {
|
||||
const secret = options.secret ?? new OTPAuth.Secret({ size: 20 }).base32;
|
||||
const totp = totpFromSecret(secret, options.issuer, options.accountName);
|
||||
return {
|
||||
secret,
|
||||
otpauthUrl: totp.toString(),
|
||||
issuer: options.issuer,
|
||||
accountName: options.accountName,
|
||||
};
|
||||
}
|
||||
|
||||
export function confirmTotpEnrollment(options: {
|
||||
password: string;
|
||||
secret: string;
|
||||
code: string;
|
||||
label: string;
|
||||
atMs: number;
|
||||
}): { state: TotpPersistedState; recoveryCodes: string[] } {
|
||||
const verified = verifyTotpCode(options.secret, options.code, options.atMs);
|
||||
if (!verified.ok) {
|
||||
throw new Error('验证码不正确');
|
||||
}
|
||||
const recoveryCodes = generateRecoveryCodes();
|
||||
return {
|
||||
recoveryCodes,
|
||||
state: {
|
||||
...wrapTotpSecret(options.password, options.secret),
|
||||
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
|
||||
lastUsedStep: verified.step,
|
||||
label: options.label,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function verifySecondFactor(options: {
|
||||
password: string;
|
||||
state: TotpPersistedState;
|
||||
atMs: number;
|
||||
totp?: string;
|
||||
recoveryCode?: string;
|
||||
}): { ok: true; state: TotpPersistedState } | { ok: false } {
|
||||
if (typeof options.recoveryCode === 'string' && options.recoveryCode.length > 0) {
|
||||
const consumed = consumeRecoveryCode(options.recoveryCode, options.state.recoveryCodeHashes);
|
||||
if (!consumed.ok) return { ok: false };
|
||||
return { ok: true, state: { ...options.state, recoveryCodeHashes: consumed.remainingHashes } };
|
||||
}
|
||||
if (typeof options.totp !== 'string') return { ok: false };
|
||||
const secret = unwrapTotpSecret(options.password, options.state);
|
||||
if (secret === null) return { ok: false };
|
||||
const checked = verifyTotpCode(secret, options.totp, options.atMs, options.state.lastUsedStep);
|
||||
if (!checked.ok) return { ok: false };
|
||||
return { ok: true, state: { ...options.state, lastUsedStep: checked.step } };
|
||||
}
|
||||
|
||||
export type SecondFactorDecision =
|
||||
| { kind: 'needs-totp' }
|
||||
| { kind: 'bad-second-factor' }
|
||||
| { kind: 'ok'; state?: TotpPersistedState };
|
||||
|
||||
export function decideSecondFactorLogin(options: {
|
||||
totpEnabled: boolean;
|
||||
state?: TotpPersistedState;
|
||||
password: string;
|
||||
totp?: string;
|
||||
recoveryCode?: string;
|
||||
atMs: number;
|
||||
}): SecondFactorDecision {
|
||||
if (!options.totpEnabled) return { kind: 'ok' };
|
||||
if (!options.state) return { kind: 'bad-second-factor' };
|
||||
const totp = typeof options.totp === 'string' && options.totp.trim().length > 0
|
||||
? options.totp.trim()
|
||||
: undefined;
|
||||
const recoveryCode = typeof options.recoveryCode === 'string' && options.recoveryCode.trim().length > 0
|
||||
? options.recoveryCode.trim()
|
||||
: undefined;
|
||||
if (!totp && !recoveryCode) return { kind: 'needs-totp' };
|
||||
const result = verifySecondFactor({
|
||||
password: options.password,
|
||||
state: options.state,
|
||||
atMs: options.atMs,
|
||||
totp,
|
||||
recoveryCode,
|
||||
});
|
||||
if (!result.ok) return { kind: 'bad-second-factor' };
|
||||
return { kind: 'ok', state: result.state };
|
||||
}
|
||||
|
||||
export function regenerateRecoveryCodes(options: {
|
||||
password: string;
|
||||
state: TotpPersistedState;
|
||||
totp: string;
|
||||
atMs: number;
|
||||
}): { state: TotpPersistedState; recoveryCodes: string[] } {
|
||||
const verified = verifySecondFactor({
|
||||
password: options.password,
|
||||
state: options.state,
|
||||
totp: options.totp,
|
||||
atMs: options.atMs,
|
||||
});
|
||||
if (!verified.ok) {
|
||||
throw new Error('验证码不正确');
|
||||
}
|
||||
const recoveryCodes = generateRecoveryCodes();
|
||||
return {
|
||||
recoveryCodes,
|
||||
state: {
|
||||
...verified.state,
|
||||
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function rewrapTotpSecret(
|
||||
oldPassword: string,
|
||||
newPassword: string,
|
||||
state: TotpPersistedState,
|
||||
): TotpPersistedState {
|
||||
const secret = unwrapTotpSecret(oldPassword, state);
|
||||
if (secret === null) {
|
||||
throw new Error('无法使用当前密码解开 2FA 密钥');
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
...wrapTotpSecret(newPassword, secret),
|
||||
};
|
||||
}
|
||||
|
||||
const HEX = /^[0-9a-f]+$/i;
|
||||
|
||||
function isWrappedShape(value: Record<string, unknown>): value is WrappedTotpSecret & Record<string, unknown> {
|
||||
return typeof value.wrapSalt === 'string'
|
||||
&& HEX.test(value.wrapSalt)
|
||||
&& value.wrapSalt.length === WRAP_SALT_BYTES * 2
|
||||
&& typeof value.iv === 'string'
|
||||
&& HEX.test(value.iv)
|
||||
&& value.iv.length === WRAP_IV_BYTES * 2
|
||||
&& typeof value.ciphertext === 'string'
|
||||
&& HEX.test(value.ciphertext)
|
||||
&& value.ciphertext.length > 0
|
||||
&& value.ciphertext.length % 2 === 0
|
||||
&& typeof value.authTag === 'string'
|
||||
&& HEX.test(value.authTag)
|
||||
&& value.authTag.length === 32;
|
||||
}
|
||||
|
||||
export function prepareTotpStateForRestore(value: unknown): TotpPersistedState {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('totp state must be an object');
|
||||
}
|
||||
const v = value as Record<string, unknown>;
|
||||
if (!isWrappedShape(v)) {
|
||||
throw new Error('totp wrapped secret fields are invalid');
|
||||
}
|
||||
if (!Array.isArray(v.recoveryCodeHashes)
|
||||
|| v.recoveryCodeHashes.length > RECOVERY_CODE_COUNT
|
||||
|| v.recoveryCodeHashes.some((hash) => typeof hash !== 'string' || !/^[0-9a-f]{64}$/i.test(hash))) {
|
||||
throw new Error('totp recoveryCodeHashes must be SHA-256 hex strings');
|
||||
}
|
||||
if (typeof v.lastUsedStep !== 'number' || !Number.isInteger(v.lastUsedStep) || v.lastUsedStep < 0) {
|
||||
throw new Error('totp lastUsedStep must be a non-negative integer');
|
||||
}
|
||||
if (typeof v.label !== 'string' || v.label.length === 0 || v.label.length > 128) {
|
||||
throw new Error('totp label must be a non-empty string');
|
||||
}
|
||||
const allowed = new Set(['wrapSalt', 'iv', 'ciphertext', 'authTag', 'recoveryCodeHashes', 'lastUsedStep', 'label']);
|
||||
const unknown = Object.keys(v).find((key) => !allowed.has(key));
|
||||
if (unknown) throw new Error(`unknown totp field $.${unknown}`);
|
||||
return {
|
||||
wrapSalt: v.wrapSalt.toLowerCase(),
|
||||
iv: v.iv.toLowerCase(),
|
||||
ciphertext: v.ciphertext.toLowerCase(),
|
||||
authTag: v.authTag.toLowerCase(),
|
||||
recoveryCodeHashes: v.recoveryCodeHashes.map((hash) => (hash as string).toLowerCase()),
|
||||
lastUsedStep: v.lastUsedStep,
|
||||
label: v.label,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseTotpStateLenient(value: unknown): TotpPersistedState | undefined {
|
||||
if (value === undefined || value === null) return undefined;
|
||||
try {
|
||||
return prepareTotpStateForRestore(value);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { decideSecondFactorLogin, type TotpPersistedState } from './totp';
|
||||
|
||||
export interface WebuiLoginAuth {
|
||||
verify(password: string): boolean;
|
||||
totpEnabled(): boolean;
|
||||
totpState(): TotpPersistedState | undefined;
|
||||
mustChangePassword(): boolean;
|
||||
}
|
||||
|
||||
export type WebuiLoginResult =
|
||||
| { kind: 'bad-request' }
|
||||
| { kind: 'bad-password' }
|
||||
| { kind: 'needs-totp' }
|
||||
| { kind: 'bad-second-factor' }
|
||||
| { kind: 'ok'; mustChangePassword: boolean; totpState?: TotpPersistedState };
|
||||
|
||||
function readString(value: unknown): string {
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
export function completeWebuiLogin(auth: WebuiLoginAuth, body: unknown, atMs: number): WebuiLoginResult {
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
||||
return { kind: 'bad-request' };
|
||||
}
|
||||
const record = body as Record<string, unknown>;
|
||||
const password = readString(record.password);
|
||||
if (!auth.verify(password)) {
|
||||
return { kind: 'bad-password' };
|
||||
}
|
||||
const decision = decideSecondFactorLogin({
|
||||
totpEnabled: auth.totpEnabled(),
|
||||
state: auth.totpState(),
|
||||
password,
|
||||
totp: readString(record.totp) || undefined,
|
||||
recoveryCode: readString(record.recoveryCode) || undefined,
|
||||
atMs,
|
||||
});
|
||||
if (decision.kind === 'needs-totp') return { kind: 'needs-totp' };
|
||||
if (decision.kind === 'bad-second-factor') return { kind: 'bad-second-factor' };
|
||||
return {
|
||||
kind: 'ok',
|
||||
mustChangePassword: auth.mustChangePassword(),
|
||||
...(decision.state ? { totpState: decision.state } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function invalidateOtherSessions<T>(sessions: Map<string, T>, keepToken: string): void {
|
||||
for (const token of sessions.keys()) {
|
||||
if (token !== keepToken) sessions.delete(token);
|
||||
}
|
||||
}
|
||||
@@ -127,7 +127,10 @@ export interface MockBridge {
|
||||
nickname: string;
|
||||
findUidByUin: ReturnType<typeof vi.fn>;
|
||||
findUinByUid: ReturnType<typeof vi.fn>;
|
||||
resolveUin: ReturnType<typeof vi.fn>;
|
||||
findGroupMember: ReturnType<typeof vi.fn>;
|
||||
updateFriendRemark: ReturnType<typeof vi.fn>;
|
||||
updateGroupRemark: ReturnType<typeof vi.fn>;
|
||||
forgetGroup: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
events: { emit: ReturnType<typeof vi.fn> };
|
||||
@@ -159,7 +162,10 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
|
||||
nickname: 'self-nick',
|
||||
findUidByUin: vi.fn(() => 'cached-uid'),
|
||||
findUinByUid: vi.fn(() => 0),
|
||||
resolveUin: vi.fn(async () => null),
|
||||
findGroupMember: vi.fn(() => null),
|
||||
updateFriendRemark: vi.fn(() => true),
|
||||
updateGroupRemark: vi.fn(() => true),
|
||||
forgetGroup: vi.fn(),
|
||||
...(overrides.identity ?? {}),
|
||||
} as MockBridge['identity'],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type {
|
||||
OidbBase,
|
||||
@@ -7,7 +8,9 @@ import type {
|
||||
OidbFriend,
|
||||
OidbFriendCategory,
|
||||
OidbRobotUinRangeResponse,
|
||||
OidbSvcTrpcTcp0x88D_0Response,
|
||||
OidbSvcTrpcTcp0xFD4_1Response,
|
||||
OidbSvcTrpcTcp0xFE5_2Response,
|
||||
OidbSvcTrpcTcp0xFE7_3Response,
|
||||
} from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
@@ -18,6 +21,36 @@ import type {
|
||||
|
||||
import { ContactsApi } from '../../src/bridge/apis/contacts';
|
||||
|
||||
interface ObservedGroupRequestUserByUin {
|
||||
uin?: pb<1, uint_32>;
|
||||
name?: pb<2, string>;
|
||||
}
|
||||
|
||||
interface ObservedGroupRequestUserByUid {
|
||||
uid?: pb<1, string>;
|
||||
name?: pb<2, string>;
|
||||
}
|
||||
|
||||
interface ObservedGroupRequestGroup {
|
||||
groupUin?: pb<1, uint_32>;
|
||||
groupName?: pb<2, string>;
|
||||
}
|
||||
|
||||
interface ObservedGroupRequest<TUser> {
|
||||
sequence?: pb<1, uint_64>;
|
||||
eventType?: pb<2, uint_32>;
|
||||
state?: pb<3, uint_32>;
|
||||
group?: pb<4, ObservedGroupRequestGroup>;
|
||||
target?: pb<5, TUser>;
|
||||
invitor?: pb<6, TUser>;
|
||||
operatorUser?: pb<7, TUser>;
|
||||
comment?: pb<10, string>;
|
||||
}
|
||||
|
||||
interface ObservedGroupRequestResponse<TUser> {
|
||||
requests?: pb_repeated<1, ObservedGroupRequest<TUser>>;
|
||||
}
|
||||
|
||||
function friend(
|
||||
uin: number,
|
||||
categoryId: number,
|
||||
@@ -86,6 +119,58 @@ function memberListPacket(body: OidbSvcTrpcTcp0xFE7_3Response): SendPacketResult
|
||||
};
|
||||
}
|
||||
|
||||
function groupListPacket(body: OidbSvcTrpcTcp0xFE5_2Response): SendPacketResult {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>({ body }),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function groupDetailPacket(body: OidbSvcTrpcTcp0x88D_0Response): SendPacketResult {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({ body }),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function groupRequestPacketByUin(
|
||||
body: ObservedGroupRequestResponse<ObservedGroupRequestUserByUin>,
|
||||
): SendPacketResult {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<OidbBase<ObservedGroupRequestResponse<ObservedGroupRequestUserByUin>>>({ body }),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function groupRequestPacketByUid(
|
||||
body: ObservedGroupRequestResponse<ObservedGroupRequestUserByUid>,
|
||||
): SendPacketResult {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(
|
||||
protobuf_encode<OidbBase<ObservedGroupRequestResponse<ObservedGroupRequestUserByUid>>>({ body }),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function apiForPages(pages: OidbSvcTrpcTcp0xFD4_1Response[]) {
|
||||
let index = 0;
|
||||
const sendRawPacket = vi.fn(async (
|
||||
@@ -131,6 +216,206 @@ function apiForCategoryChange(roster: OidbSvcTrpcTcp0xFD4_1Response) {
|
||||
return { api, sendRawPacket };
|
||||
}
|
||||
|
||||
describe('apis/contacts / group roster', () => {
|
||||
it('maps QQ group remarks into the returned and remembered roster', async () => {
|
||||
const rememberGroups = vi.fn();
|
||||
const sendRawPacket = vi.fn(async () => groupListPacket({
|
||||
groups: [{
|
||||
groupUin: 123456789,
|
||||
info: {
|
||||
groupName: 'Project',
|
||||
memberCount: 42,
|
||||
memberMax: 500,
|
||||
shutUpAllTimestamp: 4_294_967_295,
|
||||
},
|
||||
customInfo: { remark: ' My Project ' },
|
||||
}],
|
||||
}));
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { rememberGroups },
|
||||
} as any);
|
||||
|
||||
const groups = await api.fetchGroupList();
|
||||
|
||||
expect(groups).toEqual([expect.objectContaining({
|
||||
groupId: 123456789,
|
||||
groupName: 'Project',
|
||||
remark: ' My Project ',
|
||||
memberCount: 42,
|
||||
memberMax: 500,
|
||||
allMuted: true,
|
||||
})]);
|
||||
expect(rememberGroups).toHaveBeenCalledWith(groups);
|
||||
});
|
||||
|
||||
// #490: `memo` prefers the announcement, so a group with both fields set used
|
||||
// to lose its description entirely. The description must stay readable.
|
||||
it('keeps the group description readable when an announcement is also set (#490)', async () => {
|
||||
const sendRawPacket = vi.fn(async () => groupListPacket({
|
||||
groups: [{
|
||||
groupUin: 123456789,
|
||||
info: {
|
||||
groupName: 'Both Set',
|
||||
description: '简介正文',
|
||||
announcement: '公告正文',
|
||||
},
|
||||
}],
|
||||
}));
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { rememberGroups: vi.fn() },
|
||||
} as any);
|
||||
|
||||
const [group] = await api.fetchGroupList();
|
||||
|
||||
expect(group?.memo).toBe('公告正文');
|
||||
expect(group?.description).toBe('简介正文');
|
||||
});
|
||||
|
||||
it('reports the description for a group that has no announcement (#490)', async () => {
|
||||
const sendRawPacket = vi.fn(async () => groupListPacket({
|
||||
groups: [{
|
||||
groupUin: 123456789,
|
||||
info: { groupName: 'Description Only', description: '只有简介' },
|
||||
}],
|
||||
}));
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { rememberGroups: vi.fn() },
|
||||
} as any);
|
||||
|
||||
const [group] = await api.fetchGroupList();
|
||||
|
||||
// memo still falls back to the description (unchanged pre-#490 behaviour).
|
||||
expect(group?.memo).toBe('只有简介');
|
||||
expect(group?.description).toBe('只有简介');
|
||||
});
|
||||
|
||||
it('leaves the description unset on a non-member detail lookup (#490)', async () => {
|
||||
const sendRawPacket = vi.fn(async () => groupDetailPacket({
|
||||
groupInfo: { uin: 123456789n, results: { name: 'Not Joined', noticePreview: '公告预览' } },
|
||||
}));
|
||||
const api = new ContactsApi({ sendRawPacket, identity: {} } as any);
|
||||
|
||||
const detail = await api.fetchGroupDetail(123456789);
|
||||
|
||||
// 0x88D_0 has no description tag, so there is nothing to expose — the field
|
||||
// must stay absent rather than echo the announcement preview.
|
||||
expect(detail?.memo).toBe('公告预览');
|
||||
expect(detail?.description).toBeUndefined();
|
||||
});
|
||||
|
||||
it('maps the group-wide mute timestamp from a single-group detail', async () => {
|
||||
const sendRawPacket = vi.fn(async () => groupDetailPacket({
|
||||
groupInfo: {
|
||||
uin: 123456789n,
|
||||
results: {
|
||||
name: 'Muted Group',
|
||||
shutUpAllTimestamp: 4_294_967_295,
|
||||
},
|
||||
},
|
||||
}));
|
||||
const api = new ContactsApi({ sendRawPacket, identity: {} } as any);
|
||||
|
||||
const detail = await api.fetchGroupDetail(123456789);
|
||||
|
||||
expect(detail).toEqual(expect.objectContaining({
|
||||
groupId: 123456789,
|
||||
groupName: 'Muted Group',
|
||||
allMuted: true,
|
||||
}));
|
||||
});
|
||||
|
||||
it('treats a past group-mute expire as unmuted (#356)', async () => {
|
||||
const sendRawPacket = vi.fn(async () => groupListPacket({
|
||||
groups: [{
|
||||
groupUin: 123456789,
|
||||
info: {
|
||||
groupName: 'Was Muted',
|
||||
shutUpAllTimestamp: 1_700_000_000,
|
||||
},
|
||||
}],
|
||||
}));
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { rememberGroups: vi.fn() },
|
||||
} as any);
|
||||
|
||||
const groups = await api.fetchGroupList();
|
||||
expect(groups[0]?.allMuted).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('apis/contacts / group requests', () => {
|
||||
it('maps the native numeric-account response into directly actionable requests', async () => {
|
||||
const rememberGroupRequests = vi.fn();
|
||||
const findUidByUin = vi.fn((uin: number) => uin === 1_234_567_890 ? 'cached_target_uid' : null);
|
||||
const sendRawPacket = vi.fn(async () => groupRequestPacketByUin({
|
||||
requests: [{
|
||||
sequence: 1_785_525_232_784_291n,
|
||||
eventType: 7,
|
||||
state: 1,
|
||||
group: { groupUin: 1_095_186_374, groupName: 'group' },
|
||||
target: { uin: 1_234_567_890, name: 'requester' },
|
||||
invitor: { uin: 2_345_678_901, name: 'inviter' },
|
||||
operatorUser: { uin: 3_456_789_012, name: 'operator' },
|
||||
comment: 'please',
|
||||
}],
|
||||
}));
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { findUidByUin, rememberGroupRequests },
|
||||
} as any);
|
||||
|
||||
const requests = await api.fetchGroupRequests(false);
|
||||
|
||||
expect(requests).toEqual([expect.objectContaining({
|
||||
groupId: 1_095_186_374,
|
||||
targetUid: 'cached_target_uid',
|
||||
targetUin: 1_234_567_890,
|
||||
invitorUin: 2_345_678_901,
|
||||
operatorUin: 3_456_789_012,
|
||||
sequence: 1_785_525_232_784_291,
|
||||
notifyType: 7,
|
||||
eventType: 1,
|
||||
filtered: false,
|
||||
})]);
|
||||
expect(rememberGroupRequests).toHaveBeenCalledWith(requests);
|
||||
});
|
||||
|
||||
it('retains the UID-form response for correlating real-time request pushes', async () => {
|
||||
const rememberGroupRequests = vi.fn();
|
||||
const findUinByUid = vi.fn((uid: string) => uid === 'target_uid' ? 1_234_567_890 : null);
|
||||
const sendRawPacket = vi.fn(async () => groupRequestPacketByUid({
|
||||
requests: [{
|
||||
sequence: 42n,
|
||||
eventType: 7,
|
||||
state: 1,
|
||||
group: { groupUin: 999, groupName: 'group' },
|
||||
target: { uid: 'target_uid', name: 'requester' },
|
||||
invitor: { uid: 'inviter_uid', name: 'inviter' },
|
||||
operatorUser: { uid: 'operator_uid', name: 'operator' },
|
||||
}],
|
||||
}));
|
||||
const api = new ContactsApi({
|
||||
sendRawPacket,
|
||||
identity: { findUinByUid, rememberGroupRequests },
|
||||
} as any);
|
||||
|
||||
const requests = await api.fetchGroupRequestsByUid(true);
|
||||
|
||||
expect(requests).toEqual([expect.objectContaining({
|
||||
targetUid: 'target_uid',
|
||||
targetUin: 1_234_567_890,
|
||||
invitorUid: 'inviter_uid',
|
||||
operatorUid: 'operator_uid',
|
||||
filtered: true,
|
||||
})]);
|
||||
expect(rememberGroupRequests).toHaveBeenCalledWith(requests);
|
||||
});
|
||||
});
|
||||
|
||||
describe('apis/contacts / categorized friend roster', () => {
|
||||
it('keeps fetchFriendList flat while traversing cookie pages', async () => {
|
||||
const cookie = Uint8Array.from([0x01]);
|
||||
@@ -395,3 +680,18 @@ describe('apis/contacts / robot group-member classification', () => {
|
||||
expect(rememberGroupMembers).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe('apis/contacts / invite-card pending application', () => {
|
||||
it('remembers, reads, and reverse-looks-up a card sequence', () => {
|
||||
const api = new ContactsApi({ identity: { uin: '10001' } } as any);
|
||||
expect(api.getGroupInviteCardSequence(12345)).toBeUndefined();
|
||||
|
||||
api.rememberGroupInviteCardSequence(12345, 778899);
|
||||
api.rememberGroupInviteCardSequence(0, 1);
|
||||
api.rememberGroupInviteCardSequence(1, 0);
|
||||
|
||||
expect(api.getGroupInviteCardSequence(12345)).toBe(778899);
|
||||
expect(api.findGroupInviteCardGroupBySequence(778899)).toBe(12345);
|
||||
expect(api.findGroupInviteCardGroupBySequence(1)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,8 @@ import type { QQEventVariant } from '@snowluma/protocol/events';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbGroupTodo,
|
||||
OidbQueryGroupTopBannersReq,
|
||||
OidbQueryGroupTopBannersResp,
|
||||
OidbStrangerStatusReq,
|
||||
OidbStrangerStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
@@ -15,7 +17,7 @@ import type {
|
||||
OidbAiVoiceResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/media';
|
||||
|
||||
// Post-namespace migration: ExtrasApi forwards 6 OIDB cmds through
|
||||
// Post-namespace migration: ExtrasApi forwards OIDB cmds through
|
||||
// namespaces under @snowluma/protocol/oidb-services/extras. Tests assert
|
||||
// against bridge.sendRawPacket directly.
|
||||
import { ExtrasApi, AiVoiceChatType } from '../../src/bridge/apis/extras';
|
||||
@@ -28,7 +30,21 @@ function packResponse(body: Uint8Array) {
|
||||
};
|
||||
}
|
||||
|
||||
describe('apis/extras / group todo (0xF90)', () => {
|
||||
describe('apis/extras / group todo (0x9474 / 0xF90)', () => {
|
||||
it('getGroupTodoList dispatches the todo-only banner query', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbQueryGroupTopBannersResp>>({ body: {} }),
|
||||
));
|
||||
|
||||
await expect(new ExtrasApi(bridge as any).getGroupTodoList(12345)).resolves.toEqual([]);
|
||||
|
||||
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
expect(wireName).toBe('OidbSvcTrpcTcp.0x9474_0');
|
||||
const env = protobuf_decode<OidbBase<OidbQueryGroupTopBannersReq>>(bytes);
|
||||
expect(env.body).toEqual({ groupId: 12345n, bannerFlag: 1 });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['setGroupTodo', 'OidbSvcTrpcTcp.0xf90_1'] as const,
|
||||
['completeGroupTodo', 'OidbSvcTrpcTcp.0xf90_2'] as const,
|
||||
@@ -48,7 +64,7 @@ describe('apis/extras / getStrangerStatus (0xFE1_2)', () => {
|
||||
it('issues the FE1_2 query with key=27372', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 5n } } } }),
|
||||
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { properties: { entries: [{ key: 27372, value: 5n }] } } } }),
|
||||
));
|
||||
await new ExtrasApi(bridge as any).getStrangerStatus(100200);
|
||||
const [wireName, bytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
@@ -62,7 +78,7 @@ describe('apis/extras / getStrangerStatus (0xFE1_2)', () => {
|
||||
it('low-band values (≤10) map to status*10 with ext_status=0', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 7n } } } }),
|
||||
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { properties: { entries: [{ key: 27372, value: 7n }] } } } }),
|
||||
));
|
||||
expect(await new ExtrasApi(bridge as any).getStrangerStatus(1)).toEqual({ status: 70, ext_status: 0 });
|
||||
});
|
||||
@@ -70,7 +86,7 @@ describe('apis/extras / getStrangerStatus (0xFE1_2)', () => {
|
||||
it('high-band values decompose into the (0xff00 + (>>16 & 0xff)) status word', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { status: { value: 0x42F100n } } } }),
|
||||
protobuf_encode<OidbBase<OidbStrangerStatusResp>>({ body: { data: { properties: { entries: [{ key: 27372, value: 0x42F100n }] } } } }),
|
||||
));
|
||||
const status = await new ExtrasApi(bridge as any).getStrangerStatus(1);
|
||||
expect(status).toEqual({ status: 10, ext_status: 0xF142 });
|
||||
|
||||
@@ -27,7 +27,6 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
import { gunzipSync } from 'zlib';
|
||||
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
|
||||
encodeOidbEnv: vi.fn(() => new Uint8Array()),
|
||||
decodeOidbEnv: vi.fn(() => ({ body: {} })),
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg';
|
||||
import { buildApiContext, type OneBotInstanceContext } from '@snowluma/onebot/instance-context';
|
||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
vi.mock('@snowluma/protocol/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn() }));
|
||||
vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPttMsgInfo: vi.fn() }));
|
||||
vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn() }));
|
||||
|
||||
describe('forward metadata through upload and cached reads', () => {
|
||||
it.each([
|
||||
{ nested: false, enrich: false }, { nested: true, enrich: false },
|
||||
{ nested: false, enrich: true }, { nested: true, enrich: true },
|
||||
])('preserves titles and previews with nesting=$nested and enrichment=$enrich', async ({ nested, enrich }) => {
|
||||
let uploadCount = 0;
|
||||
const sendRawPacket = vi.fn(async () => ({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<SendLongMsgResp>({
|
||||
result: { resId: `metadata-${nested}-${enrich}-${++uploadCount}` },
|
||||
})),
|
||||
}));
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
bridge.apis.contacts.fetchGroupMemberList.mockResolvedValue([
|
||||
{ uin: 111, nickname: 'resolved outer', card: '' },
|
||||
]);
|
||||
const forward = new ForwardApi(bridge as any);
|
||||
const ctx = {
|
||||
selfId: 10001,
|
||||
bridge: { apis: {
|
||||
forward,
|
||||
message: { sendGroup: vi.fn(async () => ({
|
||||
messageId: 1, sequence: 2, clientSequence: 0, random: 3, timestamp: 1700000000,
|
||||
})) },
|
||||
} },
|
||||
messageStore: { findEvent: () => null, findMedia: () => null },
|
||||
cacheMessageMeta: vi.fn(),
|
||||
converterCtx: {
|
||||
selfId: 10001, imageUrlResolver: null, mediaUrlResolver: null,
|
||||
messageIdResolver: null, mediaSegmentSink: null,
|
||||
},
|
||||
} as unknown as OneBotInstanceContext;
|
||||
const api = buildApiContext(ctx);
|
||||
const text = [{ type: 'text', data: { text: 'hello' } }];
|
||||
const preview = {
|
||||
title: 'outer title', source: 'custom source', summary: 'custom summary',
|
||||
prompt: 'custom prompt', news: [{ text: 'custom preview' }],
|
||||
};
|
||||
const { forwardId } = await api.sendGroupForwardMsg(12345, [{
|
||||
type: 'node', data: {
|
||||
user_id: 111, nickname: enrich ? '' : 'outer', ...preview,
|
||||
content: nested
|
||||
? [{ type: 'node', data: { user_id: 222, nickname: 'inner', title: 'inner title', content: text } }]
|
||||
: text,
|
||||
},
|
||||
}]);
|
||||
|
||||
const first = await api.getForwardMsg(forwardId);
|
||||
expect(first[0]!.sender).toMatchObject({ title: 'outer title' });
|
||||
expect(first[0]!.sender).toMatchObject({ nickname: enrich ? 'resolved outer' : 'outer' });
|
||||
expect((await forward.fetch(forwardId!))[0]).toMatchObject(preview);
|
||||
if (nested) {
|
||||
expect((await api.getForwardMsg(`metadata-true-${enrich}-1`))[0]!.sender)
|
||||
.toMatchObject({ title: 'inner title' });
|
||||
}
|
||||
|
||||
const fetched = await forward.fetch(forwardId!);
|
||||
fetched[0]!.title = 'changed title';
|
||||
fetched[0]!.news![0]!.text = 'changed preview';
|
||||
preview.news[0]!.text = 'changed input';
|
||||
const again = await forward.fetch(forwardId!);
|
||||
expect(again[0]!.title).toBe('outer title');
|
||||
expect(again[0]!.news).toEqual([{ text: 'custom preview' }]);
|
||||
expect(sendRawPacket).toHaveBeenCalledTimes(nested ? 2 : 1);
|
||||
});
|
||||
});
|
||||
@@ -59,7 +59,7 @@ function decodeOuterLongMsg(rawBytes: Uint8Array): LongMsgResult {
|
||||
return protobuf_decode<LongMsgResult>(gunzipSync(Buffer.from(payload)));
|
||||
}
|
||||
|
||||
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string } | null {
|
||||
function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: string; app?: string; news?: Array<{ text: string }>; source?: string; summary?: string } | null {
|
||||
for (const body of msgBody) {
|
||||
const elems: Elem[] = body.body?.richText?.elems ?? [];
|
||||
for (const elem of elems) {
|
||||
@@ -74,6 +74,9 @@ function findLightAppJson(msgBody: PushMsgBody[]): { resid?: string; uniseq?: st
|
||||
app: parsed.app,
|
||||
resid: parsed.meta?.detail?.resid,
|
||||
uniseq: parsed.meta?.detail?.uniseq,
|
||||
news: parsed.meta?.detail?.news,
|
||||
source: parsed.meta?.detail?.source,
|
||||
summary: parsed.meta?.detail?.summary,
|
||||
};
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
@@ -178,4 +181,86 @@ describe('forward / nested upload wire alignment', () => {
|
||||
expect(outermost.action![2]!.actionCommand).not.toBe('MultiMsg');
|
||||
expect(outermost.action![1]!.actionCommand).not.toBe(outermost.action![2]!.actionCommand);
|
||||
});
|
||||
|
||||
it('inner forward bubble prefers caller-supplied node news over auto-generated lines', async () => {
|
||||
const responses = ['inner-res', 'outer-res'];
|
||||
const sendRawPacket = vi.fn(async () =>
|
||||
uploadResponseWithResId(responses.shift()!)) as any;
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
const customNews = [{ text: '自定义预览行 1' }, { text: '自定义预览行 2' }];
|
||||
await new ForwardApi(bridge as any).upload([{
|
||||
userUin: 111,
|
||||
nickname: 'outer',
|
||||
elements: [],
|
||||
news: customNews,
|
||||
innerForward: [
|
||||
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: '会被覆盖的正文' }] },
|
||||
],
|
||||
}]);
|
||||
|
||||
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
|
||||
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
|
||||
const preview = findLightAppJson(outerMsgBody);
|
||||
|
||||
expect(preview).not.toBeNull();
|
||||
// Caller-supplied news wins over `inner: 会被覆盖的正文`.
|
||||
expect(preview!.news).toEqual(customNews);
|
||||
});
|
||||
|
||||
it('inner forward bubble falls back to auto-generated lines when node has no news', async () => {
|
||||
const responses = ['inner-res', 'outer-res'];
|
||||
const sendRawPacket = vi.fn(async () =>
|
||||
uploadResponseWithResId(responses.shift()!)) as any;
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
await new ForwardApi(bridge as any).upload([{
|
||||
userUin: 111,
|
||||
nickname: 'outer',
|
||||
elements: [],
|
||||
// no `news` field — auto-generate from inner nodes
|
||||
innerForward: [
|
||||
{ userUin: 222, nickname: '内层说话人', elements: [{ type: 'text', text: '第一句台词' }] },
|
||||
],
|
||||
}]);
|
||||
|
||||
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
|
||||
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
|
||||
const preview = findLightAppJson(outerMsgBody);
|
||||
|
||||
expect(preview).not.toBeNull();
|
||||
expect(preview!.news).toEqual([{ text: '内层说话人: 第一句台词' }]);
|
||||
});
|
||||
|
||||
it('inner forward card prefers caller-supplied source/summary/prompt metadata', async () => {
|
||||
const responses = ['inner-res', 'outer-res'];
|
||||
const sendRawPacket = vi.fn(async () =>
|
||||
uploadResponseWithResId(responses.shift()!)) as any;
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
await new ForwardApi(bridge as any).upload([{
|
||||
userUin: 111,
|
||||
nickname: 'outer',
|
||||
elements: [],
|
||||
source: '万叶的手记',
|
||||
summary: '共 12 条剧情消息',
|
||||
prompt: '查看剧情',
|
||||
innerForward: [
|
||||
{ userUin: 222, nickname: 'inner', elements: [{ type: 'text', text: 'hi' }] },
|
||||
],
|
||||
}]);
|
||||
|
||||
const outerBytes = sendRawPacket.mock.calls[1]![1] as Uint8Array;
|
||||
const outerMsgBody = decodeOuterLongMsg(outerBytes).action![0]!.actionData!.msgBody!;
|
||||
const preview = findLightAppJson(outerMsgBody);
|
||||
|
||||
expect(preview).not.toBeNull();
|
||||
// decodeOuterLongMsg → lightApp meta.detail as built by element-builder
|
||||
expect(preview!.app).toBe('com.tencent.multimsg');
|
||||
// The plaintext preview lines of the wire bubble.
|
||||
// Caller metadata wins: source = 万叶的手记, summary used instead of
|
||||
// the auto-generated `查看N条转发消息`.
|
||||
expect(preview!.source).toBe('万叶的手记');
|
||||
expect(preview!.summary).toBe('共 12 条剧情消息');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
|
||||
encodeOidbEnv: vi.fn(() => new Uint8Array()),
|
||||
decodeOidbEnv: vi.fn(() => ({ body: {} })),
|
||||
@@ -122,6 +121,29 @@ describe('actions/forward', () => {
|
||||
])).rejects.toThrow(/missing res_id/);
|
||||
});
|
||||
|
||||
it('cached fetch after upload keeps a usable image source (#441)', async () => {
|
||||
const sendRawPacket = vi.fn(async () => uploadResponseWithResId('res-img-cache')) as any;
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
const source = 'https://cdn.example/bot-built.png';
|
||||
|
||||
const resId = await new ForwardApi(bridge as any).upload([
|
||||
{
|
||||
userUin: 10001,
|
||||
nickname: 'alice',
|
||||
elements: [{ type: 'image', url: source }],
|
||||
},
|
||||
]);
|
||||
const fetched = await new ForwardApi(bridge as any).fetch(resId);
|
||||
|
||||
expect(fetched).toHaveLength(1);
|
||||
expect(fetched[0]!.elements[0]).toMatchObject({
|
||||
type: 'image',
|
||||
url: source,
|
||||
imageUrl: source,
|
||||
});
|
||||
expect(sendRawPacket).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('fetchForwardNodes serves from cache after a successful upload (no second sendRawPacket)', async () => {
|
||||
const sendRawPacket = vi.fn(async () => uploadResponseWithResId('res-cache')) as any;
|
||||
const bridge = mockBridge({ sendRawPacket });
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbDeleteFriend,
|
||||
OidbFriendRequestAction,
|
||||
OidbSetFriendRemarkResponse,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type {
|
||||
OidbDoubtApprovalReq,
|
||||
OidbDoubtDelReq,
|
||||
OidbDoubtGetResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/doubt-buddy';
|
||||
|
||||
// Post-namespace migration: FriendApi is a thin facade over the
|
||||
// namespaces under @snowluma/protocol/oidb-services/friend. Tests assert
|
||||
// against the bridge mock's sendRawPacket directly — no need for
|
||||
// module-level bridge-oidb mocks anymore.
|
||||
import { DATALINE_UIN_PAD } from '@snowluma/protocol/dataline/device-contacts';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { FriendApi } from '../../src/bridge/apis/friend';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
@@ -65,10 +74,35 @@ describe('apis/friend', () => {
|
||||
});
|
||||
|
||||
it('setRemark uses the current set command for a non-empty remark', async () => {
|
||||
const bridge = mockBridge();
|
||||
const bridge = mockBridge({
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<OidbBase<OidbSetFriendRemarkResponse>>({
|
||||
body: {
|
||||
result: {
|
||||
target: { targetUid: 'resolved-uid', targetUin: 10001n },
|
||||
remark: 'best-friend',
|
||||
},
|
||||
},
|
||||
})),
|
||||
})),
|
||||
});
|
||||
await new FriendApi(bridge as any).setRemark(10001, 'best-friend');
|
||||
expect(bridge.sendRawPacket.mock.calls[0]![0])
|
||||
.toBe('OidbSvcTrpcTcp.0x912e_0');
|
||||
expect(bridge.identity.updateFriendRemark)
|
||||
.toHaveBeenCalledWith('resolved-uid', 10001, 'best-friend');
|
||||
});
|
||||
|
||||
it('refuses to delete or rename a my-device contact', async () => {
|
||||
const bridge = mockBridge();
|
||||
const api = new FriendApi(bridge as any);
|
||||
await expect(api.delete(DATALINE_UIN_PAD)).rejects.toThrow('cannot be deleted');
|
||||
await expect(api.setRemark(DATALINE_UIN_PAD, 'pad')).rejects.toThrow('does not support remarks');
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('setRemark uses the dedicated clear command for an empty remark', async () => {
|
||||
@@ -77,4 +111,160 @@ describe('apis/friend', () => {
|
||||
expect(bridge.sendRawPacket.mock.calls[0]![0])
|
||||
.toBe('OidbSvcTrpcTcp.0x912f_0');
|
||||
});
|
||||
|
||||
it('getDoubtRequests fills a missing uid via resolveUserUid', async () => {
|
||||
const bridge = mockBridge({
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: encodeNumericDoubtList([{ nick: 'Alice', uin: 12345n, reqTime: 1700000000n }]),
|
||||
})),
|
||||
});
|
||||
const list = await new FriendApi(bridge as any).getDoubtRequests(10);
|
||||
expect(bridge.resolveUserUid).toHaveBeenCalledWith(12345);
|
||||
expect(list).toEqual([
|
||||
{
|
||||
uid: 'resolved-uid', user_id: 12345, nick: 'Alice', source: '',
|
||||
reason: '', msg: '', group_code: '', reqTime: 1700000000,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('getDoubtRequests keeps a wire uid and does not resolve', async () => {
|
||||
const bridge = mockBridge({
|
||||
identity: { findUinByUid: vi.fn(() => 12345) } as any,
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: encodeDoubtList([
|
||||
{ uid: 'u_alice', nick: 'Alice', reqTime: 1700000000n },
|
||||
]),
|
||||
})),
|
||||
});
|
||||
const list = await new FriendApi(bridge as any).getDoubtRequests(10);
|
||||
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
|
||||
expect(list[0]?.uid).toBe('u_alice');
|
||||
expect(list[0]?.user_id).toBe(12345);
|
||||
});
|
||||
|
||||
it('getDoubtRequests keeps an empty uid when resolveUserUid fails', async () => {
|
||||
const bridge = mockBridge({
|
||||
resolveUserUid: vi.fn(async () => { throw new Error('no mapping'); }),
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: encodeNumericDoubtList([{ nick: 'Alice', uin: 12345n }]),
|
||||
})),
|
||||
});
|
||||
const captured: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => {
|
||||
if (entry.scope === 'Bridge.Friend') captured.push(entry);
|
||||
});
|
||||
try {
|
||||
const list = await new FriendApi(bridge as any).getDoubtRequests(10);
|
||||
expect(list[0]?.uid).toBe('');
|
||||
expect(list[0]?.user_id).toBe(12345);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
expect(captured.map(({ level, message }) => ({ level, message }))).toEqual([{
|
||||
level: 'warn',
|
||||
message: 'doubt-request uid resolve failed: user=12345 err=no mapping',
|
||||
}]);
|
||||
});
|
||||
|
||||
it('approveDoubtRequest resolves a digit-only flag before sending', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new FriendApi(bridge as any).approveDoubtRequest('12345');
|
||||
expect(bridge.resolveUserUid).toHaveBeenCalledWith(12345);
|
||||
const [cmd, bytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
expect(cmd).toBe('OidbSvcTrpcTcp.0xd72_0');
|
||||
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
|
||||
expect(env.body).toMatchObject({ selfUid: 'self-uid', targetUid: 'resolved-uid', field3: 0, field4: '' });
|
||||
});
|
||||
|
||||
it('approveDoubtRequest forwards a uid flag without resolving', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new FriendApi(bridge as any).approveDoubtRequest('u_abc');
|
||||
expect(bridge.resolveUserUid).not.toHaveBeenCalled();
|
||||
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
|
||||
expect(env.body).toMatchObject({ selfUid: 'self-uid', targetUid: 'u_abc' });
|
||||
});
|
||||
|
||||
it('approves a filtered stranger through Identity without requiring a shared roster', async () => {
|
||||
const identity = new IdentityService('10001', null);
|
||||
const bridge = mockBridge();
|
||||
const fetchProfile = vi.fn(async (uin: number) => ({
|
||||
uin, uid: uin === 10001 ? 'u_self' : 'u_stranger',
|
||||
}));
|
||||
identity.setFetcher({ fetchProfile: fetchProfile as any });
|
||||
bridge.identity = identity as any;
|
||||
bridge.resolveUserUid = vi.fn((uin: number) => identity.resolveUid(uin));
|
||||
try {
|
||||
await new FriendApi(bridge as any).approveDoubtRequest('12345');
|
||||
expect(fetchProfile.mock.calls.map(([uin]) => uin)).toEqual([12345, 10001]);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbDoubtApprovalReq>>(bytes);
|
||||
expect(env.body).toMatchObject({ selfUid: 'u_self', targetUid: 'u_stranger' });
|
||||
} finally {
|
||||
identity.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not send an approval when the applicant cannot be resolved', async () => {
|
||||
const bridge = mockBridge({
|
||||
resolveUserUid: vi.fn(async () => { throw new Error('applicant lookup failed'); }),
|
||||
});
|
||||
await expect(new FriendApi(bridge as any).approveDoubtRequest('12345'))
|
||||
.rejects.toThrow('applicant lookup failed');
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejectDoubtRequest resolves a digit-only flag before sending', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new FriendApi(bridge as any).rejectDoubtRequest('12345');
|
||||
expect(bridge.resolveUserUid).toHaveBeenCalledWith(12345);
|
||||
const [, bytes] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
const env = protobuf_decode<OidbBase<OidbDoubtDelReq>>(bytes);
|
||||
expect(env.body).toMatchObject({ field1: 3, inner: { uid: 'resolved-uid' } });
|
||||
});
|
||||
});
|
||||
|
||||
function encodeDoubtList(
|
||||
list: NonNullable<NonNullable<OidbDoubtGetResp['body']>['list']>,
|
||||
): Buffer {
|
||||
return Buffer.from(protobuf_encode<OidbBase<OidbDoubtGetResp>>({
|
||||
command: 0xD69,
|
||||
subCommand: 0,
|
||||
body: { status: 1, body: { list } },
|
||||
}));
|
||||
}
|
||||
|
||||
interface NumericDoubtItem {
|
||||
uin?: pb<1, uint_64>;
|
||||
nick?: pb<2, string>;
|
||||
reqTime?: pb<8, uint_64>;
|
||||
}
|
||||
interface NumericDoubtBody {
|
||||
list?: pb_repeated<1, NumericDoubtItem>;
|
||||
}
|
||||
interface NumericDoubtResponse {
|
||||
status?: pb<1, uint_32>;
|
||||
body?: pb<2, NumericDoubtBody>;
|
||||
}
|
||||
|
||||
function encodeNumericDoubtList(list: NumericDoubtItem[]): Buffer {
|
||||
return Buffer.from(protobuf_encode<OidbBase<NumericDoubtResponse>>({
|
||||
command: 0xD69,
|
||||
subCommand: 0,
|
||||
body: { status: 1, body: { list } },
|
||||
}));
|
||||
}
|
||||
@@ -1,14 +1,20 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbBase, OidbSvcTrpcTcp0x88D_0Response } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGetGroupExtResp } from '@snowluma/proto-defs/oidb-actions/group-ext';
|
||||
import type {
|
||||
Oidb0x8a0Req,
|
||||
Oidb0x8a7Resp,
|
||||
Oidb0x89a_0AddOption,
|
||||
Oidb0x89a_0Search,
|
||||
Oidb0x89a_0InvitePolicy,
|
||||
Oidb0x89a_0HistoryVisibility,
|
||||
Oidb0x89a_0MemberPermission,
|
||||
Oidb0xf16Req,
|
||||
OidbGroupDetailRequest,
|
||||
OidbGroupRequestAction,
|
||||
OidbKickMember,
|
||||
OidbKickMemberResponse,
|
||||
OidbLeaveGroup,
|
||||
OidbMuteAll,
|
||||
OidbMuteMember,
|
||||
@@ -17,11 +23,16 @@ import type {
|
||||
OidbSetAdmin,
|
||||
OidbSpecialTitle,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type {
|
||||
OidbChangeGroupCategoryTag,
|
||||
OidbGetGroupCategoryTags,
|
||||
OidbGetGroupCategoryTagsResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-category-tag';
|
||||
|
||||
// Post-namespace migration: GroupAdminApi forwards through namespaces
|
||||
// under @snowluma/protocol/oidb-services/group-admin. Tests assert
|
||||
// against bridge.sendRawPacket directly — no module-level mocks.
|
||||
import { GroupAdminApi } from '../../src/bridge/apis/group-admin';
|
||||
import { GroupAdminApi, MEMBER_PERMISSIONS_OWNER_ONLY } from '../../src/bridge/apis/group-admin';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function packResponse(body: Uint8Array) {
|
||||
@@ -31,6 +42,58 @@ function packResponse(body: Uint8Array) {
|
||||
};
|
||||
}
|
||||
|
||||
function packPrivilegeFlag(privilegeFlag?: number, ownerUid?: string) {
|
||||
return packResponse(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
|
||||
body: {
|
||||
groupInfo: {
|
||||
uin: 12345n,
|
||||
results: {
|
||||
...(privilegeFlag === undefined ? {} : { privilegeFlag }),
|
||||
...(ownerUid === undefined ? {} : { ownerUid }),
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
function packOidbFail(code: number) {
|
||||
return {
|
||||
success: false, gotResponse: true, errorCode: code, errorMessage: '',
|
||||
responseData: Buffer.alloc(0),
|
||||
};
|
||||
}
|
||||
|
||||
function packGroupFlagExt4(groupFlagExt4?: number) {
|
||||
return packResponse(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
|
||||
body: {
|
||||
groupInfo: {
|
||||
uin: 12345n,
|
||||
results: groupFlagExt4 === undefined ? {} : { groupFlagExt4 },
|
||||
},
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
function packAdminDetail(results: NonNullable<NonNullable<OidbSvcTrpcTcp0x88D_0Response['groupInfo']>['results']>) {
|
||||
return packResponse(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
|
||||
body: { groupInfo: { uin: 12345n, results } },
|
||||
}));
|
||||
}
|
||||
|
||||
function packRobotExt(robotMemberSwitch?: number, robotMemberExamine?: number) {
|
||||
return packResponse(protobuf_encode<OidbBase<OidbGetGroupExtResp>>({
|
||||
body: {
|
||||
items: [{
|
||||
groupCode: 12345n,
|
||||
ext: {
|
||||
inviteRobotMemberSwitch: robotMemberSwitch,
|
||||
inviteRobotMemberExamine: robotMemberExamine,
|
||||
},
|
||||
}],
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
describe('apis/group-admin', () => {
|
||||
it('muteMember resolves UID and dispatches 0x1253_1', async () => {
|
||||
const bridge = mockBridge();
|
||||
@@ -78,18 +141,30 @@ describe('apis/group-admin', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('kickMember rejects a server business error instead of reporting success (#298)', async () => {
|
||||
it('kickMember treats a zero per-member result as success (#413)', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
Buffer.from(
|
||||
'222008b960121be7bea4e4b8bbe697a0e6b395e8a2abe7a7bbe587bae7bea4e8818a',
|
||||
'hex',
|
||||
),
|
||||
protobuf_encode<OidbBase<OidbKickMemberResponse>>({
|
||||
body: { groupUin: 12345, results: [{ result: 0, uid: 'u_abcdefghijklmnopqrstuv' }] },
|
||||
}),
|
||||
));
|
||||
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).kickMember(12345, 67890, false),
|
||||
).rejects.toThrow('群主无法被移出群聊');
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('kickMember rejects a server business error instead of reporting success (#298)', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbKickMemberResponse>>({
|
||||
body: { groupUin: 12345, results: [{ result: 1, uid: 'u_abcdefghijklmnopqrstuv' }] },
|
||||
}),
|
||||
));
|
||||
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).kickMember(12345, 67890, false),
|
||||
).rejects.toThrow('kick member failed: result=1');
|
||||
});
|
||||
|
||||
it('kickMembers resolves each UID in parallel', async () => {
|
||||
@@ -108,15 +183,14 @@ describe('apis/group-admin', () => {
|
||||
it('kickMembers rejects the same command-level business error', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
Buffer.from(
|
||||
'222008b960121be7bea4e4b8bbe697a0e6b395e8a2abe7a7bbe587bae7bea4e8818a',
|
||||
'hex',
|
||||
),
|
||||
protobuf_encode<OidbBase<OidbKickMemberResponse>>({
|
||||
body: { groupUin: 12345, results: [{ result: 1, uid: 'u_abcdefghijklmnopqrstuv' }] },
|
||||
}),
|
||||
));
|
||||
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).kickMembers(12345, [67890], false),
|
||||
).rejects.toThrow('群主无法被移出群聊');
|
||||
).rejects.toThrow('kick members failed: result=1');
|
||||
});
|
||||
|
||||
it('leave sends 0x1097_1, emits a self group_member_leave, and forgets the group (#133)', async () => {
|
||||
@@ -185,11 +259,24 @@ describe('apis/group-admin', () => {
|
||||
|
||||
const addOptEnv = protobuf_decode<OidbBase<Oidb0x89a_0AddOption>>(bridge.sendRawPacket.mock.calls[4]![1]);
|
||||
expect(addOptEnv.body).toMatchObject({ groupUin: 1n, settings: { addType: 2 } });
|
||||
expect(addOptEnv.body?.settings?.groupQuestion ?? undefined).toBeUndefined();
|
||||
|
||||
const searchEnv = protobuf_decode<OidbBase<Oidb0x89a_0Search>>(bridge.sendRawPacket.mock.calls[5]![1]);
|
||||
expect(searchEnv.body?.groupUin).toBe(1n);
|
||||
});
|
||||
|
||||
it('setAddOption forwards question and answer for type 4', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new GroupAdminApi(bridge as any).setAddOption(12345, 4, 'how', '42');
|
||||
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0AddOption>>(
|
||||
bridge.sendRawPacket.mock.calls[0]![1],
|
||||
);
|
||||
expect(envelope.body).toMatchObject({
|
||||
groupUin: 12345n,
|
||||
settings: { addType: 4, groupQuestion: 'how', groupAnswer: '42' },
|
||||
});
|
||||
});
|
||||
|
||||
it('setAddRequest picks _1 / _2 based on filtered flag', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new GroupAdminApi(bridge as any).setAddRequest(12345, 5, 1, true, 'ok', false);
|
||||
@@ -210,6 +297,301 @@ describe('apis/group-admin', () => {
|
||||
expect(env2.body?.accept).toBe(2);
|
||||
});
|
||||
|
||||
it('setMemberInvitePolicy reads, merges, writes, and verifies the privilege flag (#334)', async () => {
|
||||
const bridge = mockBridge();
|
||||
const currentPrivilegeFlag = 0x86100001;
|
||||
const expectedPrivilegeFlag = 0x84000001;
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(currentPrivilegeFlag))
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(expectedPrivilegeFlag));
|
||||
|
||||
await new GroupAdminApi(bridge as any).setMemberInvitePolicy(12345, 'disabled');
|
||||
|
||||
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
|
||||
'OidbSvcTrpcTcp.0x88d_0',
|
||||
'OidbSvcTrpcTcp.0x89a_0',
|
||||
'OidbSvcTrpcTcp.0x88d_0',
|
||||
]);
|
||||
const env = protobuf_decode<OidbBase<Oidb0x89a_0InvitePolicy>>(
|
||||
bridge.sendRawPacket.mock.calls[1]![1],
|
||||
);
|
||||
expect(env.body).toMatchObject({
|
||||
groupUin: 12345n,
|
||||
settings: {
|
||||
appPrivilegeFlag: expectedPrivilegeFlag,
|
||||
appPrivilegeMask: 0x06100000,
|
||||
allowMemberInvite: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('setMemberInvitePolicy treats an omitted privilege flag as zero', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packPrivilegeFlag())
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(0));
|
||||
|
||||
await new GroupAdminApi(bridge as any).setMemberInvitePolicy(12345, 'require_approval');
|
||||
|
||||
const env = protobuf_decode<OidbBase<Oidb0x89a_0InvitePolicy>>(
|
||||
bridge.sendRawPacket.mock.calls[1]![1],
|
||||
);
|
||||
expect(env.body?.settings).toEqual({
|
||||
appPrivilegeFlag: 0,
|
||||
appPrivilegeMask: 0x06100000,
|
||||
allowMemberInvite: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('setMemberInvitePolicy fails when group detail has no results block', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
|
||||
body: { groupInfo: { uin: 12345n } },
|
||||
}),
|
||||
));
|
||||
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).setMemberInvitePolicy(12345, 'require_approval'),
|
||||
).rejects.toThrow(/unable to read group member invite policy before update/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('setMemberInvitePolicy rejects a successful ack when read-back does not match', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(0x80100001))
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(0x80100001));
|
||||
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).setMemberInvitePolicy(12345, 'disabled'),
|
||||
).rejects.toThrow(/was not applied/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('setNewMemberHistoryVisibility accepts a 0/1 history-visible read-back (#387)', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packGroupFlagExt4(1));
|
||||
|
||||
await new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, true);
|
||||
|
||||
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
|
||||
'OidbSvcTrpcTcp.0x89a_0',
|
||||
'OidbSvcTrpcTcp.0x88d_0',
|
||||
]);
|
||||
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0HistoryVisibility>>(
|
||||
bridge.sendRawPacket.mock.calls[0]![1],
|
||||
);
|
||||
expect(envelope.body).toMatchObject({
|
||||
groupUin: 12345n,
|
||||
settings: {
|
||||
groupFlagExt4: 0x4,
|
||||
groupFlagExt4Mask: 0x4,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('setNewMemberHistoryVisibility clears visibility when read-back is the off flag', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packGroupFlagExt4(0));
|
||||
|
||||
await new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, false);
|
||||
|
||||
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0HistoryVisibility>>(
|
||||
bridge.sendRawPacket.mock.calls[0]![1],
|
||||
);
|
||||
expect(envelope.body?.settings).toEqual({
|
||||
groupFlagExt4: 0,
|
||||
groupFlagExt4Mask: 0x4,
|
||||
});
|
||||
});
|
||||
|
||||
it('setNewMemberHistoryVisibility treats an omitted history flag as hidden', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packGroupFlagExt4());
|
||||
|
||||
await new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, false);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('setNewMemberHistoryVisibility fails when group detail has no results block', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
|
||||
body: { groupInfo: { uin: 12345n } },
|
||||
}),
|
||||
));
|
||||
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, true),
|
||||
).rejects.toThrow(/unable to read new-member history visibility after update/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('setNewMemberHistoryVisibility rejects an ack when read-back stays hidden', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packGroupFlagExt4(0));
|
||||
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, true),
|
||||
).rejects.toThrow(/was not applied/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('setMemberPermissions applies supplied switches separately and verifies the combined result (#335)', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(0x80018001))
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(0x80010000));
|
||||
|
||||
await new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
|
||||
allowMemberUploadAlbum: true,
|
||||
allowMemberTemporarySession: false,
|
||||
allowMemberCreateGroup: true,
|
||||
});
|
||||
|
||||
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
|
||||
'OidbSvcTrpcTcp.0x88d_0',
|
||||
'OidbSvcTrpcTcp.0x89a_0',
|
||||
'OidbSvcTrpcTcp.0x89a_0',
|
||||
'OidbSvcTrpcTcp.0x89a_0',
|
||||
'OidbSvcTrpcTcp.0x88d_0',
|
||||
]);
|
||||
|
||||
const writes = bridge.sendRawPacket.mock.calls.slice(1, 4).map((call) =>
|
||||
protobuf_decode<OidbBase<Oidb0x89a_0MemberPermission>>(call[1]).body?.settings,
|
||||
);
|
||||
expect(writes).toEqual([
|
||||
{ appPrivilegeFlag: 0x80018000, appPrivilegeMask: 0x1 },
|
||||
{ appPrivilegeFlag: 0x80018000, appPrivilegeMask: 0x10000 },
|
||||
{ appPrivilegeFlag: 0x80010000, appPrivilegeMask: 0x8000 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('setMemberPermissions rejects an empty update before reading group state', async () => {
|
||||
const bridge = mockBridge();
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).setMemberPermissions(12345, {}),
|
||||
).rejects.toThrow(/at least one member permission/);
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('setMemberPermissions treats an omitted privilege flag as all-allowed (#388)', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packPrivilegeFlag())
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(0));
|
||||
|
||||
await new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
|
||||
allowMemberUploadAlbum: true,
|
||||
});
|
||||
|
||||
expect(bridge.sendRawPacket.mock.calls[1]![0]).toBe('OidbSvcTrpcTcp.0x89a_0');
|
||||
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0MemberPermission>>(
|
||||
bridge.sendRawPacket.mock.calls[1]![1],
|
||||
);
|
||||
expect(envelope.subCommand ?? 0).toBe(0);
|
||||
expect(envelope.body?.settings).toEqual({
|
||||
appPrivilegeFlag: 0,
|
||||
appPrivilegeMask: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('setMemberPermissions fails when group detail has no results block', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
|
||||
body: { groupInfo: { uin: 12345n } },
|
||||
}),
|
||||
));
|
||||
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
|
||||
allowMemberUploadAlbum: true,
|
||||
}),
|
||||
).rejects.toThrow(/unable to read group member permissions before update/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('setMemberPermissions rejects a non-owner before writing (#411)', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packPrivilegeFlag(0x80000001, 'u_owner'));
|
||||
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
|
||||
allowMemberUploadAlbum: true,
|
||||
}),
|
||||
).rejects.toThrow(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x88d_0');
|
||||
});
|
||||
|
||||
it('setMemberPermissions maps a not-owner server refusal to a readable error (#411)', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(0x80000001))
|
||||
.mockResolvedValueOnce(packOidbFail(1287));
|
||||
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
|
||||
allowMemberUploadAlbum: true,
|
||||
}),
|
||||
).rejects.toThrow(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
|
||||
'OidbSvcTrpcTcp.0x88d_0',
|
||||
'OidbSvcTrpcTcp.0x89a_0',
|
||||
]);
|
||||
});
|
||||
|
||||
it('setMemberPermissions writes when the bot is the group owner', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(0x80000001, 'self-uid'))
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(0, 'self-uid'));
|
||||
|
||||
await new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
|
||||
allowMemberUploadAlbum: true,
|
||||
});
|
||||
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
|
||||
'OidbSvcTrpcTcp.0x88d_0',
|
||||
'OidbSvcTrpcTcp.0x89a_0',
|
||||
'OidbSvcTrpcTcp.0x88d_0',
|
||||
]);
|
||||
});
|
||||
|
||||
it('setMemberPermissions rejects an ack when final read-back does not match', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(0x80000001))
|
||||
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
|
||||
.mockResolvedValueOnce(packPrivilegeFlag(0x80000001));
|
||||
|
||||
await expect(
|
||||
new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
|
||||
allowMemberUploadAlbum: true,
|
||||
}),
|
||||
).rejects.toThrow(/were not applied/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('getAtAllRemain decodes the response and converts BigInts', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
@@ -225,6 +607,94 @@ describe('apis/group-admin', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('getAdminSettings composes detail and ext-info into setter-aligned fields (#385)', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === 'OidbSvcTrpcTcp.0x88d_0') {
|
||||
return packAdminDetail({
|
||||
addType: 2,
|
||||
question: 'how',
|
||||
answer: '42',
|
||||
privilegeFlag: 0x84018001,
|
||||
groupFlagExt4: 1,
|
||||
noFingerOpen: 1,
|
||||
});
|
||||
}
|
||||
if (cmd === 'OidbSvcTrpcTcp.0xef0_1') {
|
||||
return packRobotExt(1, 2);
|
||||
}
|
||||
return packResponse(Buffer.alloc(0));
|
||||
});
|
||||
|
||||
const out = await new GroupAdminApi(bridge as any).getAdminSettings(12345);
|
||||
expect(out).toEqual({
|
||||
add_type: 2,
|
||||
group_question: 'how',
|
||||
group_answer: '42',
|
||||
robot_member_switch: 1,
|
||||
robot_member_examine: 2,
|
||||
member_invite_policy: 'disabled',
|
||||
allow_member_upload_album: false,
|
||||
allow_member_temporary_session: false,
|
||||
allow_member_create_group: false,
|
||||
new_member_history_visible: true,
|
||||
no_finger_open: 1,
|
||||
no_code_finger_open: 0,
|
||||
});
|
||||
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0]).sort()).toEqual([
|
||||
'OidbSvcTrpcTcp.0x88d_0',
|
||||
'OidbSvcTrpcTcp.0xef0_1',
|
||||
]);
|
||||
const detailReq = protobuf_decode<OidbBase<OidbGroupDetailRequest>>(
|
||||
bridge.sendRawPacket.mock.calls.find((call) => call[0] === 'OidbSvcTrpcTcp.0x88d_0')![1],
|
||||
);
|
||||
expect(detailReq.body?.config?.flags?.question).toBe('');
|
||||
expect(detailReq.body?.config?.flags?.answer).toBe('');
|
||||
});
|
||||
|
||||
it('getAdminSettings treats omitted detail/ext zeros as the default values', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === 'OidbSvcTrpcTcp.0x88d_0') {
|
||||
return packAdminDetail({});
|
||||
}
|
||||
if (cmd === 'OidbSvcTrpcTcp.0xef0_1') {
|
||||
return packRobotExt();
|
||||
}
|
||||
return packResponse(Buffer.alloc(0));
|
||||
});
|
||||
|
||||
await expect(new GroupAdminApi(bridge as any).getAdminSettings(12345)).resolves.toEqual({
|
||||
add_type: 0,
|
||||
group_question: '',
|
||||
group_answer: '',
|
||||
robot_member_switch: 0,
|
||||
robot_member_examine: 0,
|
||||
member_invite_policy: 'require_approval',
|
||||
allow_member_upload_album: true,
|
||||
allow_member_temporary_session: true,
|
||||
allow_member_create_group: true,
|
||||
new_member_history_visible: false,
|
||||
no_finger_open: 0,
|
||||
no_code_finger_open: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('getAdminSettings fails when group detail has no results block', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === 'OidbSvcTrpcTcp.0x88d_0') {
|
||||
return packResponse(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
|
||||
body: { groupInfo: { uin: 12345n } },
|
||||
}));
|
||||
}
|
||||
return packRobotExt(0, 0);
|
||||
});
|
||||
|
||||
await expect(new GroupAdminApi(bridge as any).getAdminSettings(12345))
|
||||
.rejects.toThrow(/unable to read group admin settings/);
|
||||
});
|
||||
|
||||
it('getAtAllRemain falls back to zero / false when the response is empty', async () => {
|
||||
const bridge = mockBridge();
|
||||
// Empty OidbBase envelope (no body) — invokeOidb substitutes `{}`
|
||||
@@ -240,4 +710,54 @@ describe('apis/group-admin', () => {
|
||||
remain_at_all_count_for_uin: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('lists category tags and keeps category 0 on the wire', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbGetGroupCategoryTagsResp>>({
|
||||
body: { tags: [{ id: 7, name: '学习', type: 1 }, { name: '未编号' }] },
|
||||
}),
|
||||
));
|
||||
|
||||
const out = await new GroupAdminApi(bridge as any).listCategoryTags(0);
|
||||
expect(out).toEqual({
|
||||
tags: [
|
||||
{ id: 7, name: '学习', type: 1 },
|
||||
{ id: 0, name: '未编号', type: 0 },
|
||||
],
|
||||
});
|
||||
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x967c_0');
|
||||
const env = protobuf_decode<OidbBase<OidbGetGroupCategoryTags>>(bridge.sendRawPacket.mock.calls[0]![1]);
|
||||
expect(env.command).toBe(0x967C);
|
||||
expect(env.body?.groupClass).toBe(0);
|
||||
});
|
||||
|
||||
it('returns an empty tag list when the category has none', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
|
||||
protobuf_encode<OidbBase<OidbGetGroupCategoryTagsResp>>({ body: {} }),
|
||||
));
|
||||
await expect(new GroupAdminApi(bridge as any).listCategoryTags(2)).resolves.toEqual({ tags: [] });
|
||||
});
|
||||
|
||||
it('adds and removes a category tag by its name', async () => {
|
||||
const bridge = mockBridge();
|
||||
await new GroupAdminApi(bridge as any).addCategoryTag(3, ' 户外 ');
|
||||
await new GroupAdminApi(bridge as any).removeCategoryTag(3, '户外');
|
||||
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
|
||||
'OidbSvcTrpcTcp.0x967d_0',
|
||||
'OidbSvcTrpcTcp.0x967e_0',
|
||||
]);
|
||||
const added = protobuf_decode<OidbBase<OidbChangeGroupCategoryTag>>(bridge.sendRawPacket.mock.calls[0]![1]);
|
||||
expect(added.body).toMatchObject({ groupClass: 3, name: ' 户外 ' });
|
||||
const removed = protobuf_decode<OidbBase<OidbChangeGroupCategoryTag>>(bridge.sendRawPacket.mock.calls[1]![1]);
|
||||
expect(removed.body).toMatchObject({ groupClass: 3, name: '户外' });
|
||||
});
|
||||
|
||||
it('refuses an empty tag name instead of sending it', async () => {
|
||||
const bridge = mockBridge();
|
||||
await expect(new GroupAdminApi(bridge as any).addCategoryTag(1, '')).rejects.toThrow(/must not be empty/);
|
||||
await expect(new GroupAdminApi(bridge as any).removeCategoryTag(1, '')).rejects.toThrow(/must not be empty/);
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,14 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type {
|
||||
DeleteMediasRequest,
|
||||
DeleteMediasResponse,
|
||||
DoQunCommentRequest,
|
||||
DoQunCommentResponse,
|
||||
GetAlbumListResponse,
|
||||
GetMediaListResponse,
|
||||
GetQunFeedDetailRequest,
|
||||
GetQunFeedDetailResponse,
|
||||
QunFeedCellCommon,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-album';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { GroupAlbumApi } from '../../src/bridge/apis/group-album';
|
||||
@@ -437,4 +444,501 @@ describe('apis/group-album', () => {
|
||||
nextAttachInfo: 'next-video-page',
|
||||
});
|
||||
});
|
||||
|
||||
function packDeleteOk() {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<DeleteMediasResponse>({ field1: 8694 })),
|
||||
};
|
||||
}
|
||||
|
||||
function packMediaList(body: GetMediaListResponse['data']) {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<GetMediaListResponse>({ data: body })),
|
||||
};
|
||||
}
|
||||
|
||||
it('deletes a photo by lloc and includes the batch id', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
|
||||
if (cmd.endsWith('GetMediaList')) {
|
||||
return packMediaList({
|
||||
mediaList: [{ type: 1, image: { lloc: 'photo-lloc' }, batchId: 77n }],
|
||||
});
|
||||
}
|
||||
return packDeleteOk();
|
||||
});
|
||||
|
||||
await expect(new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'photo-lloc'))
|
||||
.resolves.toEqual({ success: true });
|
||||
|
||||
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
|
||||
String(call[0]).endsWith('DeleteMedias'),
|
||||
);
|
||||
expect(deleteCall?.[0]).toBe('QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias');
|
||||
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
|
||||
expect(request.body).toMatchObject({
|
||||
groupId: '12345',
|
||||
albumId: 'album-id',
|
||||
mediaIds: ['photo-lloc'],
|
||||
batchIds: ['77'],
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes a video by video id using the cover lloc', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
|
||||
if (cmd.endsWith('GetMediaList')) {
|
||||
return packMediaList({
|
||||
mediaList: [{
|
||||
type: 2,
|
||||
video: { id: 'video-id', cover: { lloc: 'cover-large' } },
|
||||
batchId: 88n,
|
||||
}],
|
||||
});
|
||||
}
|
||||
return packDeleteOk();
|
||||
});
|
||||
|
||||
await expect(new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'video-id'))
|
||||
.resolves.toEqual({ success: true });
|
||||
|
||||
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
|
||||
String(call[0]).endsWith('DeleteMedias'),
|
||||
);
|
||||
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
|
||||
expect(request.body?.mediaIds).toEqual(['cover-large']);
|
||||
expect(request.body?.batchIds).toEqual(['88']);
|
||||
});
|
||||
|
||||
it('pages the media list until the video is found', async () => {
|
||||
const bridge = mockBridge();
|
||||
let pages = 0;
|
||||
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
|
||||
if (cmd.endsWith('GetMediaList')) {
|
||||
pages += 1;
|
||||
if (pages === 1) {
|
||||
return packMediaList({
|
||||
mediaList: [{ type: 1, image: { lloc: 'other' }, batchId: 1n }],
|
||||
nextAttachInfo: 'page-2',
|
||||
});
|
||||
}
|
||||
return packMediaList({
|
||||
mediaList: [{
|
||||
type: 2,
|
||||
video: { id: 'video-id', cover: { lloc: 'cover-2' } },
|
||||
batchId: 2n,
|
||||
}],
|
||||
});
|
||||
}
|
||||
return packDeleteOk();
|
||||
});
|
||||
|
||||
await new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'video-id');
|
||||
expect(pages).toBe(2);
|
||||
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
|
||||
String(call[0]).endsWith('DeleteMedias'),
|
||||
);
|
||||
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
|
||||
expect(request.body?.mediaIds).toEqual(['cover-2']);
|
||||
expect(request.body?.batchIds).toEqual(['2']);
|
||||
});
|
||||
|
||||
it('falls back to the raw id when the media list has no match', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
|
||||
if (cmd.endsWith('GetMediaList')) {
|
||||
return packMediaList({ mediaList: [] });
|
||||
}
|
||||
return packDeleteOk();
|
||||
});
|
||||
|
||||
await new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'unknown-id');
|
||||
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
|
||||
String(call[0]).endsWith('DeleteMedias'),
|
||||
);
|
||||
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
|
||||
expect(request.body?.mediaIds).toEqual(['unknown-id']);
|
||||
expect(request.body?.batchIds ?? []).toEqual([]);
|
||||
});
|
||||
|
||||
function packCommentOk(comment: DoQunCommentResponse['comment']): ReturnType<typeof packDeleteOk> {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<DoQunCommentResponse>({
|
||||
field1: 8527,
|
||||
comment,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function packFeedDetail(
|
||||
feedId = 'official-feed-id',
|
||||
time = 1700000123n,
|
||||
extra: {
|
||||
ownerUin?: string;
|
||||
cellCommon?: Omit<QunFeedCellCommon, 'time' | 'feedId'>;
|
||||
cellMedia?: {
|
||||
medias?: Array<{ type?: number; image?: { lloc?: string }; video?: { cover?: { lloc?: string } } }>;
|
||||
albumId?: string;
|
||||
batchId?: bigint;
|
||||
};
|
||||
} = {},
|
||||
): ReturnType<typeof packDeleteOk> {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<GetQunFeedDetailResponse>({
|
||||
result: 0,
|
||||
data: {
|
||||
feed: {
|
||||
feed: {
|
||||
cellCommon: { time, feedId, ...extra.cellCommon },
|
||||
...(extra.ownerUin ? { cellUserInfo: { user: { uin: extra.ownerUin } } } : {}),
|
||||
...(extra.cellMedia ? { cellMedia: extra.cellMedia } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function packPhotoMedia(lloc = 'photo-lloc', batchId = 77n) {
|
||||
return packMediaList({
|
||||
mediaList: [{ type: 1, image: { lloc }, batchId }],
|
||||
});
|
||||
}
|
||||
|
||||
function commentMocks(
|
||||
extra: (cmd: string) => ReturnType<typeof packDeleteOk> | undefined = () => undefined,
|
||||
) {
|
||||
return async (cmd: string) => {
|
||||
const override = extra(cmd);
|
||||
if (override) return override;
|
||||
if (cmd.endsWith('GetMediaList')) return packPhotoMedia();
|
||||
if (cmd.endsWith('GetQunFeedDetail')) {
|
||||
return packFeedDetail('official-feed-id', 1700000123n, {
|
||||
ownerUin: '3119936551',
|
||||
cellCommon: {
|
||||
type: 422,
|
||||
cellId: '421_1_0_12345|album-id|77^||^421_1_0_12345|album-id|photo-lloc^||^0',
|
||||
field6: 3,
|
||||
},
|
||||
});
|
||||
}
|
||||
return packCommentOk({
|
||||
data: {
|
||||
id: 'cmt-1',
|
||||
user: { uin: '10001' },
|
||||
content: [{ type: 0, content: 'hello' }],
|
||||
time: 1700000000n,
|
||||
clientKey: 'ck',
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function commentCallBytes(bridge: ReturnType<typeof mockBridge>): Uint8Array {
|
||||
const commentCall = bridge.sendRawPacket.mock.calls.find((call) =>
|
||||
String(call[0]).endsWith('DoQunComment'),
|
||||
);
|
||||
expect(commentCall?.[0]).toBe(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
|
||||
);
|
||||
return commentCall![1] as Uint8Array;
|
||||
}
|
||||
|
||||
function commentRequestOf(bridge: ReturnType<typeof mockBridge>): DoQunCommentRequest {
|
||||
return protobuf_decode<DoQunCommentRequest>(commentCallBytes(bridge));
|
||||
}
|
||||
|
||||
function feedDetailRequestOf(bridge: ReturnType<typeof mockBridge>): GetQunFeedDetailRequest {
|
||||
const feedCall = bridge.sendRawPacket.mock.calls.find((call) =>
|
||||
String(call[0]).endsWith('GetQunFeedDetail'),
|
||||
);
|
||||
expect(feedCall?.[0]).toBe(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_feeds.FeedsReader.GetQunFeedDetail',
|
||||
);
|
||||
return protobuf_decode<GetQunFeedDetailRequest>(feedCall![1] as Uint8Array);
|
||||
}
|
||||
|
||||
it('looks up the official feed then comments with its header and slim photo cell', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(commentMocks());
|
||||
|
||||
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
|
||||
.resolves.toEqual({
|
||||
id: 'cmt-1',
|
||||
user: { uin: '10001' },
|
||||
content: [{ type: 0, content: 'hello' }],
|
||||
time: '1700000000',
|
||||
clientKey: 'ck',
|
||||
});
|
||||
|
||||
expect(feedDetailRequestOf(bridge).data).toMatchObject({
|
||||
groupId: '12345',
|
||||
commentCount: 20,
|
||||
albumId: 'album-id',
|
||||
batchId: '77',
|
||||
lloc: 'photo-lloc',
|
||||
});
|
||||
expect(feedDetailRequestOf(bridge).data?.feedId ?? '').toBe('');
|
||||
expect(feedDetailRequestOf(bridge).data?.attachInfo ?? '').toBe('');
|
||||
|
||||
const request = commentRequestOf(bridge);
|
||||
expect(request.field1).toBe(8527);
|
||||
expect(request.body).toMatchObject({
|
||||
groupId: '12345',
|
||||
field3: 2,
|
||||
reqBody: {
|
||||
field1: {
|
||||
time: 1700000123n,
|
||||
feedId: 'official-feed-id',
|
||||
},
|
||||
field2: { field1: { uin: '3119936551' } },
|
||||
field5: {
|
||||
albumId: 'album-id',
|
||||
batchId: 77n,
|
||||
medias: [{
|
||||
image: { lloc: 'photo-lloc' },
|
||||
}],
|
||||
},
|
||||
},
|
||||
field5: {
|
||||
user: { uin: '10001' },
|
||||
contents: [{ content: 'hello' }],
|
||||
},
|
||||
});
|
||||
expect(request.body?.reqBody?.field5?.medias?.[0]?.type ?? 0).toBe(0);
|
||||
expect(Buffer.from(commentCallBytes(bridge)).subarray(0, 7).toString('hex'))
|
||||
.toBe('08cf4212001a00');
|
||||
});
|
||||
|
||||
it('falls back to the media uploader when the official feed has no owner cell', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
|
||||
if (cmd.endsWith('GetMediaList')) {
|
||||
return packMediaList({
|
||||
mediaList: [{ type: 1, image: { lloc: 'photo-lloc' }, batchId: 77n, uploader: '3119936551' }],
|
||||
});
|
||||
}
|
||||
if (cmd.endsWith('GetQunFeedDetail')) return packFeedDetail();
|
||||
return undefined;
|
||||
}));
|
||||
|
||||
await new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello');
|
||||
|
||||
expect(commentRequestOf(bridge).body?.reqBody?.field2?.field1?.uin).toBe('3119936551');
|
||||
expect(commentRequestOf(bridge).body?.field5?.user?.uin).toBe('10001');
|
||||
});
|
||||
|
||||
it('copies the official feed media cell instead of a reconstructed lloc-only cell', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
|
||||
if (cmd.endsWith('GetQunFeedDetail')) {
|
||||
return packFeedDetail('official-feed-id', 1700000123n, {
|
||||
ownerUin: '3119936551',
|
||||
cellMedia: {
|
||||
albumId: 'feed-album',
|
||||
batchId: 88n,
|
||||
medias: [{
|
||||
type: 0,
|
||||
image: { lloc: 'feed-lloc' },
|
||||
}],
|
||||
},
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}));
|
||||
|
||||
await new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello');
|
||||
|
||||
expect(commentRequestOf(bridge).body?.reqBody?.field5).toMatchObject({
|
||||
albumId: 'feed-album',
|
||||
batchId: 88n,
|
||||
medias: [{
|
||||
image: { lloc: 'feed-lloc' },
|
||||
}],
|
||||
});
|
||||
});
|
||||
|
||||
it('writes only the official comment header fields even when the feed cell has extra locator data', async () => {
|
||||
const cellId = '421_1_0_964445447|album-id|2147483665^||^421_1_0_964445447|album-id|photo-lloc^||^0';
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
|
||||
if (cmd.endsWith('GetQunFeedDetail')) {
|
||||
return packFeedDetail('422_0_2147483665', 1789315793n, {
|
||||
ownerUin: '3119936551',
|
||||
cellCommon: { type: 422, cellId, field6: 3 },
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}));
|
||||
|
||||
await new GroupAlbumApi(bridge as never).comment(964445447, 'album-id', 'photo-lloc', 'hello');
|
||||
|
||||
expect(commentRequestOf(bridge).body?.reqBody?.field1).toMatchObject({
|
||||
time: 1789315793n,
|
||||
feedId: '422_0_2147483665',
|
||||
});
|
||||
expect(commentRequestOf(bridge).body?.reqBody?.field1?.type ?? 0).toBe(0);
|
||||
expect(commentRequestOf(bridge).body?.reqBody?.field1?.cellId ?? '').toBe('');
|
||||
expect(commentRequestOf(bridge).body?.reqBody?.field1?.field6 ?? 0).toBe(0);
|
||||
});
|
||||
|
||||
it('comments a video with the cover location and video media type', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
|
||||
if (cmd.endsWith('GetMediaList')) {
|
||||
return packMediaList({
|
||||
mediaList: [{
|
||||
type: 2,
|
||||
video: { id: 'video-id', cover: { lloc: 'cover-lloc' } },
|
||||
batchId: 88n,
|
||||
}],
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}));
|
||||
|
||||
await new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'video-id', 'hello');
|
||||
|
||||
expect(feedDetailRequestOf(bridge).data?.lloc).toBe('cover-lloc');
|
||||
expect(commentRequestOf(bridge).body?.reqBody?.field5).toMatchObject({
|
||||
albumId: 'album-id',
|
||||
batchId: 88n,
|
||||
medias: [{
|
||||
type: 1,
|
||||
video: { cover: { lloc: 'cover-lloc' } },
|
||||
}],
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a comment when the album media cannot be resolved', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
|
||||
if (cmd.endsWith('GetMediaList')) return packMediaList({ mediaList: [] });
|
||||
return undefined;
|
||||
}));
|
||||
|
||||
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'missing-lloc', 'hello'))
|
||||
.rejects.toThrow('comment album media error: media not found');
|
||||
expect(bridge.sendRawPacket.mock.calls.some((call) => String(call[0]).endsWith('DoQunComment')))
|
||||
.toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a comment when the official feed lookup fails', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
|
||||
if (cmd.endsWith('GetQunFeedDetail')) {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<GetQunFeedDetailResponse>({
|
||||
result: 10016,
|
||||
errorText: '服务器繁忙',
|
||||
})),
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}));
|
||||
|
||||
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
|
||||
.rejects.toThrow('fetch album feed error: retCode 10016, 服务器繁忙');
|
||||
expect(bridge.sendRawPacket.mock.calls.some((call) => String(call[0]).endsWith('DoQunComment')))
|
||||
.toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a comment when the official feed has no id', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
|
||||
if (cmd.endsWith('GetQunFeedDetail')) return packFeedDetail('');
|
||||
return undefined;
|
||||
}));
|
||||
|
||||
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
|
||||
.rejects.toThrow('comment album media error: empty feed');
|
||||
expect(bridge.sendRawPacket.mock.calls.some((call) => String(call[0]).endsWith('DoQunComment')))
|
||||
.toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a seq-echo 8527 packet that has no comment body', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
|
||||
if (cmd.endsWith('DoQunComment')) {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<DoQunCommentResponse>({ field1: 8527 })),
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}));
|
||||
|
||||
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
|
||||
.rejects.toThrow('comment album media error: empty comment');
|
||||
});
|
||||
|
||||
it('surfaces the album result code instead of treating seq 8527 as success', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
|
||||
if (cmd.endsWith('DoQunComment')) {
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<DoQunCommentResponse>({
|
||||
field1: 8527,
|
||||
result: 1001,
|
||||
errorText: 'permission denied',
|
||||
})),
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}));
|
||||
|
||||
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
|
||||
.rejects.toThrow('comment album media error: retCode 1001, permission denied');
|
||||
});
|
||||
|
||||
it('accepts a comment written directly on envelope field 4', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockImplementation(commentMocks((cmd) => {
|
||||
if (cmd.endsWith('DoQunComment')) {
|
||||
return packCommentOk({
|
||||
id: 'flat-id',
|
||||
content: [{ type: 0, content: 'hello' }],
|
||||
time: 123n,
|
||||
clientKey: 'ck',
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}));
|
||||
|
||||
await expect(new GroupAlbumApi(bridge as never).comment(12345, 'album-id', 'photo-lloc', 'hello'))
|
||||
.resolves.toMatchObject({
|
||||
id: 'flat-id',
|
||||
user: { uin: '10001' },
|
||||
content: [{ type: 0, content: 'hello' }],
|
||||
time: '123',
|
||||
clientKey: 'ck',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -327,7 +327,10 @@ describe('apis/group-file', () => {
|
||||
nickname: 'self-nick',
|
||||
findUidByUin: vi.fn(() => 'cached-uid'),
|
||||
findUinByUid: vi.fn(() => 0),
|
||||
resolveUin: vi.fn(async () => null),
|
||||
findGroupMember: vi.fn(() => null),
|
||||
updateFriendRemark: vi.fn(() => true),
|
||||
updateGroupRemark: vi.fn(() => true),
|
||||
forgetGroup: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -7,12 +7,12 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type {
|
||||
C2CRecallRequest,
|
||||
SsoReadedReportReq,
|
||||
SsoReadedReportResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', () => ({
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
|
||||
encodeOidbEnv: vi.fn(() => new Uint8Array()),
|
||||
decodeOidbEnv: vi.fn(() => ({ body: {} })),
|
||||
@@ -66,6 +66,17 @@ describe('apis/message — recall + markRead', () => {
|
||||
expect(serviceCmd).toBe('trpc.msg.msg_svc.MsgService.SsoC2CRecallMsg');
|
||||
});
|
||||
|
||||
it('recallPrivate keeps the 64-bit message id exact for any random', async () => {
|
||||
const random = 0x1234567;
|
||||
const bridge = mockBridge();
|
||||
await new MessageApi(bridge as any).recallPrivate(10001, 11110, 200, random, 1700000000);
|
||||
|
||||
const [, body] = bridge.sendRawPacket.mock.calls[0]!;
|
||||
const request = protobuf_decode<C2CRecallRequest>(body);
|
||||
expect(request.info?.random).toBe(random);
|
||||
expect(request.info?.messageId).toBe(0x0100000001234567n);
|
||||
});
|
||||
|
||||
it('probes and confirms group plus private reads in the same packets', async () => {
|
||||
const sendRawPacket = vi.fn()
|
||||
.mockResolvedValueOnce(readReportResult({
|
||||
|
||||
@@ -33,7 +33,7 @@ describe('apis/interaction', () => {
|
||||
|
||||
it('setReaction picks _1 for set and _2 for unset', async () => {
|
||||
// setReaction now forwards through the SetReaction namespace, which
|
||||
// calls bridge.sendRawPacket directly (bypassing runOidb).
|
||||
// calls bridge.sendRawPacket directly.
|
||||
const bridge = mockBridge();
|
||||
const api = new InteractionApi(bridge as any);
|
||||
await api.setReaction(12345, 99, '128516', true);
|
||||
@@ -51,20 +51,21 @@ describe('apis/interaction', () => {
|
||||
expect(cmds).toEqual(['OidbSvcTrpcTcp.0xeac_1', 'OidbSvcTrpcTcp.0xeac_2']);
|
||||
});
|
||||
|
||||
it('getEmojiLikes decodes user list, base64-encodes cookie, and reports isLast', async () => {
|
||||
it('getEmojiLikes decodes user list, returns the cookie, and reports isLast', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x9083Resp>>({
|
||||
body: {
|
||||
inner: { userInfo: [{ uin: 10001n }, { uin: 20002n }] },
|
||||
cookie: new Uint8Array([0xCA, 0xFE]),
|
||||
} as any,
|
||||
users: [{ uin: 10001n }, { uin: 20002n }],
|
||||
cookie: 'next-page',
|
||||
isLast: false,
|
||||
},
|
||||
})),
|
||||
});
|
||||
const out = await new InteractionApi(bridge as any).getEmojiLikes(12345, 99, '128516');
|
||||
expect(out.users).toEqual([{ uin: 10001 }, { uin: 20002 }]);
|
||||
expect(out.cookie).toBe(Buffer.from([0xCA, 0xFE]).toString('base64'));
|
||||
expect(out.cookie).toBe('next-page');
|
||||
expect(out.isLast).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeContext } from '../../src/bridge/bridge-context';
|
||||
import { MessageApi } from '../../src/bridge/apis/message';
|
||||
import { mockBridge } from './_helpers';
|
||||
|
||||
function sender(responseHex: string) {
|
||||
const ctx = {
|
||||
...mockBridge(),
|
||||
nextMessageRandom: () => 1234,
|
||||
sendRawPacket: vi.fn(async () => ({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(responseHex, 'hex'),
|
||||
})),
|
||||
};
|
||||
return { api: new MessageApi(ctx as unknown as BridgeContext), send: ctx.sendRawPacket };
|
||||
}
|
||||
|
||||
describe('group send receipts (#492)', () => {
|
||||
it('accepts the confirmed response from the issue log', async () => {
|
||||
const { api } = sender('080018abb3e8d506500058844a60abb3e8d506700078df0d');
|
||||
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }])).resolves.toMatchObject({
|
||||
sequence: 9476, messageId: 1234,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['missing', '080018c9b3e8d506500060c9b3e8d5067000'],
|
||||
['zero', '08005800'],
|
||||
])('rejects a %s receipt without automatically resending', async (_name, response) => {
|
||||
const { api, send } = sender(response);
|
||||
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }]))
|
||||
.rejects.toThrow('group message delivery was not confirmed');
|
||||
expect(send).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('preserves an explicit server rejection', async () => {
|
||||
const { api } = sender('0801');
|
||||
await expect(api.sendGroup(10001, [{ type: 'text', text: 'test' }]))
|
||||
.rejects.toThrow('send group message rejected: result=1');
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,9 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
CustomFaceModifyResp,
|
||||
CustomFaceMoveBody,
|
||||
FaceroamOpResp,
|
||||
GroupAvatarExtra,
|
||||
Oidb0x7edResp,
|
||||
Oidb0xe17Resp,
|
||||
@@ -9,18 +12,12 @@ import type {
|
||||
SetStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
|
||||
// `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers
|
||||
// (substituted at the call site with the inlined codec). Mocking them on
|
||||
// the module object is a no-op — proton has already inlined the call.
|
||||
// We mock `runOidb` (non-generic) to return real proton-encoded bytes
|
||||
// that the production-side codec actually decodes.
|
||||
vi.mock('@snowluma/protocol/bridge-oidb', async () => {
|
||||
const actual = await vi.importActual<typeof import('@snowluma/protocol/bridge-oidb')>(
|
||||
'@snowluma/protocol/bridge-oidb',
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
runOidb: vi.fn(async () => new Uint8Array()),
|
||||
makeOidbEnvelope: vi.fn((_oidbCmd, _subCmd, body) => ({ body })),
|
||||
};
|
||||
});
|
||||
@@ -44,8 +41,6 @@ import { mockBridge } from './_helpers';
|
||||
|
||||
describe('apis/profile', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(oidb.runOidb).mockReset();
|
||||
vi.mocked(oidb.runOidb).mockResolvedValue(new Uint8Array());
|
||||
vi.mocked(oidb.makeOidbEnvelope).mockClear();
|
||||
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
|
||||
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
|
||||
@@ -84,9 +79,30 @@ describe('apis/profile', () => {
|
||||
expect(decoded.batteryStatus ?? 0).toBe(0);
|
||||
});
|
||||
|
||||
it('setOnlineStatus accepts QQ\'s success reply even when the reply code is non-zero (#405)', async () => {
|
||||
const bridge = mockBridge();
|
||||
const respBuf = Buffer.from(protobuf_encode<SetStatusResp>({
|
||||
errCode: 1,
|
||||
errMsg: 'set status success',
|
||||
}));
|
||||
expect(respBuf.length).toBeGreaterThan(0);
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf,
|
||||
} as any);
|
||||
await expect(new ProfileApi(bridge as any).setOnlineStatus(10, 0, 100)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('setOnlineStatus accepts a success-only reply body (#405)', async () => {
|
||||
const bridge = mockBridge();
|
||||
const respBuf = Buffer.from(protobuf_encode<SetStatusResp>({ errMsg: 'set status success' }));
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf,
|
||||
} as any);
|
||||
await expect(new ProfileApi(bridge as any).setOnlineStatus(10, 0)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('setDiyOnlineStatus surfaces server errors via the same path as setOnlineStatus', async () => {
|
||||
const bridge = mockBridge();
|
||||
// Build a response that decodes to errCode != 0.
|
||||
const respBuf = Buffer.from(protobuf_encode<SetStatusResp>({ errCode: 1, errMsg: 'denied' }));
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf,
|
||||
@@ -170,22 +186,35 @@ describe('apis/profile', () => {
|
||||
|
||||
it('getProfileLike (self): resolves self UID, returns formatted favorite + vote info', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.identity.findUinByUid.mockImplementation(
|
||||
(uid: string) => uid === 'liker-uid' ? 20002 : 0,
|
||||
);
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x7edResp>>({
|
||||
body: {
|
||||
userLikeInfos: [{
|
||||
uid: 'u',
|
||||
time: 1700000000n,
|
||||
favoriteInfo: { totalCount: 5, lastTime: 1n, newCount: 1 },
|
||||
voteInfo: { totalCount: 7, newCount: 2, lastTime: 2n },
|
||||
time: 1700000000,
|
||||
favoriteInfo: { totalCount: 5, lastTime: 1, todayCount: 1 },
|
||||
voteInfo: {
|
||||
totalCount: 7,
|
||||
newCount: 2,
|
||||
newNearbyCount: 1,
|
||||
lastVisitTime: 2,
|
||||
userInfos: [{ uid: 'liker-uid', nick: '点赞者', count: 3 }],
|
||||
},
|
||||
}],
|
||||
} as any,
|
||||
})),
|
||||
});
|
||||
const out = await new ProfileApi(bridge as any).getLike();
|
||||
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x7ed_13');
|
||||
expect(out.favoriteInfo.total_count).toBe(5);
|
||||
expect(out.voteInfo.total_count).toBe(7);
|
||||
expect(out.voteInfo.userInfos).toEqual([
|
||||
expect.objectContaining({ uid: 'liker-uid', uin: 20002, nick: '点赞者', count: 3 }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('getProfileLike throws on empty result', async () => {
|
||||
@@ -197,6 +226,60 @@ describe('apis/profile', () => {
|
||||
await expect(new ProfileApi(bridge as any).getLike()).rejects.toThrow(/empty/);
|
||||
});
|
||||
|
||||
it('getProfileLike resolves uncached liker uins through Identity.resolveUin', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.identity.findUinByUid.mockReturnValue(null);
|
||||
bridge.identity.resolveUin.mockImplementation(async (uid: string) => (
|
||||
uid === 'stranger-uid' ? 30003 : null
|
||||
));
|
||||
const fetchUserProfileByUid = vi.fn();
|
||||
(bridge.apis.contacts as any).fetchUserProfileByUid = fetchUserProfileByUid;
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x7edResp>>({
|
||||
body: {
|
||||
userLikeInfos: [{
|
||||
uid: 'self-uid',
|
||||
voteInfo: { userInfos: [{ uid: 'stranger-uid', nick: '陌生点赞者' }] },
|
||||
}],
|
||||
},
|
||||
})),
|
||||
});
|
||||
|
||||
const out = await new ProfileApi(bridge as any).getLike();
|
||||
|
||||
expect(bridge.identity.resolveUin).toHaveBeenCalledOnce();
|
||||
expect(bridge.identity.resolveUin).toHaveBeenCalledWith('stranger-uid');
|
||||
expect(fetchUserProfileByUid).not.toHaveBeenCalled();
|
||||
expect(out.voteInfo.userInfos[0]?.uin).toBe(30003);
|
||||
});
|
||||
|
||||
it('getProfileLike keeps uin=0 when Identity.resolveUin misses', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.identity.findUinByUid.mockReturnValue(null);
|
||||
bridge.identity.resolveUin.mockResolvedValue(null);
|
||||
const fetchUserProfileByUid = vi.fn(async () => {
|
||||
throw new Error('profile lookup failed');
|
||||
});
|
||||
(bridge.apis.contacts as any).fetchUserProfileByUid = fetchUserProfileByUid;
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<OidbBase<Oidb0x7edResp>>({
|
||||
body: {
|
||||
userLikeInfos: [{
|
||||
uid: 'self-uid',
|
||||
voteInfo: { userInfos: [{ uid: 'stranger-uid' }] },
|
||||
}],
|
||||
},
|
||||
})),
|
||||
});
|
||||
|
||||
const out = await new ProfileApi(bridge as any).getLike();
|
||||
|
||||
expect(out.voteInfo.userInfos[0]?.uin).toBe(0);
|
||||
expect(fetchUserProfileByUid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('getUnidirectionalFriendList parses the embedded JSON body', async () => {
|
||||
const bridge = mockBridge();
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
@@ -208,4 +291,173 @@ describe('apis/profile', () => {
|
||||
const out = await new ProfileApi(bridge as any).getUnidirectionalFriendList();
|
||||
expect(out).toEqual([{ uin: 10001 }, { uin: 10002 }]);
|
||||
});
|
||||
|
||||
it('fetchCustomFaceIds slices the Faceroam list and skips the packet for count=0', async () => {
|
||||
const bridge = mockBridge();
|
||||
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
|
||||
const emojiB = '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0';
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({
|
||||
retCode: 0,
|
||||
item: { faceIds: [emojiA, emojiB] },
|
||||
})),
|
||||
} as any);
|
||||
|
||||
const api = new ProfileApi(bridge as any);
|
||||
await expect(api.fetchCustomFaceIds(1)).resolves.toEqual([emojiA]);
|
||||
expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('Faceroam.OpReq');
|
||||
|
||||
await expect(api.fetchCustomFaceIds(0)).resolves.toEqual([]);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('fetchCustomFace maps ids to image urls', async () => {
|
||||
const bridge = mockBridge();
|
||||
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
|
||||
bridge.sendRawPacket.mockResolvedValueOnce({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({
|
||||
retCode: 0,
|
||||
item: { faceIds: [emojiA] },
|
||||
})),
|
||||
} as any);
|
||||
|
||||
await expect(new ProfileApi(bridge as any).fetchCustomFace(1)).resolves.toEqual([
|
||||
`https://p.qpic.cn/qq_expression/10001/${emojiA}/0`,
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(['resource', 'md5'])('resolves a saved sticker by %s without fetching every description', async (kind) => {
|
||||
const bridge = mockBridge();
|
||||
const md5 = 'ABCDEF0123456789ABCDEF0123456789';
|
||||
const emojiId = `10001_0_0_0_${md5}_0_0`;
|
||||
bridge.sendRawPacket.mockResolvedValue({
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({ item: { faceIds: [emojiId] } })),
|
||||
} as any);
|
||||
const api = new ProfileApi(bridge as any);
|
||||
expect(await api.resolveCustomFace(kind === 'md5' ? md5.toLowerCase() : emojiId)).toEqual({
|
||||
emojiId, md5, url: `https://p.qpic.cn/qq_expression/10001/${emojiId}/0`,
|
||||
});
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
|
||||
await expect(api.resolveCustomFace('missing')).rejects.toThrow(/not in the saved sticker list/);
|
||||
await expect(api.resolveCustomFace(' ')).rejects.toThrow(/identifier is empty/);
|
||||
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('rejects a negative custom-face count before sending', async () => {
|
||||
const bridge = mockBridge();
|
||||
await expect(new ProfileApi(bridge as any).fetchCustomFaceIds(-1)).rejects.toThrow(
|
||||
/non-negative integer/,
|
||||
);
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('moveCustomFaceToFront reorders from the id list without parsing urls', async () => {
|
||||
const bridge = mockBridge();
|
||||
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
|
||||
const emojiB = '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0';
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({
|
||||
retCode: 0,
|
||||
item: { faceIds: [emojiA, emojiB] },
|
||||
})),
|
||||
} as any)
|
||||
.mockResolvedValue({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<OidbBase<CustomFaceModifyResp>>({
|
||||
body: { retCode: 0 },
|
||||
})),
|
||||
} as any);
|
||||
|
||||
await new ProfileApi(bridge as any).moveCustomFaceToFront(emojiB);
|
||||
|
||||
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
|
||||
'Faceroam.OpReq',
|
||||
'OidbSvcTrpcTcp.0x902f_1',
|
||||
'OidbSvcTrpcTcp.0x902e_1',
|
||||
]);
|
||||
const moveBody = protobuf_decode<OidbBase<CustomFaceMoveBody>>(
|
||||
bridge.sendRawPacket.mock.calls[2]![1],
|
||||
);
|
||||
expect(moveBody.body?.emojis?.map((emoji) => emoji.emojiId)).toEqual([emojiB, emojiA]);
|
||||
});
|
||||
|
||||
it('fetchCustomFaceDetails supplements the Faceroam ids with server descriptions (#333)', async () => {
|
||||
const bridge = mockBridge();
|
||||
const emojiA = '10001_0_0_0_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0_0';
|
||||
const emojiB = '10001_0_0_0_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB_0_0';
|
||||
bridge.sendRawPacket
|
||||
.mockResolvedValueOnce({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<FaceroamOpResp>({
|
||||
retCode: 0,
|
||||
item: { faceIds: [emojiA, emojiB] },
|
||||
})),
|
||||
} as any)
|
||||
.mockResolvedValueOnce({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<OidbBase<CustomFaceModifyResp>>({
|
||||
body: {
|
||||
retCode: 0,
|
||||
entries: [{ emoji: { emojiId: emojiB }, desc: '第二个表情' }],
|
||||
},
|
||||
})),
|
||||
} as any);
|
||||
|
||||
const out = await new ProfileApi(bridge as any).fetchCustomFaceDetails(2);
|
||||
|
||||
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
|
||||
'Faceroam.OpReq',
|
||||
'OidbSvcTrpcTcp.0x902e_1',
|
||||
]);
|
||||
const detailRequest = protobuf_decode<OidbBase<CustomFaceMoveBody>>(
|
||||
bridge.sendRawPacket.mock.calls[1]![1],
|
||||
);
|
||||
expect(detailRequest.body?.emojis).toEqual([
|
||||
{ emojiId: emojiA, md5: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' },
|
||||
{ emojiId: emojiB, md5: 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB' },
|
||||
]);
|
||||
expect(out).toEqual([
|
||||
{
|
||||
emojiId: emojiA,
|
||||
url: `https://p.qpic.cn/qq_expression/10001/${emojiA}/0`,
|
||||
md5: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
|
||||
desc: '',
|
||||
},
|
||||
{
|
||||
emojiId: emojiB,
|
||||
url: `https://p.qpic.cn/qq_expression/10001/${emojiB}/0`,
|
||||
md5: 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB',
|
||||
desc: '第二个表情',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('fetchCustomFaceDetails returns immediately for count=0', async () => {
|
||||
const bridge = mockBridge();
|
||||
await expect(new ProfileApi(bridge as any).fetchCustomFaceDetails(0)).resolves.toEqual([]);
|
||||
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -34,6 +34,20 @@ function runtimeTrace(entries: LogEntry[]): LogEntry[] {
|
||||
);
|
||||
}
|
||||
|
||||
function testSends(sendPacket: ReturnType<typeof vi.fn>): unknown[][] {
|
||||
return sendPacket.mock.calls.filter(([cmd]) => String(cmd).startsWith('Test.'));
|
||||
}
|
||||
|
||||
function ownershipSendTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return runtimeTrace(entries).filter((entry) => {
|
||||
if (entry.message.startsWith('bridge_sender_fact ')) return true;
|
||||
if (entry.message.startsWith('bridge_send_')) {
|
||||
return entry.message.includes('serviceCmd="Test.');
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
function packet(pid: number, uin: string): PacketInfo {
|
||||
return {
|
||||
pid,
|
||||
@@ -284,8 +298,8 @@ describe('BridgeManager PID ownership', () => {
|
||||
|
||||
expect(bridge.activePid).toBe(202);
|
||||
await bridge.sendRawPacket('Test.BeforeDisconnect', new Uint8Array([1]));
|
||||
expect(second.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(first.sendPacket).not.toHaveBeenCalled();
|
||||
expect(testSends(second.sendPacket)).toHaveLength(1);
|
||||
expect(testSends(first.sendPacket)).toHaveLength(0);
|
||||
|
||||
manager.onPidDisconnected(202);
|
||||
|
||||
@@ -293,8 +307,8 @@ describe('BridgeManager PID ownership', () => {
|
||||
expect(bridge.activePid).toBe(101);
|
||||
expect(closed).not.toHaveBeenCalled();
|
||||
await bridge.sendRawPacket('Test.AfterDisconnect', new Uint8Array([2]));
|
||||
expect(first.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(second.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(testSends(first.sendPacket)).toHaveLength(1);
|
||||
expect(testSends(second.sendPacket)).toHaveLength(1);
|
||||
|
||||
manager.onPidDisconnected(101);
|
||||
expect(manager.getSession('10001')).toBeNull();
|
||||
@@ -324,9 +338,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
manager.onPidDisconnected(101);
|
||||
await bridge.sendRawPacket('Test.NoSender', new Uint8Array([0x00, 0xff]));
|
||||
|
||||
const sender = runtimeTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('bridge_sender_fact ')
|
||||
|| entry.message.startsWith('bridge_send_'));
|
||||
const sender = ownershipSendTrace(entries);
|
||||
expect(sender.map((entry) => entry.message)).toEqual([
|
||||
'bridge_sender_fact event=selected uin="10001" pid=101 previousPid=null',
|
||||
'bridge_sender_fact event=selected uin="10001" pid=202 previousPid=101',
|
||||
@@ -381,17 +393,17 @@ describe('BridgeManager PID ownership', () => {
|
||||
expect(started).toHaveBeenCalledOnce();
|
||||
expect(bridge.activePid).toBe(101);
|
||||
await bridge.sendRawPacket('Test.Rebound', new Uint8Array([1]));
|
||||
expect(reboundFirst.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(testSends(reboundFirst.sendPacket)).toHaveLength(1);
|
||||
|
||||
manager.onPidDisconnected(101);
|
||||
expect(bridge.activePid).toBe(303);
|
||||
await bridge.sendRawPacket('Test.Fallback', new Uint8Array([2]));
|
||||
expect(third.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(testSends(third.sendPacket)).toHaveLength(1);
|
||||
|
||||
manager.onPidDisconnected(303);
|
||||
expect(bridge.activePid).toBe(202);
|
||||
await bridge.sendRawPacket('Test.SecondFallback', new Uint8Array([3]));
|
||||
expect(second.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(testSends(second.sendPacket)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('applies the same ownership transition when a packet reveals a new UIN', async () => {
|
||||
@@ -413,7 +425,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
const replacement = manager.getSession('20002')!.bridge;
|
||||
expect(replacement.hasPid(101)).toBe(true);
|
||||
await replacement.sendRawPacket('Test.AfterPacketRebind', new Uint8Array([1]));
|
||||
expect(sender.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(testSends(sender.sendPacket)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps the old UIN alive when its active PID moves and a fallback remains', async () => {
|
||||
@@ -437,12 +449,12 @@ describe('BridgeManager PID ownership', () => {
|
||||
expect(oldBridge.hasPid(202)).toBe(false);
|
||||
expect(oldBridge.activePid).toBe(101);
|
||||
await oldBridge.sendRawPacket('Test.OldUinFallback', new Uint8Array([1]));
|
||||
expect(fallback.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(testSends(fallback.sendPacket)).toHaveLength(1);
|
||||
|
||||
const newBridge = manager.getSession('20002')!.bridge;
|
||||
expect(newBridge.activePid).toBe(202);
|
||||
await newBridge.sendRawPacket('Test.NewUinSender', new Uint8Array([2]));
|
||||
expect(rebound.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(testSends(rebound.sendPacket)).toHaveLength(1);
|
||||
|
||||
manager.onPidDisconnected(202);
|
||||
expect(lifecycle).toEqual([
|
||||
@@ -485,7 +497,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
manager.onPidDisconnected(101);
|
||||
expect(targetBridge.activePid).toBe(202);
|
||||
await targetBridge.sendRawPacket('Test.ExistingTargetFallback', new Uint8Array([1]));
|
||||
expect(second.sendPacket).toHaveBeenCalledOnce();
|
||||
expect(testSends(second.sendPacket)).toHaveLength(1);
|
||||
expect(closed).toHaveBeenCalledOnce();
|
||||
|
||||
manager.onPidDisconnected(202);
|
||||
|
||||
@@ -35,28 +35,22 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo {
|
||||
};
|
||||
}
|
||||
|
||||
class RefreshingBridge extends Bridge {
|
||||
readonly memberFetches: Array<{ groupId: number; force: boolean }> = [];
|
||||
|
||||
constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) {
|
||||
super(identity);
|
||||
// `fetchGroupMemberList` moved from Bridge onto `apis.contacts`
|
||||
// under the #6 refactor — patch the method on the constructed
|
||||
// ContactsApi instance to intercept calls + record them for
|
||||
// assertions. (Direct property assignment works because the
|
||||
// method is just an own property on the Api instance, not on
|
||||
// its prototype.)
|
||||
this.apis.contacts.fetchGroupMemberList = async (
|
||||
groupId: number,
|
||||
options: { force?: boolean } = {},
|
||||
): Promise<GroupMemberInfo[]> => {
|
||||
this.memberFetches.push({ groupId, force: Boolean(options.force) });
|
||||
for (const member of this.refreshedMembers) {
|
||||
this.identity.updateGroupMember(groupId, member);
|
||||
}
|
||||
return this.refreshedMembers;
|
||||
};
|
||||
}
|
||||
function emptyProfile(uin: number, uid: string) {
|
||||
return {
|
||||
uin,
|
||||
uid,
|
||||
nickname: '',
|
||||
remark: '',
|
||||
qid: '',
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
sign: '',
|
||||
avatar: '',
|
||||
level: 0,
|
||||
qidianMasterFlag: 0,
|
||||
qidianCrewFlag: 0,
|
||||
qidianCrewFlag2: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function makePacket(): PacketInfo {
|
||||
@@ -87,11 +81,21 @@ async function waitForEvent(events: GroupMemberJoin[]): Promise<GroupMemberJoin>
|
||||
}
|
||||
|
||||
describe('Bridge group member identity refresh', () => {
|
||||
it('forces a fresh member list before dispatching an unresolved join event', async () => {
|
||||
it('resolves an unresolved join UIN via inbound profile before dispatch', async () => {
|
||||
const member = makeGroupMember(22222, 'u_new_member');
|
||||
const identity = IdentityService.memory(SELF_UIN);
|
||||
identity.rememberGroups([makeGroup()]);
|
||||
const bridge = new RefreshingBridge(identity, [member]);
|
||||
const bridge = new Bridge(identity);
|
||||
const profileFetches: string[] = [];
|
||||
const memberFetches: Array<{ groupId: number; force: boolean }> = [];
|
||||
bridge.apis.contacts.fetchUserProfileByUid = async (uid) => {
|
||||
profileFetches.push(uid);
|
||||
return emptyProfile(member.uin, uid);
|
||||
};
|
||||
bridge.apis.contacts.fetchGroupMemberList = async (groupId, options = {}) => {
|
||||
memberFetches.push({ groupId, force: Boolean(options.force) });
|
||||
return [];
|
||||
};
|
||||
const seen: GroupMemberJoin[] = [];
|
||||
|
||||
bridge.registerCmd('test.member_join', () => [{
|
||||
@@ -111,9 +115,9 @@ describe('Bridge group member identity refresh', () => {
|
||||
bridge.onPacket(makePacket());
|
||||
const event = await waitForEvent(seen);
|
||||
|
||||
expect(bridge.memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]);
|
||||
expect(profileFetches).toEqual([member.uid]);
|
||||
expect(memberFetches.some((fetch) => fetch.force)).toBe(false);
|
||||
expect(event.userUin).toBe(member.uin);
|
||||
expect(event.operatorUin).toBe(member.uin);
|
||||
});
|
||||
|
||||
it('remembers UID mappings from realtime request events', () => {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { DatalineMsgBody, DatalineTextMsg } from '@snowluma/proto-defs/dataline';
|
||||
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
|
||||
import type { FileExtra } from '@snowluma/proto-defs/message';
|
||||
import { DATALINE_UIN_PHONE } from '@snowluma/protocol/dataline/device-contacts';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-actions/media';
|
||||
|
||||
@@ -201,4 +203,62 @@ describe('Bridge private media routing', () => {
|
||||
expect(fileExtra?.file?.fileUuid).toBe('uuid-abc-123');
|
||||
expect(fileExtra?.field6 ?? undefined).toBeUndefined();
|
||||
});
|
||||
|
||||
it('sends my-device text through trans0x211 instead of ordinary c2c', async () => {
|
||||
class TestBridge extends Bridge {
|
||||
capturedBody: Uint8Array | null = null;
|
||||
|
||||
override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||
expect(serviceCmd).toBe('MessageSvc.PbSendMsg');
|
||||
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'));
|
||||
await bridge.apis.message.sendPrivate(DATALINE_UIN_PHONE, [{ type: 'text', text: 'hello phone' }]);
|
||||
|
||||
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody as Uint8Array);
|
||||
expect(request?.routingHead?.trans0x211).toMatchObject({
|
||||
ccCmd: 7,
|
||||
uid: 'u_Wcc5rknRRqRO8y5gxMD6sA',
|
||||
toUin: 10000n,
|
||||
});
|
||||
expect(request?.routingHead?.c2c ?? undefined).toBeUndefined();
|
||||
const body = protobuf_decode<DatalineMsgBody>(request!.messageBody!.msgContent as Uint8Array);
|
||||
expect(body?.subCmd).toBe(4);
|
||||
expect(body?.header).toMatchObject({
|
||||
srcAppId: 1,
|
||||
dstAppId: 1001,
|
||||
srcTerType: 1,
|
||||
dstTerType: 2,
|
||||
srcUin: 10000n,
|
||||
dstUin: 10000n,
|
||||
});
|
||||
const text = protobuf_decode<DatalineTextMsg>(body!.generic!.buf as Uint8Array);
|
||||
expect(new TextDecoder().decode(text!.items![0]!.text as Uint8Array)).toBe('hello phone');
|
||||
});
|
||||
|
||||
it('rejects non-text my-device sends', async () => {
|
||||
class TestBridge extends Bridge {
|
||||
override async sendRawPacket(): Promise<SendPacketResult> {
|
||||
throw new Error('should not send');
|
||||
}
|
||||
}
|
||||
const bridge = new TestBridge(IdentityService.memory('10000'));
|
||||
await expect(bridge.apis.message.sendPrivate(DATALINE_UIN_PHONE, [
|
||||
{ type: 'image', url: 'file:///tmp/a.png' } as any,
|
||||
])).rejects.toThrow('only accepts text');
|
||||
});
|
||||
});
|
||||
Loaded 100 of 539 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user